Ansible Lab Environment setup in Docker container

For ansible lab environment setup, first I will generate ssh key for non-root user and then create a Dockerfile to build a docker image. After that, we will start the container and you will be able to practice your Ansible playbook in the Docker container.

Generate ssh key

ssh-keygen -f keycontainer
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in keycontainer.
Your public key has been saved in keycontainer.pub.


The key's randomart image is:
+---[RSA 3072]----+
|     . .ooo=..   |
|      +...+ =    |
|     o ..+oo .   |
|    E o +==o     |
|   o + =S+o+.    |
|  . + =.o.o.o    |
|   . oo+....     |
|  ..o.+o.        |
|   o**..         |
+----[SHA256]-----+

The command above will create two files, private and public keys. We have to add a public key to the container.

ls                                                                       
keycontainer     keycontainer.pub

In Dockerfile, I am using latest version of ubuntu. Dockerfile will install ssh package and run it. It also copy keycontainer.pub key file which we generated earlier to container. And for privilege access I have added non-root user to sudoers file. Here user will be authenticated as key based.

FROM ubuntu:latest
MAINTAINER bdn@bidhankhatri.com.np

ARG USERNAME=thunder
EXPOSE 22

# Apt update & apt install required packages
RUN apt update && apt -y install openssh-server sudo net-tools less


# Add a non-root user
RUN useradd -ms /bin/bash $USERNAME

# Remove no-needed packages
RUN apt -y autoremove && apt -y autoclean && apt -y clean

# Create the ssh directory and authorized_keys file
USER $USERNAME
RUN mkdir /home/$USERNAME/.ssh
COPY keycontainer.pub /home/$USERNAME/.ssh/authorized_keys

USER root
RUN chown $USERNAME /home/$USERNAME/.ssh/authorized_keys && \
chmod 600 /home/$USERNAME/.ssh/authorized_keys
RUN echo "${USERNAME} ALL=(ALL) NOPASSWD: ALL " >> /etc/sudoers

# Run ssh service
RUN service ssh start

CMD ["/usr/sbin/sshd","-D"]

Dockerfile Instruction:
FROM To specify the parent image.
EXPOSE is for documentating. To define which port through which to access your container application.
ARG for defining variable that can be passed at build time.
RUN install your application and packages required to container. It executes any commands on top of the current image and creates a new layer by committing the results.
USER switch to the non root user first and later to root user to perform their task.
CMD Arguments passed to the entrypoint. If ENTRYPOINT is not set (defaults to /bin/sh -c), the CMD will be the commands the container executes.

Now build Image from a Dockerfile.

docker build -t ubuntu-lab .
[+] Building 4.6s (14/14) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                                                   0.0s
 => => transferring dockerfile: 752B                                                                                                                                                                   0.0s
 => [internal] load .dockerignore                                                                                                                                                                      0.0s
 => => transferring context: 2B                                                                                                                                                                        0.0s
 => [internal] load metadata for docker.io/library/ubuntu:latest                                                                                                                                       3.3s
 => [1/9] FROM docker.io/library/ubuntu:latest@sha256:82becede498899ec668628e7cb0ad87b6e1c371cb8a1e597d83a47fac21d6af3                                                                                 0.0s
 => [internal] load build context                                                                                                                                                                      0.0s
 => => transferring context: 625B                                                                                                                                                                      0.0s
 => CACHED [2/9] RUN apt update && apt -y install openssh-server sudo net-tools less                                                                                                                   0.0s
 => CACHED [3/9] RUN useradd -ms /bin/bash thunder                                                                                                                                                     0.0s
 => CACHED [4/9] RUN apt -y autoremove && apt -y autoclean && apt -y clean                                                                                                                             0.0s
 => CACHED [5/9] RUN mkdir /home/thunder/.ssh                                                                                                                                                          0.0s
 => [6/9] COPY keycontainer.pub /home/thunder/.ssh/authorized_keys                                                                                                                                     0.0s
 => [7/9] RUN chown thunder /home/thunder/.ssh/authorized_keys && chmod 600 /home/thunder/.ssh/authorized_keys                                                                                         0.3s
 => [8/9] RUN echo "thunder ALL=(ALL) NOPASSWD: ALL " >> /etc/sudoers                                                                                                                                  0.3s
 => [9/9] RUN service ssh start                                                                                                                                                                        0.3s
 => exporting to image                                                                                                                                                                                 0.1s
 => => exporting layers                                                                                                                                                                                0.1s
 => => writing image sha256:3aadca7b60cb4bc97df0956539fcf8116295f58234a096242b682deba5df3439                                                                                                           0.0s
 => => naming to docker.io/library/ubuntu-lab                                                                                                                                                          0.0s

Now view the newly created docker image by executing below command.

docker images 
REPOSITORY                            TAG       IMAGE ID       CREATED         SIZE
ubuntu-lab                            latest    3aadca7b60cb   53 seconds ago   230MB

now run container by executing below command.

docker run -d -p 2022:22 ubuntu-lab

Container port to be accessible through docker host, we need to publish it. Above command will map port 2022 of the docker host to port 22 of the container.

It’s better to centralize all your ssh key so I have copied my newly generated ssh key to my home directory ssh folder. Now, to access container through ssh, execute below command.

cp containerkey ~/.ssh/
ssh thunder@localhost -p2022 -i ~/.ssh/containerkey

OR
simply add in your ssh config file like below so that from next time u can easily access container.

less ~/.ssh/config
Host localhost
        HostName localhost
        User thunder
        Port 2022
        IdentityFile ~/.ssh/keycontainer

Now try to ssh your container.

ssh localhost
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.10.25-linuxkit x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

This system has been minimized by removing packages and content that are
not required on a system that users do not log into.

To restore this content, you can run the 'unminimize' command.
Last login: Sun Aug 22 11:00:31 2021 from 172.17.0.1

thunder@da64f58578e3:~$

Container SSH part is completed. Now follow the ansible config part.

Ansible

I hope you have already installed ansible on your control host. If yes then first create an inventory file like below.

cat inventory.ini 
[local]
localhost

Now check ansible connection through AD-Hoc Command

ansible local -i inventory.ini -m ping       
localhost | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

ansible local -i inventory.ini -a 'hostname -I' 
localhost | CHANGED | rc=0 >>
172.17.0.2

That’s it.

Setup is now completed. Now you can test your ansible playbooks in Docker container.

Comments