HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerModerate

Applying ansible playbook to a docker container on a remote host

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
containerdockerplaybookhostremoteapplyingansible

Problem

I have automated the setup of several docker containers with ansible. This works pretty well but there are certain recurring tasks that have to be executed within the docker containers.

It is possible to implement this using the docker connection driver for ansible but this only seems to work when ansible is running on the host that is the docker runner. This is not the case and I don't want to run ansible on multiple hosts if possible. Is there a better way to use ansible to execute playbooks within containers?

Notes:

  • I know how I can execute commands in a docker container from the host system but I don't only want to execute commands. I want to be able to use Ansible for docker containers as if they where standalone hosts.



  • I tried it out of curiosity and it works pretty well using ansible directly on the docker runner,... anyway not my favorite solution.

Solution

With the help of @Levi (refered to Stackoverflow) I managed to find a way to connect straigt into the docker containers using ansibles docker connection driver and the remote API capability of Docker.

First of all you have to expose the API which is by default not the case. Simply add -H tcp://0.0.0.0:1337 to the ExecStart constant of the systemd script. Then reload the start script and restart the docker service. (From this blogpost)

Then you can list the containers in the inventory file like this:

[containers]
container-name ansible_connection=docker ansible_docker_extra_args="-H tcp://1.2.3.4:1337"


And execute any playbook like your used to.

ansible-playbook -i docker_inventory playbooks/my_playbook.yml


The upside of this way of implementing it this way is that you can mix up "real" hosts/vms that are maintained through SSH and Docker containers. One negative thing I have to mention is that the docker API is much slower than using SSH as a control tunnel.

This setup is of cause horribly insecure and its only purpose is to explain the concept. Before using it in production you should read into the security features and limit access to the daemon as far as possible.

Code Snippets

[containers]
container-name ansible_connection=docker ansible_docker_extra_args="-H tcp://1.2.3.4:1337"
ansible-playbook -i docker_inventory playbooks/my_playbook.yml

Context

StackExchange DevOps Q#4440, answer score: 14

Revisions (0)

No revisions yet.