Access Docker container attributes in Ansible

Ansible is a great automation solution. I mainly use it to provision servers and launch Docker instances on them. Sometimes I need container attributes, like PID or Port to configure Nginx or monitoring tools.

While the Ansible documentation gives you some hints, I didn’t find it 100% obvious on how to solve this. Basically all your newly-created containers will end up in a list called docker_containers. It has the same structure as docker inspect.

For the PID:

docker_containers[0]['State']['Pid']

For the host port:

docker_containers[0]['NetworkSettings']['Ports']['8888/tcp'][0]['HostPort']

So you could add a PID-file for a container like this:

 - copy: dest="/var/run/{{ image_name }}.pid"
   content="{{docker_containers[0]['State']['Pid']}}"

Also read the full docs here.