将调试变量输出拆分为两个独立的变量

问题描述

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

- 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本身下的两个单独变量中或以其他任何形式存储,以便我可以将这两个变量重新用于下一个任务?

解决方法

您可以使用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