使用Molecule测试Ansible Role

什么是Molecule

Molecule可以帮助开发人员在本地借助虚拟技术(Vagrant, Docker, Etc.)测试和运行Ansible Role。
可以参考一下官网的介绍。

如何安装

安装Molecule需要:

  • Python>=3.8
  • Ansible>=2.8

对于Python环境,推荐使用pyenv。它是一个非常不错的Python多版本管理工具。
你可以任意切换你想要的Python版本。

安装 pyenv

使用 pyenv installer 安装 pyenv

1
curl https://pyenv.run | bash

以下内容添加到 .bashrc, .zshrc

1
2
3
4
5
# pyenv
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv init --path)"
eval "$(pyenv virtualenv-init -)"

重载 SHELL

1
exec $SHELL

确认安装是否成功

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
➜  ~ pyenv
pyenv 2.2.5
Usage: pyenv <command> [<args>]

Some useful pyenv commands are:
   --version   Display the version of pyenv
   activate    Activate virtual environment
   commands    List all available pyenv commands
   deactivate   Deactivate virtual environment
   doctor      Verify pyenv installation and development tools to build pythons.
   exec        Run an executable with the selected Python version
   global      Set or show the global Python version(s)
   help        Display help for a command
   hooks       List hook scripts for a given pyenv command
   init        Configure the shell environment for pyenv
   install     Install a Python version using python-build
   local       Set or show the local application-specific Python version(s)
   prefix      Display prefixes for Python versions
   rehash      Rehash pyenv shims (run this after installing executables)
   root        Display the root directory where versions and shims are kept
   shell       Set or show the shell-specific Python version
   shims       List existing pyenv shims
   uninstall   Uninstall a specific Python version
   version     Show the current Python version(s) and its origin
   version-file   Detect the file that sets the current pyenv version
   version-name   Show the current Python version
   version-origin   Explain how the current Python version is set
   versions    List all Python versions available to pyenv
   virtualenv   Create a Python virtualenv using the pyenv-virtualenv plugin
   virtualenv-delete   Uninstall a specific Python virtualenv
   virtualenv-init   Configure the shell environment for pyenv-virtualenv
   virtualenv-prefix   Display real_prefix for a Python virtualenv version
   virtualenvs   List all Python virtualenvs found in `$PYENV_ROOT/versions/*'.
   whence      List all Python versions that contain the given executable
   which       Display the full path to an executable

See `pyenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/pyenv/pyenv#readme

恭喜你,已经成功安装了pyenv

安装Python

在安装Python之前,请先安装构建依赖。
对于MacOS:

1
brew install openssl readline sqlite3 xz zlib

其他系统请参照: pyenv suggested build environment

这里安装3.10.4版的Python

1
pyenv install 3.10.4

对于其他版本的Python,可以使用以下命令来查看。

1
2
3
4
5
6
7
8
9
➜  ~ pyenv install --list
Available versions:
  2.1.3
  2.2.3
  2.3.7
  ... ...
  3.10.4
  3.11.0a6
  3.11-dev

安装Molecule

在安装Molecule之前,请先使用pyenv创建虚拟环境。

1
pyenv virtualenv 3.10.4 ansible

切换到创建的虚拟环境

1
pyenv shell ansible

使用以下命令会顺带着安装Ansible,所以不用单独再安装了。

这里请注意一下,由于新版本(>=3.6.0)的Molecule无法使用molecule login命令。#3462
所以,这边选择安装3.5.2版本的Molecule

1
pip install "molecule[ansible]==3.5.2"

确认安装的Molecule和Ansible

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
(ansible) ➜  ~ ansible --version
ansible [core 2.12.3]
  config file = None
  configured module search path = ['/Users/failover/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /Users/failover/.pyenv/versions/3.10.4/envs/ansible/lib/python3.10/site-packages/ansible
  ansible collection location = /Users/failover/.ansible/collections:/usr/share/ansible/collections
  executable location = /Users/failover/.pyenv/versions/ansible/bin/ansible
  python version = 3.10.4 (main, Mar 25 2022, 18:54:07) [Clang 13.1.6 (clang-1316.0.21.2)]
  jinja version = 3.1.0
  libyaml = False

(ansible) ➜  ~ molecule --version
molecule 3.5.2 using python 3.10
    ansible:2.12.3
    delegated:3.5.2 from molecule

安装驱动

在安装驱动之前,请确保你的系统已经安装了Docker、Vagrant。

安装Docker驱动

1
pip install "molecule[docker]"

安装Vagrant驱动

1
pip install molecule-vagrant

再次确认驱动是否安装成功

1
2
3
4
5
6
(ansible) ➜  ~ molecule --version
molecule 3.5.2 using python 3.10
    ansible:2.12.3
    delegated:3.5.2 from molecule
    docker:1.1.0 from molecule_docker requiring collections: community.docker>=1.9.1
    vagrant:1.0.0 from molecule_vagrant

常用命令

创建Ansible Role

使用Molecule创建Ansible Role,可以生成Ansible Role的目录结构和文件,以及Molecule的目录结构和文件。

1
molecule init role my-new-role --driver-name docker

--driver-name 可以指定驱动:

  • docker
  • vagrant

对于驱动的选择,推荐使用docker驱动。它占用资源更低,速度更快。
但是,如果你的role使用了systemd, 那么最好使用vagrant驱动。

运行Ansible Role

1
molecule converge

它会调用驱动创建instance并运行Ansible Role。

登录instance

使用以下命令来登录instance。

1
molecule login

销毁instance

1
molecule destroy

完整的命令列表

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
(ansible) ➜ molecule
Usage: molecule [OPTIONS] COMMAND [ARGS]...

  Molecule aids in the development and testing of Ansible roles.

  To enable autocomplete for a supported shell execute command below after replacing SHELL with either bash, zsh, or fish:

      eval "$(_MOLECULE_COMPLETE=SHELL_source molecule)"

Options:
  --debug / --no-debug    Enable or disable debug mode. Default is disabled.
  -v, --verbose           Increase Ansible verbosity level. Default is 0.
  -c, --base-config TEXT  Path to a base config (can be specified multiple times). If provided, Molecule will first load and deep merge
                          the configurations in the specified order, and deep merge each scenario's molecule.yml on top. By default
                          Molecule is looking for '.config/molecule/config.yml' in current VCS repository and if not found it will look in
                          user home. (None).
  -e, --env-file TEXT     The file to read variables from when rendering molecule.yml. (.env.yml)
  --version
  --help                  Show this message and exit.

Commands:
  check        Use the provisioner to perform a Dry-Run (destroy, dependency, create, prepare, converge).
  cleanup      Use the provisioner to cleanup any changes made to external systems during the stages of testing.
  converge     Use the provisioner to configure instances (dependency, create, prepare converge).
  create       Use the provisioner to start the instances.
  dependency   Manage the role's dependencies.
  destroy      Use the provisioner to destroy the instances.
  drivers      List drivers.
  idempotence  Use the provisioner to configure the instances and parse the output to determine idempotence.
  init         Initialize a new role or scenario.
  lint         Lint the role (dependency, lint).
  list         List status of instances.
  login        Log in to one instance.
  matrix       List matrix of steps used to test instances.
  prepare      Use the provisioner to prepare the instances into a particular starting state.
  reset        Reset molecule temporary folders.
  side-effect  Use the provisioner to perform side-effects to the instances.
  syntax       Use the provisioner to syntax check the role.
  test         Test (dependency, lint, cleanup, destroy, syntax, create, prepare, converge, idempotence, side_effect, verify,...
  verify       Run automated tests against instances.

Molecule的目录结构

Molecule的配置文件在Role的molecule目录中:

1
2
3
4
5
6
7
molecule
└── default
    ├── converge.yml
    ├── molecule.yml
    └── verify.yml

1 directory, 3 files

具体如何使用,请参照官方的说明文档: Getting Started Guide

示例

examples-molecule