Ansible Project Setup
- Create Your Ansible Project Directory
Create a project directory on your host machine to store your Ansible files:
Playbooks: Describe your tasks (e.g., playbook.yml).
Inventory:Specify the hosts you want to manage (e.g., inventory.yml).
Optional Configuration:Add an ansible.cfg file if you need custom configurations.ansible-project/ ├── playbook.yml ├── inventory.yml └── ansible.cfg (optional) - Choose a Pre-built Ansible Image
Use an existing image like cytopia/ansible:latest from Docker Hub to save time and ensure consistency.
- Run the Ansible Container
- Option A: Managing External Hosts (Including the Host Machine)
Run this command from your ansible-project directory:
docker run -it --rm --network host -v $(pwd):/ansible cytopia/ansible:latest /bin/sh-it: Starts an interactive shell.
--rm: Removes the container after you exit, keeping things clean.
--network host: Uses the host’s network, simplifying access to external hosts.
-v $(pwd):/ansible: Mounts your current directory (ansible-project) to /ansible in the container.Inside the container, navigate to the project and run the playbook:
cd /ansible ansible-playbook playbook.yml - Option B: Managing Other Docker Containers
Follow these steps:
- Create a Docker Network:
docker network create mynet - Run Managed Containers:
docker run -d --name web1 --network mynet nginx - Run the Ansible Container:
docker run -it --rm --network mynet -v $(pwd):/ansible cytopia/ansible:latest /bin/shReference the managed container (web1) in your inventory:
# inventory.yml webservers: hosts: web1: ansible_connection: sshRun the playbook:
cd /ansible ansible-playbook playbook.yml
- Create a Docker Network:
- Option A: Managing External Hosts (Including the Host Machine)
- Handle SSH Authentication (If Needed)
Mount your SSH key for secure access:
docker run -it --rm --network host -v $(pwd):/ansible -v
~/.ssh/id_rsa:/ansible/key.pem cytopia/ansible:latest /bin/shInside the container, run the playbook with the private key:
cd /ansible ansible-playbook --private-key /ansible/key.pem playbook.yml