在ansible中将调试变量输出拆分为两个单独的变量

Split debug variable output into two separate variables in ansible

我使用下面的代码片段来打印图像细节:

- set_fact:
    image_name: "{{ load.results|map(attribute='stdout_lines')|list }}"

- debug:
    var: image_name

输出:

TASK [set_fact] ***************************************************************************************************************************************************************************
ok: [xx.xx.xx.xx]

TASK [debug] ******************************************************************************************************************************************************************************
ok: [xx.xx.xx.xx] => {
  "image_name": [
    [
        "Loaded image(s): localhost/cim:v1.5"
    ],
    [
        "Loaded image(s): localhost/cim:v1.8"
    ]
  ]
}

有没有一种方法可以将图像名称和标签存储在 set_fact 本身或任何其他形式下的两个单独的变量中,以便我可以在下一个任务中重用这 2 个变量?

您可以使用 regex_findall 过滤器来实现此目的。

这里使用的正则表达式是(\S*):(\S+)如果需要,可以找到更多解释here

鉴于剧本:

- hosts: all
  gather_facts: no
  vars:
    load:
      results:
        - stdout_lines:
          - "Loaded image(s): localhost/cim:v1.5"
        - stdout_lines:
          - "Loaded image(s): localhost/cim:v1.8"
      
  tasks:
    - set_fact:
        images: "{{ images | default([]) + item | regex_findall('(\S*):(\S+)') }}"
      loop: "{{ load.results | map(attribute='stdout_lines') | flatten }}"
  
    - debug:
        msg: "This image repository is `{{ item.0 }}` and its tag is `{{ item.1 }}`"
      loop: "{{ images }}"

这产生了回顾:

PLAY [all] *********************************************************************************************************

TASK [set_fact] ****************************************************************************************************
ok: [localhost] => (item=Loaded image(s): localhost/cim:v1.5)
ok: [localhost] => (item=Loaded image(s): localhost/cim:v1.8)

TASK [debug] *******************************************************************************************************
ok: [localhost] => (item=['localhost/cim', 'v1.5']) => {
    "msg": "This image repository is `localhost/cim` and its tag is `v1.5`"
}
ok: [localhost] => (item=['localhost/cim', 'v1.8']) => {
    "msg": "This image repository is `localhost/cim` and its tag is `v1.8`"
}

PLAY RECAP *********************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0