Archive April 2018

ansible with docker containers as target

Ansible needs ssh access to target machines. But for testing It’s so heavy to use vagrant/virtualbox vm.

Even if docker containers are not the appropriate target to be used with ansible, but light weight and speed starting of containers helps to quickly test playbooks.

To do we will run an ssh server inside our docker container.

Create Dockerfile

FROM debian:jessie

RUN apt update && DEBIAN_FRONTEND=noninteractive apt install -y openssh-server sudo python python-apt apt-transport-https

RUN apt install -y unzip

RUN mkdir -p /var/run/sshd && sed -i "s/UsePrivilegeSeparation.*/UsePrivilegeSeparation no/g" /etc/ssh/sshd_config \
  && sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config \
  && touch /root/.Xauthority \
  && true

RUN useradd myuser \
        && passwd -d mypassword \
        && mkdir /home/myuser \
        && chown myuser:myuser /home/myuser \
        && addgroup myuser staff \
        && addgroup myuser sudo \
        && true

RUN echo "%sudo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

ADD ./ /



set -e

if [ -z "${SSH_KEY}" ]; then
        echo "ERROR: missed public key in the SSH_KEY environment variable"
        exit 1

for MYHOME in /root /home/myuser; do
        echo "=> Adding SSH key to ${MYHOME}"
        mkdir -p ${MYHOME}/.ssh
        chmod go-rwx ${MYHOME}/.ssh
        echo "${SSH_KEY}" > ${MYHOME}/.ssh/authorized_keys
        chmod go-rw ${MYHOME}/.ssh/authorized_keys
        echo "${MYHOME} ssh configured: OK"
chown -R myuser:myuser /home/myuser/.ssh

echo "========================================================================"
echo "You can now connect to this container via SSH using:"
echo ""
echo "    ssh root@<host>"
echo "    ssh myuser@<host>"
echo ""
echo "========================================================================"

exec /sbin/init
exec /usr/sbin/sshd -D

Build and run container

docker build -t my/image .
docker run -d my/image