我编写了一个剧本来检查命令“docker ps --all”输出,然后检查行输出中是否有名称“ansiblecontrol”,然后获取图像的值。这是我的剧本:
---
- 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 }}"
这是输出:
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"
}
尽管输出中出现字符串“ansiblecontrol”,但返回值不正确。我的条件处理代码有什么问题?返回值应该是“localhost/toolac.di.1.0.0.2024.28.2:latest”而不是“unavailable”
如果您的目标是“找到用于
anisblecontrol
容器的图像(如果存在)”,那么最简单的解决方案将是这样的:
- hosts: localhost
gather_facts: false
tasks:
- name: get information about ansiblecontrol container
docker_container_info:
name: ansiblecontrol
register: container
- debug:
var: container.container.Config.Image
community.docker
集合。它将成功检索有关 anisblecontrol
容器的信息(在这种情况下,您可以获取如图所示的图像名称),或者第一个任务将失败,因为容器不存在。