Home

Kenny's Blog

13 Mar 2022

Testing ansible locally with docker

FROM debian:bullseye

RUN apt-get update -y && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    sshpass \
    ssh \
    python3 \
    python3-pip

# install ansible specific stuff
RUN pip install pip --upgrade
RUN pip install ansible
RUN pip install ansible-lint

RUN echo "[all]" >> local
RUN echo "localhost" >> local

COPY ./ /

You can run it using the following commands:

build -t ansible .
docker run ansible-test ansible-playbook -i local users.yml -c local

After the initial build, subsequent runs are pretty quick:

$ docker run ansible-test ansible-playbook -i local users.yml -c local


PLAY [Add users] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Add the user 'johnd' with a specific uid and a primary group of 'admin'] ***
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

I’m not sure how other folks are but dealing with ansible is a bit of a pain a lot of times because writing yaml is error prone… I use this method to test relatively simple roles. Most roles are changing things on the filesystem - docker gives you filesystem and networking isolation relatively easily. It also also gives you the benefit of caching.

You could probably do something similar-ish by having a VM imaged and booting it up every time, but changing a dockerfile is a little more convenient.

This would theoretically work for saltstack as well; you just need to run commands using masterless mode:

https://docs.saltproject.io/en/latest/topics/tutorials/quickstart.html