Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible w/ Docker - Show current Container state

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

like image 616
Shai Shvili Avatar asked Jul 21 '17 12:07

Shai Shvili


Video Answer


2 Answers

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.

like image 133
David Pärsson Avatar answered Oct 20 '22 11:10

David Pärsson


Unfortunately, none of the modules around docker can currently "List containers". I did the following as work around to grab the status:

- name: get container status
  shell: docker ps -a -f name={{ container }} --format {%raw%}"table {{.Status}}"{%endraw%} | awk 'FNR == 2 {print}' | awk '{print $1}'
  register: status

Result will then be available in the status variable

like image 31
KVS Avatar answered Oct 20 '22 12:10

KVS