Thorbijoern
Thorbijoern

Reputation: 364

How to use the docker connection-plugin of ansible?

I want to create and edit docker containers automated using ansible and I found a connection plugin in the ansible GitHub repository, which uses docker exec instead of ssh to run commands etc. inside the container. I can't find any documentation about this plugin and can't exactly figure out how to use it?

Upvotes: 8

Views: 9391

Answers (2)

johntellsall
johntellsall

Reputation: 15180

2020 TLDR: run a minimal Python container

In 2020, the above solution (running a minimal Alpine container) doesn't work -- Python is not installed.

Building on Konstantin Suvorov's answer, to make Ansible happy, give it a slim Python container:

docker run -d --name=mycontainer python:3.8-slim-buster sleep 600

Check:

ansible all -i 'mycontainer,' -c docker -m setup

Classic solution

The solution above no longer works, Python is not discoverable by Ansible:

docker run -d --name=bogus alpine:latest sleep 600

ansible all -i 'bogus,' -c docker -m setup

[WARNING]: No python interpreters found for host bogus (tried ['/usr/bin/python',
'python3.7', 'python3.6', 'python3.5', 'python2.7', 'python2.6',
'/usr/libexec/platform-python', '/usr/bin/python3', 'python'])

To make Ansible happy, give it a slim Python container:

docker run -d --name=mycontainer python:3.8-slim-buster sleep 600

Check:

ansible all -i 'mycontainer,' -c docker -m setup

Recommended Docker image

Itamar Turner-Trauring[1] recommended base Python image = python:3.8-slim-buster. The Alpine image, although nice and tiny, causes a lots of problems with Python! The above image is Debian-based, small enough, and totally solid.

[1] from https://pythonspeed.com/articles/base-image-python-docker-images/

Upvotes: 3

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68329

It's simple: set connection: docker and use container names as inventory hosts.

Example:

# docker run -d --name=mycontainer -e FOO=bar alpine:latest sleep 600
fde1a28914174c53e8f186f2b8ea312c0bda9c895fc6c956f3f1315788f0bf20
# ansible all -i 'mycontainer,' -c docker -m raw -a 'echo $FOO'
mycontainer | SUCCESS | rc=0 >>
bar

Just keep in mind, that most of Ansible modules require Python, but usually you have minimal amount of libraries inside your containers, and Python is not among them.

Upvotes: 13

Related Questions