Upload
tranduong
View
249
Download
3
Embed Size (px)
Citation preview
Molecule DocumentationRelease 1.9.1
AUTHORS.rst
August 26, 2016
Contents
1 Ansible Support 3
2 Dependencies 52.1 Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Provider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 Quick Start 7
4 Documentation 9
5 License 11
6 Contents: 136.1 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
6.1.1 Travis CI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.2 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
6.2.1 Config file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146.2.2 Playbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.2.3 Override Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.2.4 Integration Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
6.3 Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196.3.1 Docker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196.3.2 OpenStack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206.3.3 Vagrant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
6.4 Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236.4.1 Libvirt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236.4.2 Parallels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256.4.3 Virtualbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256.4.4 VMware Fusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
6.5 Bash Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266.5.1 Linux users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266.5.2 OS X users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
6.6 Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276.6.1 Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276.6.2 Release Engineering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276.6.3 Roadmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.7 Contributing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286.7.1 Installing from source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286.7.2 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
i
6.7.3 Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296.8 Credits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.8.1 Development Leads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296.8.2 Core Committers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296.8.3 Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.9 Autodoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306.9.1 Ansible Galaxy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306.9.2 Ansible Playbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306.9.3 Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316.9.4 Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346.9.5 Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346.9.6 Molecule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356.9.7 State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356.9.8 Util . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356.9.9 Verifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7 Indices and tables 39
Python Module Index 41
ii
Molecule Documentation, Release 1.9.1
Molecule is designed to aid in the development and testing of Ansible roles including support for multiple instances,operating system distributions, virtualization providers and test frameworks.
It leverages Vagrant, Docker, and OpenStack to manage virtual machines/containers, with support for multiple Vagrantproviders (currently VirtualBox, Parallels, VMware Fusion, and Libvirt). Molecule supports Serverspec or Testinfrato run tests. Molecule uses an Ansible playbook (playbook.yml), to execute the role and its tests.
Contents 1
Molecule Documentation, Release 1.9.1
2 Contents
CHAPTER 1
Ansible Support
• 1.9.6 - Limited (Docker driver not-supported by Ansible)
• 2.0.2.0 - Supported
• 2.1.1.0 - Supported
3
Molecule Documentation, Release 1.9.1
4 Chapter 1. Ansible Support
CHAPTER 2
Dependencies
Molecule relies on several outside packages and programs to function.
• Ansible
• Rake
• Rubocop
• Serverspec
• Testinfra
2.1 Driver
Dependant upon driver used
• Docker
• Openstack
• Vagrant
2.2 Provider
Dependant upon provider used
• Libvirt
• VirtualBox
• VMware Fusion
• Parallels
5
Molecule Documentation, Release 1.9.1
6 Chapter 2. Dependencies
CHAPTER 3
Quick Start
Install molecule using pip:
$ pip install molecule
Create a new role with the docker driver:
$ molecule init foo --docker--> Initializing role foo...Successfully initialized new role in ./foo
Or add molecule to an existing role:
$ cd foo$ molecule init --docker--> Initializing molecule in current directory...Successfully initialized new role in /private/tmp
Update the role with needed functionality and tests. Now test it:
$ cd foo$ molecule test--> Destroying instances ...--> Checking playbooks syntax ...
playbook: playbook.yml--> Creating instances ...--> Creating Ansible compatible image of ubuntu:latest ...--> Creating Ansible compatible image of ubuntu:latest ...Creating container foo-01 with base image ubuntu:latest ...Container created.Creating container foo-02 with base image ubuntu:latest ...Container created.--> Starting Ansible Run ...
PLAY [all] *********************************************************************
TASK [setup] *******************************************************************ok: [foo-01]ok: [foo-02]
PLAY RECAP *********************************************************************foo-01 : ok=1 changed=0 unreachable=0 failed=0foo-02 : ok=1 changed=0 unreachable=0 failed=0
7
Molecule Documentation, Release 1.9.1
--> Idempotence test in progress (can take a few minutes)...--> Starting Ansible Run ...Idempotence test passed.--> Executing testinfra tests found in tests/.============================= test session starts ==============================platform darwin -- Python 2.7.11, pytest-2.9.2, py-1.4.31, pluggy-0.3.1rootdir: /private/tmp/foo/tests, inifile:plugins: mock-1.1, xdist-1.14, testinfra-1.3.1collected 2 itemss
tests/test_default.py ..
=========================== 2 passed in 1.11 seconds ===========================No serverspec tests found in spec/.--> Destroying instances ...Stopping container foo-01 ...Removed container foo-01.Stopping container foo-02 ...Removed container foo-02.
8 Chapter 3. Quick Start
CHAPTER 4
Documentation
http://molecule.readthedocs.org/en/latest/
9
Molecule Documentation, Release 1.9.1
10 Chapter 4. Documentation
CHAPTER 5
License
MIT
The logo is licensed under the Creative Commons NoDerivatives 4.0 License. If you have some other use in mind,contact us.
11
Molecule Documentation, Release 1.9.1
12 Chapter 5. License
CHAPTER 6
Contents:
6.1 Usage
In the contexts of operations and virtualization, the word ‘provision’ tends to refer to the initial creation of machinesby allocating (hardware) resources; in contrast, in the context of configuration management (and in vagrant), ‘provi-sioning’ refers to taking the (virtual) machine from an initial boot to having run the configuration management system(Ansible, Salt, Puppet, Chef, CFEngine or just shell). Molecule uses the term ‘converge’ (as does Test Kitchen) torefer to this latter meaning of ‘provisioning’ (i.e. “Run Ansible on the new test VM”).
It is very simple to run tests using the molecule command from the working directory of your role.
See molecule --help
The exact sequence of commands run during the test command can be configured in the test[’sequence’] configoption.
molecule:test:sequence:
- destroy- syntax- create- converge- idempotence- verify
The test command will destroy the instance(s) after successful completion of all test sequences. The test commandsupports a --destroy argument that will accept the values always (default), never, and passing. Use these to tunethe behavior for various use cases.
For example, --destroy=always might be useful when using molecule for CI/CD.
6.1.1 Travis CI
Travis is an excellent CI platform for testing Ansible roles. With the docker driver, molecule can easily be used to testmultiple configurations on Travis. Here is an example of a .travis.yml that is used to test a role named foo1. Inthis example, the role foo1 uses the docker driver and is assumed to be in the directory roledir/foo1 with theproper molecule.yml.
sudo: required
language: python
13
Molecule Documentation, Release 1.9.1
services:- docker
before_install:- sudo apt-get -qq update- sudo apt-get install -o Dpkg::Options::="--force-confold" --force-yes -y docker-engine
install:- pip install molecule
script:- cd roledir/foo1- molecule test
6.2 Configuration
Molecule attempts to pick sane default configuration options (set internally), however it’s also possible to overrideconfiguration, for example in ~/.config/molecule/config.yml.
6.2.1 Config file
This file (molecule.yml), located in the role directory, contains all the molecule-specific information for the role inthe directory in which it’s located. It allows you to configure how molecule, vagrant and ansible will behave. Thisinformation is contained in 3 top level YAML sections: molecule, ansible and vagrant.
Example
---molecule:
# directories to ignore when doing trailing whitespace checks on files during verify commandignore_paths:- .git- .vagrant- .molecule
# directory to look for serverspec testsserverspec_dir: spec
# directory to look for testinfra teststestinfra_dir: tests
# directory in CWD to place all temp files, etc.molecule_dir: .molecule
# where temporary state will be stored (lives under molecule_dir)state_file: state.yml
# name of temporary vagrantfile created during runs (lives under molecule_dir)vagrantfile_file: vagrantfilerakefile_file: rakefile
# template files to load when creating corresponding temporary files# this would be a good place to specify your own ansible.cfg template, for example
14 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
vagrantfile_template: vagrantfile.j2ansible_config_template: ansible.cfg.j2rakefile_template: rakefile.j2
# default provider to use when no --provider flag is specified# comment this out to default to the first in the provider list# default_provider: virtualbox
# default platform to use when no --platform flag is specified# comment this out to default to the first in the platform list# default_platform: rhel-7
# ssh arguments passed to molecule login commandraw_ssh_args:- -o StrictHostKeyChecking=no- -o UserKnownHostsFile=/dev/null
test:# sequence of commands to run when performing `molecule test`sequence:
- destroy- syntax- create- converge- idempotence- verify
init:# default platform to populate when doing `molecule init`platform:
name: trusty64box: trusty64box_url: https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/14.04/providers/virtualbox.boxbox_version: 0.1.0
# templates to use when creating files during `molecule init`templates:
molecule: molecule.yml.j2molecule_docker: molecule_docker.yml.j2molecule_openstack: molecule_openstack.yml.j2playbook: playbook.yml.j2test_default: test_default.py.j2
# defaults passed to ansible-playbookansible:
timeout: 30sudo: Truesudo_user: Falseask_sudo_pass: Falseask_vault_pass: Falsevault_password_file: Falselimit: allverbose: Falsediff: Truetags: Falsehost_key_checking: Falseraw_ssh_args:- -o UserKnownHostsFile=/dev/null- -o IdentitiesOnly=yes
6.2. Configuration 15
Molecule Documentation, Release 1.9.1
- -o ControlMaster=auto- -o ControlPersist=60s
galaxy: {}inventory_file: ansible_inventoryconfig_file: ansible.cfgplaybook: playbook.yml
testinfra: {}
Molecule Section
The molecule section allows you to override molecule defaults. This is is the most specific setting for molecule andwill override the contents of all other config files. This is where you give molecule role-specific behavior.
molecule:raw_ssh_args:- -o StrictHostKeyChecking=false- -o UserKnownHostsFile=/dev/null
Ansible Section
In the ansible section, you can configure flags exactly as they’re passed to ansible-playbook. Please note, however, thatcommands that normally contain a hyphen (-) will need to be replaced with an underscore (_) to remain compatiblewith YAML.
Values set to False will NOT be passed to ansible-playbook, but rather will be skipped entirely. An example ansiblesection of molecule.yml may look something like this:
ansible:inventory_file: ../../inventory/diff: Falsesudo: Truevault_password_file: ~/.vault
As you can see, the names of these values correspond to what the underlying ansible-playbook accepts. As such, asthe functionality of Ansible grows, support for new CLI options will be supported simply by adding its name: valuecombination to the ansible section of your configuration.
The ansible section also supports a few values that aren’t passed to ansible-playbook in this way, but rather are passedas environment variables. There are only a few currently in use.
ansible:config_file: /path/to/your/ansible.cfgplaybook: /path/to/some/other_playbook.ymlhost_key_checking: Falseraw_ssh_args:- -o UserKnownHostsFile=/dev/null- -o IdentitiesOnly=yes- -o ControlMaster=auto- -o ControlPersist=60s
raw_env_vars:ANSIBLE_ACTION_PLUGINS: ../plugins
The raw_env_vars section allows you to pass arbitrary environment variables to ansible-playbook. This can be useful,for example, if you want to do a role level override of a value normally found in ansible.cfg.
16 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
Host/Group Vars
Some playbooks require hosts/groups to have certain variables set. If you are in this situation - simply add the host_varsand/or group_vars to the ansible section. For example,
ansible:playbook: playbook.ymlgroup_vars:foo1:
- test: keyvar2: value
foo2:- test: key
var: valuehost_vars:foo1-01:
- set_this_value: True
This example will set the variables for the ansible groups foo1 and foo2. For hosts foo1-01 the value set_this_valuewill be set to True.
Role Requirements
Testing roles may rely upon additional roles. In this case adding requirements_file to the ansible section, willcause molecule to download roles using Ansible Galaxy.
Additional options can be passed to ansible-galaxy through the galaxy option under the ansible section. Anyoption set in this section will override the defaults.
ansible:requirements_file: requirements.ymlgalaxy:
ignore-certs: Trueignore-errors: True
Vagrant Section
The other part of the configuration is the vagrant section. This is where you will define what instances will be created,and how they will be configured. Under the hood, molecule creates a Vagrantfile from a template and populates it withthe data you specify in this config.
Because it’s impossible to support every Vagrant option, there are two places where you can specify raw_config_args.The first is in the root of the vagrant block, and this can be used for Vagrant options that are not supported explicitlyby Molecule currently - like configuring port forwarding to a guest VM from your local machine.
The second place raw_config_args can be defined is within a specific instance within the instances block. This allowsyou to define instance-specific settings such as network interfaces with a config more complicated than the interfacessection allows for.
Note: You can specify an options section for an instance. Currently, the only key supported here is ap-pend_platform_to_hostname. By setting this to ‘no’ the platform name won’t be appended to hostnames automatically,which is the default. So, for example, an instance will simply be named vagrant-01 instead of vagrant-01-rhel-7.
See Vagrant vagrant_driver_usage
6.2. Configuration 17
Molecule Documentation, Release 1.9.1
Docker Section
Molecule supports docker too. If you want to test roles on containers, remove the vagrant option or initialize yourrole with the --docker flag. Docker, of course must be installed onto your system. The daemon does not need tobe running on your machine. Molecule will simply pull the environment variables from your docker client. Also, theAnsible connection must be set to docker with user root.
In order to use the docker driver, the image used must have at least one of the following:
• apt-get/yum
• python 2.5+
• python 2.4 with python-simplejson
See Docker Usage
OpenStack Section
See OpenStack openstack_driver_usage
Testinfra Section
In the testinfra section, you can configure flags exactly as they’re passed to testinfra. Some flags, such asansible-inventory, connection and hosts, are already set by Molecule. Any flag set in this section willoverride the defaults. See more details on using testinfra’s command line arguments.
testinfra:n: 1
Note: Testinfra is based on pytest, so additional pytest arguments can be passed through it.
6.2.2 Playbook
In general, your playbook.yml shouldn’t require anything specific to molecule. Rather, it should contain the logic youwould like to apply in order to test this particular role.
- hosts: allroles:- role: demo.molecule
6.2.3 Override Configuration
1. project config
2. local config (~/.config/molecule/config.yml)
3. default config (molecule.yml)
The merge order is default -> local -> project, meaning that elements at the top of the above list will be merged last,and have greater precedence than elements at the bottom of the list.
18 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
6.2.4 Integration Testing
Molecule supports testing using both Serverspec and Testinfra. Tests located in the spec/ directory will be run byserverspec and tests located in the tests/ directory will be run by testinfra. Both of these directories can be changedas molecule config options. Molecule will run serverspec and testinfra if both directories are present.
Testinfra
Testinfra requires the following structure:
role_name/-- ...-- tests/
-- test_*.py
Serverspec
Serverspec requires the following structure:
role_name/-- ...-- spec/
-- spec_helper.rb-- default_spec.rb
When using serverspec, it’s possible to target tests at the following levels: all instances, specific groups, specificinstances.
All files matching the pattern spec/*_spec.rb will be run against every instance.
Tests located in spec/hosts/<hostname>/*_spec.rb will be run against the specific instance with the givenhostname.
Tests located in spec/groups/<groupname>/*_spec.rb will be run against the instances in the given group.
Please note, this behavior only pertains to inventory generated by Molecule. Specifying outside inventory files orscripts will disable this functionality.
6.3 Drivers
Molecule uses drivers to bring up Ansible ready hosts to operate on. Currently, Molecule supports three drivers:Vagrant, Docker, and OpenStack.
The driver can set when using init command or through the molecule.yml file.
6.3.1 Docker
The docker driver is compatible with any image that has python installed. Molecule will automatically install pythonfor images with the yum or apt-get package tools. A new docker image will be built with the prefix molecule_local toseparate it from the other images on your system.
The image being used is responsible for implementing the command to execute on docker run.
Below is an example of a molecule.yml file using two containers foo-01 and foo-02. foo-01 is running thelatest image of ubuntu and foo-02 is running the latest image of ubuntu from a custom registry.
6.3. Drivers 19
Molecule Documentation, Release 1.9.1
Options
• name - name of the container
• ansible_groups - groups the container belongs to in Ansible
• image - name of the image
• image_version - version of the image
• privileged - (OPTIONAL) whether or not to run the container in privileged mode (boolean)
• registry - (OPTIONAL) the registry to obtain the image
• install_python - (default=yes) install python onto the image being used
• port_bindings - (OPTIONAL) the port mapping between the Docker host and the container. This is passedto docker-py as the port_bindings host config.
• volume_mounts - (OPTIONAL) the volume mappings between the Docker host and the container.
• command - (OPTIONAL) the command to launch the container with
The available param for the docker driver itself is:
• install_python - (default=yes) install python onto all images for all containers
Usage
---docker:
containers:- name: foo-01
ansible_groups:- group1image: ubuntuimage_version: latestprivileged: Trueport_bindings:
80: 80- name: foo-02
ansible_groups:- group2
image: ubuntuimage_version: '14.04'registry: testhost:5323volume_mounts:
- '/this/volume:/to/this:rw'command: '/bin/sh'
Note: numeric versions need to be put in quotes. If the image version tag is not a number, it does not need to be inquotes.
A specific registry can also be defined with the registry option in the container. When accessing a private registry,ensure your docker client is logged into whichever registry you are trying to access.
6.3.2 OpenStack
The openstack driver will create instances in your openstack service. The environment variables required to use thisdriver can be found in the RC file provided on your openstack site.
20 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
Options
• name - name of the openstack instance
• image - openstack image to use for instance
• flavor - openstack flavor to use for instance
• sshuser - user to access ssh with
• ansible_groups - groups the instance belongs to in ansible
• security_groups - security groups the instance belongs to in openstack
The keypair and keyfile options must also be given to specify the keypair to use when accessing your openstackservice. Usage can be seen in the example below.
Usage
---openstack:
keypair: KeyNamekeyfile: ~/.ssh/id_rsainstances:- name: my_instance
image: 'CentOS 7'flavor: m1.xlargesshuser: centosansible_groups:
- ansiblegroup
6.3.3 Vagrant
The vagrant driver performs in a similar manner to the docker driver. Except for using virtual machines instead ofcontainers. Each instance of a vagrantbox are defined inside of an instance with similar options to docker. The driveris set to vagrant by default if the --docker flag is not passed when molecule init is run.
Options
• name - name of the vagrant box
• ansible_groups - groups the instance belongs to in ansible
• interfaces - network inferfaces (see usage)
• options - Vagrant options supported by Molecule
• raw_config_args - Vagrant options unsupported by Molecule
Usage
This is an example of a set of vagrant instance - for information on specifying the platform/provider, see Providers.
---instances:
- name: vagrant-test-01ansible_groups:
6.3. Drivers 21
Molecule Documentation, Release 1.9.1
- group_1interfaces:
- network_name: private_networktype: dhcpauto_config: true
options:append_platform_to_hostname: no
- name: vagrant-test-02ansible_groups:
- group_2interfaces:
- network_name: private_networktype: dhcpauto_config: true
options:append_platform_to_hostname: no
Comprehensive Usage
---vagrant:
raw_config_args:- "ssh.insert_key = false"- "vm.network 'forwarded_port', guest: 80, host: 8080"
platforms:- name: trusty64
box: trusty64box_url: https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/14.04/providers/virtualbox.box
providers:- name: virtualbox
type: virtualboxoptions:
memory: 512cpus: 2
instances:- name: vagrant-01
ansible_groups:- group_1- group_2
interfaces:- network_name: private_networktype: dhcpauto_config: true
- network_name: private_networktype: staticip: 192.168.0.1auto_config: true
options:append_platform_to_hostname: no
raw_config_args:- "vm.network 'private_network', type: 'dhcp', auto_config: false"
A box_url is not required - if the vagrant box is available on hashicorp, it can be specified in box. For example, thesame image in the previous example can be invoked like so:
22 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
platforms:- name: trusty64box: ubuntu/trusty64
6.4 Providers
Vagrant uses provider plugins to support managing machines onvarious virtualization platforms. There areworkstation-local provider plugins such as VirtualBox and VMware Fusion/Workstation and cloud-based providerssuch as AWS/EC2.
Molecule can be configured to give provider-specific configuration data in molecule.yml - in the vagrant.providershash. Necessarily, the configuration requirements/options are much more complicated for cloud-based providers thanthey are for workstation-local virtualization provider plugins.
6.4.1 Libvirt
The libvirt toolkit is known to work with the vagrant-libvirt provider plugin. But before installing this plugin you needto have libvirt installed (if you plan to run the tests on your local machine). Some users have reported dependencyissues while installing vagrant-libvirt, so it is highly recommended to check this section. You also need a vagrantcompatible version installed on your machine (note that, not all versions are supported. Check the vagrant-libvirtdocumentation).
You can install the vagrant-libvirt plugin with:
$ vagrant plugin install vagrant-libvirt
Molecule allows to specify provider options and domain specific options within the molecule.yml file, in the providerssection.
Options
These options are described in the provider options section of the vagrant-libvirt project site:
Although it should work without any configuration for most people, this provider exposes quite a few provider-specificconfiguration options. The following options allow you to configure how vagrant-libvirt connects to libvirt, and areused to generate the libvirt connection URI:
• driver - A hypervisor name to access. For now only kvm and qemu are supported.
• host - The name of the server, where libvirtd is running. You want to use this option when creating the VM ina remote host.
• connect_via_ssh - If use ssh tunnel to connect to Libvirt. Absolutely needed to access libvirt on remotehost. It will not be able to get the IP address of a started VM otherwise.
• username - Username and password to access Libvirt.
• password - Password to access Libvirt.
• id_ssh_key_file - If not nil, uses this ssh private key to access Libvirt. Default is $HOME/.ssh/id_rsa.Prepends $HOME/.ssh/ if no directory.
• socket - Path to the libvirt unix socket
• uri - For advanced usage. Directly specifies what libvirt connection URI vagrant-libvirt should use. Overridesall other connection configuration options.
6.4. Providers 23
Molecule Documentation, Release 1.9.1
Connection-independent options:
• storage_pool_name - Libvirt storage pool name, where box image and instance snapshots will be stored.
Domain Specific Options
• disk_bus - The type of disk device to emulate. Defaults to virtio if not set.
• nic_model_type - parameter specifies the model of the network adapter when you create a domain value bydefault virtio KVM believe possible values, see the nics documentation.
• memory - Amount of memory in MBytes. Defaults to 512 if not set.
• cpus - Number of virtual cpus. Defaults to 2 if not set.
• nested - Enable nested virtualization. Default is false.
• cpu_mode - CPU emulation mode. Defaults to ‘host-model’ if not set. Allowed values: host-model, host-passthrough.
• Other options - Such as graphics_port, suspend_mode, boot, etc. Please, take a look at the vagrant-libvirtdocumentation for seeing all available options.
Usage
All libvirt specific options(such as the one above, provider specific and domain options) must be specified inthe providers section. Nevertheless, other options such as synced or network settings should be added to theraw_config_args, as they are vagrant generic parameters. Note that you can use special libvirt parameters such as“libvirt__tunnel_type”, as it is shown in the example below.
Please, refer to the vagrant-libvirt documentation for getting a better understanding of all available options.
---vagrant:
raw_config_args:- "ssh.pty = true"- "vm.network :private_network, :libvirt__dhcp_enabled=> false ,:libvirt__tunnel_type => 'server', :libvirt__tunnel_port => '11111'"
platforms:- name: rhel6
box: rhel/rhel-6- name: rhel7
box: rhel/rhel-7- name: centos7
box: centos/7
providers:- name: libvirt
type: libvirtoptions:
memory: 1024cpus: 2# There are two available drivers: kvm and qemu.# Refer to the vagrant-libvirt docs for more info.driver: kvmvideo_type: vga
24 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
6.4.2 Parallels
---vagrant:
platforms:- name: ubuntu
box: ubuntu/trusty32
providers:- name: parallels
type: parallelsoptions:
memory: 512
6.4.3 Virtualbox
---vagrant:
platforms:- name: ubuntu
box: ubuntu/trusty32
providers:- name: virtualbox
type: virtualboxoptions:
memory: 512
Comprehensive Usage
This example is far more extensive than you likely need and it demonstrateslots of options that you probably don’twant to set.
---ansible:
playbook: playbook.ymlsudo: Truesudo_user: Falseverbose: vvvv
vagrant:raw_config_args:- "ssh.insert_key = false"
platforms:- name: ubuntu
box: ubuntu/precise32- name: trusty64
box: trusty64box_version: "~> 20151130.0.0"box_url: https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/14.04/providers/virtualbox.box
- name: rhel-7box: rhel/rhel-7
providers:- name: virtualbox
6.4. Providers 25
Molecule Documentation, Release 1.9.1
type: virtualboxoptions:
memory: 512
Other Notes
• box_version, defaults to ‘=’, can include an constraints like ‘<, >, >=, <=, ~.’ as listed in the Versioning docs.
6.4.4 VMware Fusion
---vagrant:
platforms:- name: ubuntu
box: ubuntu/trusty32
providers:- name: vmware_fusion
type: vmware_fusionoptions:
memory: 512
6.5 Bash Completion
A bash completion script is provided in the asset directory. It auto-completes the subcommands, options and dynamicarguments such as platform, providers, and hosts.
6.5.1 Linux users
The script will install globally in etc/bash_completion.d.
6.5.2 OS X users
For OS X user, you must do the following to enable the script:
$ USER_BASH_COMPLETION_DIR=~/bash_completion.d$ mkdir -p "${USER_BASH_COMPLETION_DIR}"$ wget -O "${USER_BASH_COMPLETION_DIR}/molecule" \
https://github.com/metacloud/molecule/blob/master/asset/bash_completion/molecule.bash-completion.sh
and in ~/.bash_profile, add the following:
if [ -d ~/bash_completion.d ]; then. ~/bash_completion.d/*
fi
if you are using brew you can use ${BASH_COMPLETION_DIR} instead of${USER_BASH_COMPLETION_DIR}.
26 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
6.6 Development
• Please read the Contributing guidelines.
6.6.1 Branches
• The master branch is stable. Major changes should be performed elsewhere.
6.6.2 Release Engineering
Pre-release
• Update version in doc/source/conf.py.
• Edit the CHANGELOG.
• Ensure tox tests pass.
Release
Tag the release and push to github.com
$ git tag -a 1.0.5 -m "Version 1.0.5"$ git push origin 1.0.5
Upload to PyPI
• Install twine using pip.
• You will require credentials to upload to PyPI. Create a ~/.pypirc:
[distutils]index-servers = pypi[pypi]repository = https://pypi.python.org/pypi/moleculeusername = XXXXXXXpassword = XXXXXXX
• Upload to PyPI.
$ cd /path/to/molecule$ rm -rf dist/$ python setup.py sdist bdist_wheel$ twine upload dist/*
Update Molecule.ReadTheDocs.org
Docs are updated through a github webhook.
6.6. Development 27
Molecule Documentation, Release 1.9.1
Post-release
• Comment/close any relevant Issues.
• Announce the release.
6.6.3 Roadmap
• See Issues on Github.com.
6.7 Contributing
• We are interested in various different kinds of improvement for Molecule; please feel free to raise an Issue ifyou would like to work on something major to ensure efficient collaboration and avoid duplicate effort.
• Create a topic branch from where you want to base your work.
• Check for unnecessary whitespace with git diff --check before committing.
• Make sure you have added tests for your changes.
• Run all the tests to ensure nothing else was accidentally broken.
• Reformat the code by following the formatting section below.
• Submit a pull request.
6.7.1 Installing from source
Due to the rapid pace of development on this tool, you might want to install it in “development” mode so that newupdates can be obtained by simply doing a git pull in the repository’s directory.
$ cd /path/to/repos$ git clone [email protected]:metacloud/molecule.git$ cd molecule$ sudo python setup.py develop
There is also a pip pattern for development mode:
$ cd /path/to/repos$ git clone [email protected]:metacloud/molecule.git$ pip install -U -e .
6.7.2 Testing
Test Dependencies
Install serverspec dependencies:
$ bundle install
28 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
Unit
Unit tests are invoked by Tox.
$ tox -l$ py{27}-ansible{19,20,21}-unit
Functional
Functional tests are invoked by Tox.
$ tox -l$ py{27}-ansible{19,20,21}-functional
6.7.3 Formatting
The formatting is done using YAPF.
From the root for the project, run:
$ tox -e syntax
6.8 Credits
6.8.1 Development Leads
• John Dewey <[email protected]>
6.8.2 Core Committers
• Abel Lopez <[email protected]>
• Adam Brown <[email protected]>
• Duncan Hutty <[email protected]>
• Erik Nadel <[email protected]>
• Rémy Greinhofer <[email protected]>
6.8.3 Contributors
$ git shortlog -s | cut -c8-
6.8. Credits 29
Molecule Documentation, Release 1.9.1
6.9 Autodoc
6.9.1 Ansible Galaxy
class molecule.ansible_galaxy.AnsibleGalaxy(config, _env=None, _out=<bound methodLogger.info of <logging.Logger object at0x7ff6f38c3cd0>>, _err=<bound methodLogger.error of <logging.Logger object at0x7ff6f38c3cd0>>)
add_env_arg(name, value)Adds argument to environment passed to ansible-galaxy
Parameters
• name – Name of argument to be added
• value – Value of argument to be added
Returns None
bake()Bake ansible-galaxy command so it’s ready to execute.
Returns None
execute()Executes ansible-galaxy install
Returns sh.stdout on success, else None
Returns None
6.9.2 Ansible Playbook
class molecule.ansible_playbook.AnsiblePlaybook(args, _env=None, _out=<bound methodLogger.info of <logging.Logger object at0x7ff6f38ef950>>, _err=<bound methodLogger.error of <logging.Logger object at0x7ff6f38ef950>>)
add_cli_arg(name, value)Adds argument to CLI passed to ansible-playbook
Parameters
• name – Name of argument to be added
• value – Value of argument to be added
Returns None
add_env_arg(name, value)Adds argument to environment passed to ansible-playbook
Parameters
• name – Name of argument to be added
• value – Value of argument to be added
Returns None
30 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
bake()Bake ansible-playbook command so it’s ready to execute.
Returns None
execute(hide_errors=False)Executes ansible-playbook
Returns exit code if any, output of command as string
parse_arg(name, value)Parses argument and adds to CLI or environment
Parameters
• name – Name of argument to be added
• value – Value of argument to be added
Returns None
remove_cli_arg(name)Removes CLI argument
Parameters name – Key name of CLI argument to remove
Returns None
remove_env_arg(name)Removes environment argument
Parameters name – Key name of environment argument to remove
Returns None
6.9.3 Command
Converge
class molecule.command.converge.Converge(command_args, args, molecule=False)Provisions all instances defined in molecule.yml.
Usage: converge [–platform=<platform>] [–provider=<provider>] [–tags=<tag1,tag2>...] [–debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--tags=<tag1,tag2> comma separated list of ansible tags to target
--debug get more detail
execute(idempotent=False, create_instances=True, create_inventory=True, exit=True,hide_errors=True)
Parameters
• idempotent – Optionally provision servers quietly so output can be parsed for idempo-tence
• create_inventory – Toggle inventory creation
• create_instances – Toggle instance creation
6.9. Autodoc 31
Molecule Documentation, Release 1.9.1
Returns Provisioning output
Create
class molecule.command.create.Create(command_args, args, molecule=False)Creates all instances defined in molecule.yml.
Usage: create [–platform=<platform>] [–provider=<provider>] [–debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--debug get more detail
Destroy
class molecule.command.destroy.Destroy(command_args, args, molecule=False)Destroys all instances created by molecule.
Usage: destroy [–platform=<platform>] [–provider=<provider>] [–debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--debug get more detail
execute(exit=True)Removes template files. Clears state file of all info (default platform).
Returns None
Idempotence
class molecule.command.idempotence.Idempotence(command_args, args, molecule=False)Provisions instances and parses output to determine idempotence.
Usage: idempotence [–platform=<platform>] [–provider=<provider>] [–debug]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provide
--debug get more detail
Init
class molecule.command.init.Init(command_args, args, molecule=False)Creates the scaffolding for a new role intended for use with molecule.
Usage: init [<role>] [–docker | –openstack] [–offline]
32 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
List
class molecule.command.list.List(command_args, args, molecule=False)Prints a list of currently available platforms
Usage: list [–debug] ([-m]|[–porcelain])
Options:
--debug get more detail
-m synonym for ‘–porcelain’ (deprecated)
--porcelain machine readable output
Login
class molecule.command.login.Login(command_args, args, molecule=False)Initiates an interactive ssh session with the given host.
Usage: login [<host>]
Status
class molecule.command.status.Status(command_args, args, molecule=False)Prints status of configured instances.
Usage: status [–debug][–porcelain] ([–hosts] [–platforms][–providers])
Options:
--debug get more detail
--porcelain machine readable output
--hosts display the available hosts
--platforms display the available platforms
--providers display the available providers
Syntax
class molecule.command.syntax.Syntax(command_args, args, molecule=False)Performs a syntax check on the current role.
Usage: syntax
Test
class molecule.command.test.Test(command_args, args, molecule=False)Runs a series of commands (defined in config) against instances for a full test/verify run.
Usage: test [–platform=<platform>] [–provider=<provider>] [–destroy=<destroy>] [–debug] [–sudo]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
6.9. Autodoc 33
Molecule Documentation, Release 1.9.1
--destroy=<destroy> destroy behavior (passing, always, never)
--debug get more detail
--sudo run tests with sudo
Verify
class molecule.command.verify.Verify(command_args, args, molecule=False)Performs verification steps on running instances.
Usage: verify [–platform=<platform>] [–provider=<provider>] [–debug] [–sudo]
Options:
--platform=<platform> specify a platform
--provider=<provider> specify a provider
--debug get more detail
--sudo runs tests with sudo
6.9.4 Config
class molecule.config.Config(configs=[’/home/docs/checkouts/readthedocs.org/user_builds/molecule/envs/stable-1.9/local/lib/python2.7/site-packages/molecule/conf/defaults.yml’,‘~/.config/molecule/config.yml’, ‘molecule.yml’])
populate_instance_names(platform)Updates instances section of config with an additional key containing the full instance name
Parameters platform – platform name to pass to format_instance_name call
Returns None
6.9.5 Driver
Docker
class molecule.driver.dockerdriver.DockerDriver(molecule)
Openstack
class molecule.driver.openstackdriver.OpenstackDriver(molecule)
Proxmox
Not Implemented
Vagrant
class molecule.driver.vagrantdriver.VagrantDriver(molecule)
34 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
6.9.6 Molecule
class molecule.core.Molecule(args)
6.9.7 State
class molecule.state.State(state_file=’state.yml’)
6.9.8 Util
molecule.util.debug(title, data)Prints colorized output for use when debugging portions of molecule.
Parameters
• title – title of debug output
• data – data of debug output
Returns None
molecule.util.format_instance_name(name, platform, instances)Takes an instance name and formats it according to options specified in the instance’s config.
Parameters
• name – the name of the instance
• platform – the current molecule platform in use
• instances – the current molecule instances dict in use
Returns formatted instance name if found in instances, otherwise None
molecule.util.get_logger(name=None)Build a logger with the given name.
Parameters name – The name for the logger. This is usually the module name, __name__.
molecule.util.merge_dicts(a, b)Merges the values of B into A and returns a new dict. Uses the same merge strategy as config._combine.
dict a
b:- c: 0- c: 2
d:e: "aaa"f: 3
dict b
a: 1b:
- c: 3d:
e: "bbb"
Will give an object such as:
6.9. Autodoc 35
Molecule Documentation, Release 1.9.1
{'a': 1, 'b': [{'c': 3}], 'd': {'e': "bbb", 'f': 3}}
Parameters
• a – the target dictionary
• b – the dictionary to import
Returns dict
molecule.util.remove_args(command_args, args, kill)Removes args so commands can be passed around easily. :param command_args: list of command args fromDocOpt :param args: dict of arguments from DocOpt :kill: list of args to remove from returned values :return:pruned command_args list, pruned args dict
molecule.util.write_file(filename, content)Writes a file with the given filename using the given content. Overwrites, does not append.
Parameters
• filename – the target filename
• content – what gets written into the file
Returns None
molecule.util.write_template(src, dest, kwargs={}, _module=’molecule’, _dir=’template’)Writes a file from a jinja2 template.
Parameters
• src – the target template files to use
• dest – destination of the templatized file to be written
• kwargs – dictionary of arguments passed to jinja2 when rendering template
• _module – module (to look for template files) passed to jinja2 PackageLoader
• _dir – directory (to look for template files) passed to jinja2 PackageLoader
Returns None
6.9.9 Verifier
Serverspec
class molecule.verifier.serverspec.Serverspec(molecule)
Testinfra
class molecule.verifier.testinfra.Testinfra(molecule)
Trailing
class molecule.verifier.trailing.Trailing(molecule)
36 Chapter 6. Contents:
Molecule Documentation, Release 1.9.1
execute(exit=True)Recursively finds all files relative to CWD, and checks them for trailing whitespace and newlines.
Parameters ignore_paths – list of paths to ignore during checks
Returns A sys.exit code if found an error, otherwise None
6.9. Autodoc 37
Molecule Documentation, Release 1.9.1
38 Chapter 6. Contents:
CHAPTER 7
Indices and tables
• genindex
• modindex
• search
39
Molecule Documentation, Release 1.9.1
40 Chapter 7. Indices and tables
Python Module Index
mmolecule.util, 35
41
Molecule Documentation, Release 1.9.1
42 Python Module Index
Index
Aadd_cli_arg() (molecule.ansible_playbook.AnsiblePlaybook
method), 30add_env_arg() (molecule.ansible_galaxy.AnsibleGalaxy
method), 30add_env_arg() (molecule.ansible_playbook.AnsiblePlaybook
method), 30AnsibleGalaxy (class in molecule.ansible_galaxy), 30AnsiblePlaybook (class in molecule.ansible_playbook),
30
Bbake() (molecule.ansible_galaxy.AnsibleGalaxy method),
30bake() (molecule.ansible_playbook.AnsiblePlaybook
method), 30
CConfig (class in molecule.config), 34Converge (class in molecule.command.converge), 31Create (class in molecule.command.create), 32
Ddebug() (in module molecule.util), 35Destroy (class in molecule.command.destroy), 32DockerDriver (class in molecule.driver.dockerdriver), 34
Eexecute() (molecule.ansible_galaxy.AnsibleGalaxy
method), 30execute() (molecule.ansible_playbook.AnsiblePlaybook
method), 31execute() (molecule.command.converge.Converge
method), 31execute() (molecule.command.destroy.Destroy method),
32execute() (molecule.verifier.trailing.Trailing method), 36
Fformat_instance_name() (in module molecule.util), 35
Gget_logger() (in module molecule.util), 35
IIdempotence (class in molecule.command.idempotence),
32Init (class in molecule.command.init), 32
LList (class in molecule.command.list), 33Login (class in molecule.command.login), 33
Mmerge_dicts() (in module molecule.util), 35Molecule (class in molecule.core), 35molecule.util (module), 35
OOpenstackDriver (class in
molecule.driver.openstackdriver), 34
Pparse_arg() (molecule.ansible_playbook.AnsiblePlaybook
method), 31populate_instance_names() (molecule.config.Config
method), 34
Rremove_args() (in module molecule.util), 36remove_cli_arg() (molecule.ansible_playbook.AnsiblePlaybook
method), 31remove_env_arg() (molecule.ansible_playbook.AnsiblePlaybook
method), 31
SServerspec (class in molecule.verifier.serverspec), 36State (class in molecule.state), 35Status (class in molecule.command.status), 33Syntax (class in molecule.command.syntax), 33
43
Molecule Documentation, Release 1.9.1
TTest (class in molecule.command.test), 33Testinfra (class in molecule.verifier.testinfra), 36Trailing (class in molecule.verifier.trailing), 36
VVagrantDriver (class in molecule.driver.vagrantdriver), 34Verify (class in molecule.command.verify), 34
Wwrite_file() (in module molecule.util), 36write_template() (in module molecule.util), 36
44 Index