Ansible container
In order to run Ansible in a Docker container, you can use a Dockerfile and a docker-compose file.
Dockerfile¶
# Use Python base image
FROM --platform=linux/amd64 python:3
# Set environment variables
ENV ANSIBLE_HOME=/ansible
WORKDIR $ANSIBLE_HOME
# Install system dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends \
sshpass \
libffi-dev \
libssl-dev \
build-essential \
python3-dev \
python3-pip \
git \
&& rm -rf /var/lib/apt/lists/*
# Upgrade pip
RUN pip install --upgrade pip
# Install Ansible and required Python packages
RUN pip install ansible requests unificontrol
# Install Ansible collections
RUN ansible-galaxy collection install community.general
# Default shell entry point for manual use (Option 1)
CMD ["/bin/sh"]
# Uncomment the following lines for Option 2: Automatically run a specific playbook
# ENTRYPOINT ["ansible-playbook"]
# CMD ["playbooks/collect_unifi_inventory.yml"]
# Notes:
# - Option 1 (default): The container starts with a shell, allowing you to manually run Ansible commands or playbooks.
# - Option 2: Uncomment the ENTRYPOINT and CMD lines above to automatically run the specified playbook when the container starts.
docker-compose¶
version: '3.8'
# option 2 is for MacOS and Windows
networks:
ansible_net:
driver: bridge
services:
ansible:
build: .
container_name: ansible-controller
networks:
- ansible_net
# option 1 is for Linux systems, not MacOS or Windows
# option 1 #network_mode: "host" # Use the host's network stack
volumes:
# specific files mapped to the '/ansible' directory
- ./ansible.cfg:/ansible/ansible.cfg:ro
- ./playbooks/playbook-inventory.yml:/ansible/playbook-inventory.yml:ro
- ./vault.yml:/ansible/vault.yml:rw
# specific subdirectories mapped to the '/ansible' directory
- ./backup:/ansible/backup:rw
- ./group_vars:/ansible/group_vars:ro
- ./inventory:/ansible/inventory
- ./roles:/ansible/roles:ro
working_dir: /ansible
stdin_open: true
tty: true
restart: unless-stopped
Reference list¶
Links found when looking up Running Ansible in a container
:
- https://github.com/ansible/awx-ee
- https://hub.docker.com/r/geerlingguy/docker-ubuntu2404-ansible
- https://github.com/William-Yeh/docker-ansible
- https://www.reddit.com/r/ansible/comments/1d8trn1/which_image_should_i_use_for_ansible_container/?rdt=62502
- https://github.com/thegreenrobot/alpine-ansible-python3/blob/master/Dockerfile
- https://github.com/willhallonline/docker-ansible/blob/master/README.md
- https://www.reddit.com/r/ansible/comments/1c6hqk0/running_ansible_in_docker/