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
- 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
- Update the system:
- 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
- Create SSH key pair:
- Prepare Docker Environment
- Pull Ubuntu image:
docker pull ubuntu:22.04 - Create Docker network:
docker network create ansible-lab
- Pull Ubuntu image:
- 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
- Server 1:
- 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
- Access container:
- Create SSH User
- Add user 'devops':
useradd -m -s /bin/bash devops
- Create SSH directory:
mkdir /home/devops/.ssh chmod 700 /home/devops/.ssh
- Add user 'devops':
- 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
- Add public key to
- 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
- Edit
- Repeat for Second Server — repeat steps 5 to 8 for ubuntu-server-2
- Get Container IP Addresses
docker inspect ubuntu-server-1 | grep IPAddress docker inspect ubuntu-server-2 | grep IPAddress
- SSH Into Containers Using PEM Key
ssh -i ansible-key.pem devops@<server-ip>
- Result
- Two Ubuntu servers running as Docker containers
- SSH access secured using PEM key authentication
- Ready-to-use local environment for Ansible automation