Ansible Project Setup

  1. 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)
  2. Choose a Pre-built Ansible Image

    Use an existing image like cytopia/ansible:latest from Docker Hub to save time and ensure consistency.

  3. 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:

      1. Create a Docker Network:
        docker network create mynet
      2. Run Managed Containers:
        docker run -d --name web1 --network mynet nginx
      3. Run the Ansible Container:
        docker run -it --rm --network mynet -v $(pwd):/ansible cytopia/ansible:latest /bin/sh

        Reference the managed container (web1) in your inventory:

        # inventory.yml
        webservers:
          hosts:
            web1:
              ansible_connection: ssh

        Run the playbook:

        cd /ansible
        ansible-playbook playbook.yml
  4. 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/sh

    Inside the container, run the playbook with the private key:

    cd /ansible
    ansible-playbook --private-key /ansible/key.pem playbook.yml