Testing ansible locally with Docker
Introduction
Configuration management is a critical aspect of IT infrastructure, and Ansible has emerged as a powerful tool for automating this process. While Ansible excels at managing remote systems, testing playbooks and roles locally can be cumbersome. In this article, we’ll explore a streamlined approach to testing Ansible locally using Docker, allowing you to iterate and validate configurations more efficiently.
Pre-requisites
- Docker
- Ansible
And that’s it! With these two, you can start along.
Preface
Before diving into Ansible playbooks, we need to create an SSH server image for Docker. This step is essential for setting up the necessary environment to run Ansible locally.
If you went to test your changes already and did not follow this tutorial, you can also download the code from this repo: https://github.com/anmolb12/docker-ansible
Creating SSH Server image
We’ll use Ubuntu for our image and set up the SSH server. Create a Dockerfile with the following content:
Build the image using the command:
docker build -t ubuntu-ssh-server .
Now, run a container from this image:
docker run -d -p 2222:22 --name ssh_container ubuntu-ssh-server
You now have a running SSH server. Test the connection with:
ssh -p 2222 node@localhost
Amazing, so now let’s move to the next part.
Run ansible-playbook on the docker container
Next, let’s create an Ansible project. We need two files: ansible-playbook.yaml
and inventory.ini
.
inventory.ini
[docker]
localhost become_ansible_user=node become_ansible_password=node1234 ansible_user=node ansible_password=node1234 ansible_ssh_port=2222
ansible-playbook.yaml
- name: Docker Playbook
hosts: all
become: true
tasks:
- name: Update apt cache
apt:
update_cache: yes
- name: Install Apache
apt:
name: apache2
state: present
In this file, we are installing apache2 in host.
Run the playbook on the Docker container:
ansible-playbook -i inventory.ini playbook.yaml --ask-become-pass
Voila! You now have Apache server installed on the Docker container using Ansible.
Conclusion
This simple setup can be extended to use multiple containers, making debugging and testing Ansible playbooks locally even more straightforward. Explore the possibilities for scaling and adapting this approach to your specific needs.