I am considerably new with Ansible and wanted to verify the changes I have made to an existing Ansible project. I found a nifty solution to my problem. I am now running the Ansible playbook inside a docker container. I got inspiration from couple of places that I should give credit to:
So what I have done is, I am creating a Docker container with the open-ssh server, sudo and python installed. Then I am adding an inventory for the docker container. Finally I am executing a bash script where I am building my image, running the container and then running the playbook on the container. I will show you just how I did it.
My Ansible project structure looks like this:
├── ansible
│ ├── env
│ │ └── local_docker
│ ├── roles
│ │ └── role1
│ │ └── tasks
│ │ └── main.yml
│ ├── myplaybook.yml
├── container-start-and-playbook-run.sh
└── docker
├── Dockerfile
The Dockerfile looks like this:
FROM ubuntu:16.04
RUN apt-get update && apt-get install -y openssh-server sudo python unzip
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
The content of my local_docker
file looks like this:
[local]
ansible-test ansible_connection=docker
The ansible-test
is the name of my container that I will create in my container-start-and-playbook-run.sh
script. ansible_connection=docker
is the part that tell Ansible that it needs to run the playbook inside the ansible-test
container.
Now the content of myplaybook
will need to refer to this local
inventory that I have created. Like so:
---
- hosts: local
become: true
roles:
- role1
Finally the content of the bash script that puts everything together is:
#!/bin/bash
DOCKER_CONTAINER_NAME="ansible-test"
cd docker && docker build -t myubuntu .
docker run -ti --privileged --name $DOCKER_CONTAINER_NAME -d -p 5000:22 myubuntu
cd ../ansible && ansible-playbook -i env/local_docker myplaybook.yml -vvvdocker stop $DOCKER_CONTAINER_NAME
docker rm $DOCKER_CONTAINER_NAME
This has been greatly helpful for me, as I have zero confidence in my Ansible skills. Hope someone finds it helpful.