大网数据广告活动
服务器运维问答

Ansible - how to conditionally change an item in the list

· 52CE 我爱测

I have two lists: "combo_all": [ [ null, "3", "210 ], [ "r0004", "65", "212" ] and "zone_name_list": [ { "dns_zone_id": 10423, "name": "212.18.172.in-addr.arpa." }, { "dns_zone_id": 10424, "name": ""210.18.172.in-addr.arpa."." } …

问题原文

原帖链接 · kuda · CC BY-SA 4.0

I have two lists:

        "combo_all": [
        [
            null,
            "3",
            "210
        ],
        [
            "r0004",
            "65",
            "212"
        ]

and

        "zone_name_list": [
        {
            "dns_zone_id": 10423,
            "name": "212.18.172.in-addr.arpa."
        },
        {
            "dns_zone_id": 10424,
            "name": ""210.18.172.in-addr.arpa."."
        }

How can I replace the third item in the "combo_all" (first list) by the "dns_zone_id" number (from the second list) whenever the first octet from the "name" matches the third item from the first list (210, 212)?

已采纳解答

原帖链接 · Vladimir Botka · CC BY-SA 4.0

Create the dictionary octet1_id

  dns_zone_id: "{{ zone_name_list|map(attribute='dns_zone_id') }}"
  octet1: "{{ zone_name_list|map(attribute='name')
                            |map('split', '.')
                            |map('first') }}"
  octet1_id: "{{ dict(octet1|zip(dns_zone_id)) }}"

gives

  octet1_id:
    '210': 10424
    '212': 10423

Then create a list

    - set_fact:
        combo_id: "{{ combo_id|d([]) + [item[:-1] + [octet1_id[item[-1]]]] }}"
      loop: "{{ combo_all }}"

gives

  combo_id:
    - [null, '3', 10424]
    - [r0004, '65', 10423]

Example of a complete playbook for testing

- hosts: all

  vars:

    combo_all:
      - [ null, "3", "210"]
      - [ "r0004", "65", "212"]
    zone_name_list:
      - {dns_zone_id: 10423, name: 212.18.172.in-addr.arpa.}
      - {dns_zone_id: 10424, name: 210.18.172.in-addr.arpa.}

    dns_zone_id: "{{ zone_name_list|map(attribute='dns_zone_id') }}"
    octet1: "{{ zone_name_list|map(attribute='name')
                              |map('split', '.')
                              |map('first') }}"
    octet1_id: "{{ dict(octet1|zip(dns_zone_id)) }}"

  tasks:

    - debug:
        var: dns_zone_id
    - debug:
        var: octet1
    - debug:
        var: octet1_id

    - set_fact:
        combo_id: "{{ combo_id|d([]) + [item[:-1] + [octet1_id[item[-1]]]] }}"
      loop: "{{ combo_all }}"
    - debug:
        var: combo_id|to_yaml

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2024-01-15)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。