8 Ansible
Markus Bergholz edited this page 2 months ago

Test Ansible Roles using Docker

KISS: You don't need molecule magic. Just prepare an container image, e.g.

FROM debian:10

RUN apt update && apt install -y init sudo python

Run it:

docker run \
  --name debian --rm -d \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v /sys/fs/cgroup:/sys/fs/cgroup:ro \
  --cap-add SYS_ADMIN \
  --privileged \
  debian:testing /sbin/init

And run your playbook against that container

---
- hosts: localhost
  connection: local
  gather_facts: False

  tasks:
    - name: add container to inventory
      add_host:
        name: debian
        ansible_connection: docker
      changed_when: false

    - name: test my debian role
      include_role:
        name: deb
        apply:
          delegate_to: debian

or use a generic playbook

---
- hosts: debian
  gather_facts: True

  roles:
    - deb

and use a testing inventory, which adresses the docker container

[testing]
debian ansible_connection=docker 

References

Ansible Testing for contributing

run tests in docker container

bin/ansible-test units -v --python 3.7 --docker default

run sanity check for all

./bin/ansible-test sanity --docker default

run sanity check for one module

bin/ansible-test sanity lib/ansible/modules/cloud/amazon/cloudwatchlogs_log_group_metric_filter.py --docker default

prepare integration test

cp ~/.local/lib/python3.8/site-packages/ansible_test/config/cloud-config-aws.ini.template tests/integration/cloud-config-aws.ini

run integration test

./bin/ansible-test integration -v --python 3.7 cloudwatchlogs --docker --allow-unsupported

Gitlab Integration test

ansible-test integration -v --python 3.6 gitlab_project_variable --docker ubuntu1804 --allow-unsupported  
ansible-test integration -v --python 3.6 gitlab_group --docker ubuntu1804 --allow-unsupported --allow-disabled

With tests/integration/integration_config.yml

---
gitlab_host: https://gitlab.com
gitlab_login_token: secret-access-token
gitlab_project_name: markuman/dotfiles