Ansible w/ Docker - Show current Container state

Shai Shvili picture Shai Shvili · Jul 21, 2017 · Viewed 12.8k times · Source

Im working on a little Ansible project in which I'm using Docker Containers.

I'll keep my question short:

I want to get the state of a running Dockercontainer!

What I mean by that is, that i want to get the current state of the container, that Docker shows you by using the "docker ps" command.

Examples would be:

  1. Up
  2. Exited
  3. Restarting

I want to get one of those results from a specific container. But without using the Command or the Shell module!

KR

Answer

David Pärsson picture David Pärsson · Jan 25, 2019

As of Ansible 2.8 you can use the docker_container_info, which essentially returns the input from docker inspect <container>:

- name: Get infos on container
  docker_container_info:
    name: my_container
  register: result

- name: Does container exist?
  debug:
    msg: "The container {{ 'exists' if result.exists else 'does not exist' }}"

- name: Print the status of the container
  debug:
    msg: "The container status is {{ result.container['State']['Status'] }}"
  when: result.exists

With my Docker version, State contains this:

"State": {
    "Status": "running",
    "Running": true,
    "Paused": false,
    "Restarting": false,
    "OOMKilled": false,
    "Dead": false,
    "Pid": 8235,
    "ExitCode": 0,
    "Error": "",
    "StartedAt": "2019-01-25T14:10:08.3206714Z",
    "FinishedAt": "0001-01-01T00:00:00Z"
}

See https://docs.ansible.com/ansible/2.8/modules/docker_container_info_module.html for more details.