How to connect to Docker from Ansible

Sat, Feb 4, 2017

Ansible #Ansible #Docker

In this post we are going to use Ansible to connect to Docker and run some commands. I’ve been using this for quite some time, and find it quite useful especially when I want to test provisioning some test before I run it in the actual servers.

Basically we will need to specify the connection type to the “ansible_connection” properties in the inventory file.

First we will start a Postgres docker container

docker run --name postgres-container -d postgres

Now we have a Postgres container running with the name “postgres-container”. Then we will enter the following content into an inventory file named “inventory”.

postgres-container ansible_connection=docker

And now we are able to connect to the Postgres container using Ansible. To test it, we can use the ping module

thor$ ansible -i inventory all -m ping
postgres-container | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

And now we have successfully connect to a Docker container from Ansible. If you have trouble connecting to your docker container, please check the following

  • the container needs to have python installed
  • the container name must match the entry in the inventory file