在 Ansible 中使用子列表滚动列表

Scrolling through a list with sublist in Ansible

我需要同时遍历一个数据结构来对齐值,我用下面的代码得到了这个结构:

- name: Set instances
  set_fact:
    instance_db:
      - 'db2inst1'
      - 'db2inst2'

- name: Get Dialog Path
  shell: db2 get dbm cfg | grep -i "Current member resolved DIAGPATH" | awk {'print '}
  become: true
  become_method: sudo
  become_flags: -i
  become_user: "{{ item }}"
  loop: "{{ instance_db }}"
  register: kud_path

- name: set_fact
  set_fact:
    db2_store: "[{{ instance_db | list }}] + [{{ kud_path.results|map(attribute='stdout')|list }}]"
  vars:
    db2_store: []

结果

{
    "changed": false,
    "ansible_facts": {
        "db2_store": [
            "db2inst1",
            "db2inst2",
            [
                "/db2home/db2inst1/sqllib/db2dump/DIAG0000/",
                "/home/db2inst2/sqllib/db2dump/DIAG0000/"
            ]
        ]
    },
    "_ansible_no_log": false
}

现在我需要在我放置[*]的地方自动遍历这些索引。因为实际上,我只能像这样访问数据 item[0][1]

- name: Creating silent config
  template:
    src: template.txt.j2
    dest: '/tmp/template{{ item[0][*] | lower }}.txt'
    mode: '0775'
  loop:
    - "{{ db2_store }}"

为了能够将两个值都传递给模板,必须采用此解决方法

模板

################## Database connection config ##################
INSTANCE={{ item[0][*] }}
DIAGLOG_PATH={{ item[1][*] }}db2diag.log

关于如何执行此操作或获得相同结果的更优雅的方法有什么建议吗?

假设如下:

instance_db = ["db2inst1", "db2inst2"]
kud_path.results|map(attribute='stdout')|list = ["/db2home/db2inst1/sqllib/db2dump/DIAG0000/", "/home/db2inst2/sqllib/db2dump/DIAG0000/"]

然后您可以使用 zip 过滤器,它将第一个列表的第 N 个元素与第二个列表的第 N 个元素配对。

- debug:
    msg: "{{ instance_db | zip(kud_path.results|map(attribute='stdout')|list) }}"

输出:

TASK [debug] ********************************************************************
ok: [localhost] => {
    "msg": [
        [
            "db2inst1",
            "/db2home/db2inst1/sqllib/db2dump/DIAG0000/"
        ],
        [
            "db2inst2",
            "/home/db2inst2/sqllib/db2dump/DIAG0000/"
        ]
    ]
}

这使您可以轻松循环:

- name: Creating silent config
  template:
    src: template.txt.j2
    dest: '/tmp/template{{ item[0] | lower }}.txt'
    mode: '0775'
  loop: "{{ instance_db | zip(kud_path.results|map(attribute='stdout')|list) }}"
################## Database connection config ##################
INSTANCE={{ item[0] }}
DIAGLOG_PATH={{ item[1] }}db2diag.log