I write a playbook to check command docker ps --all
output then check if there is a names ansiblecontrol
in output of line then get the value of images.
Here down is my playbook:
---
- name: Check and update Docker toolkit status
hosts: dockerhost0
become: yes
become_method: su
tasks:
- name: Check list of docker containers in host
command: docker ps --all
register: docker_ps_output
- name: Debug Docker output
debug:
msg: "{{ docker_ps_output.stdout_lines }}"
- name: Set fact based on command output
set_fact:
toolstatus: >-
{% set found = 'unavailable' %}
{% for line in docker_ps_output.stdout_lines %}
{% if 'ansiblecontroll' in line %}
{% set parts = line.split() %}
{% set found = parts[1] %}
{% endif %}
{% endfor %}
{{ found }}
- name: Debug toolstatus
debug:
msg: "Toolstatus is set to: {{ toolstatus }}"
Here is the output:
TASK [Check list of docker containers in host] **************************************************************************************************************************
changed: [dockerhost0]
TASK [Debug Docker output] **********************************************************************************************************************************************
ok: [dockerhost0] => {
"msg": [
"CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES",
"468bc9a43749 localhost/toolac.di.1.0.0.2024.28.2:latest /bin/bash 3 weeks ago Up 3 weeks ago ansiblecontrol",
"ad73b324913e localhost/toolac.di.1.0.0.2024.12.4:latest /bin/bash 3 months ago Up 3 months ago acnode"
]
}
TASK [Set fact based on command output] *********************************************************************************************************************************
ok: [dockerhost0]
TASK [Debug toolstatus] *************************************************************************************************************************************************
ok: [dockerhost0] => {
"msg": "Toolstatus is set to: unavailable"
}
The return value is incorrect as expected although there is string ansiblecontrol
appeared in output. The return value should be localhost/toolac.di.1.0.0.2024.28.2:latest
in stead of unavailable
.
What's wrong in my condition processing codes?
If your goal is "find the image used for the anisblecontrol
container, if it exists", then the simplest solution is going to be something like this:
- hosts: localhost
gather_facts: false
tasks:
- name: get information about ansiblecontrol container
community.docker.docker_container_info:
name: ansiblecontrol
register: container
- when: container.container is none
fail:
msg: No ansiblecontrol container exists
- debug:
var: container.container.Config.Image
This relies on the community.docker
collection.
It will either successfully retrieve information about the anisblecontrol
container, in which case you can get the name of the image as shown, or the value of container.container
will be none
.