CONFIGURE NODES

Introduction

To create a local Ansible lab using Docker containers and connect to them securely using a PEM (SSH key) authentication. This setup is ideal for learning and practicing Ansible without using cloud VMs.

Steps

  1. Install Ansible and Docker on the Host Machine
    • Update the system: sudo apt update
    • Install Docker:
      sudo apt install -y docker.io
      sudo systemctl start docker
      sudo systemctl enable docker
    • Install Ansible: sudo apt install -y ansible
    • Verify installations:
      docker --version
      ansible --version
  2. Generate PEM Key for SSH Authentication
    • Create SSH key pair:
      ssh-keygen -t rsa -b 4096 -f ansible-key.pem

      Generates:

      • ansible-key.pem (private key)
      • ansible-key.pem.pub (public key)
    • Set permission for private key: chmod 400 ansible-key.pem
  3. Prepare Docker Environment
    • Pull Ubuntu image: docker pull ubuntu:22.04
    • Create Docker network: docker network create ansible-lab
  4. Create Ubuntu Servers as Docker Containers
    • Server 1:
      docker run -dit --name ubuntu-server-1 --hostname server1 --network ansible-lab ubuntu:22.04
    • Server 2:
      docker run -dit --name ubuntu-server-2 --hostname server2 --network ansible-lab ubuntu:22.04
  5. Configure SSH Inside Containers
    • Access container:
      docker exec -it ubuntu-server-1 bash
    • Install SSH and required packages:
      apt update
      apt install -y openssh-server sudo
      mkdir /var/run/sshd
  6. Create SSH User
    • Add user 'devops':
      useradd -m -s /bin/bash devops
    • Create SSH directory:
      mkdir /home/devops/.ssh
      chmod 700 /home/devops/.ssh
  7. Configure PEM Key Authentication
    • Add public key to /home/devops/.ssh/authorized_keys
    • Set permissions:
      chmod 600 /home/devops/.ssh/authorized_keys
      chown -R devops:devops /home/devops/.ssh
  8. Enable and Start SSH Service
    • Edit /etc/ssh/sshd_config:
      • PubkeyAuthentication yes
      • PasswordAuthentication no
      • PermitRootLogin no
    • Start SSH service: service ssh start
    • Exit container: exit
  9. Repeat for Second Server — repeat steps 5 to 8 for ubuntu-server-2
  10. Get Container IP Addresses
    docker inspect ubuntu-server-1 | grep IPAddress
    docker inspect ubuntu-server-2 | grep IPAddress
  11. SSH Into Containers Using PEM Key
    ssh -i ansible-key.pem devops@<server-ip>
  12. Result
    • Two Ubuntu servers running as Docker containers
    • SSH access secured using PEM key authentication
    • Ready-to-use local environment for Ansible automation