Ansible中如何为输入字符串动态取匹配值

How to dynamically take the matching value for the input string in Ansible

这里我有一个工作脚本,它通过在脚本中提及来静态获取相关值。我正在寻找一种解决方案来动态获取 input.yml 文件 subnetname[=43 之间匹配的值=].

例如:如果在 input.yml 中定义了一个名为 net1 的新子网,那么剧本应该能够匹配该值并更新 rules.yml 动态,如果 input.yml.

中添加了新的子网名,则不应对剧本进行任何更改

剧本

- set_fact:
        ruleoutput: >-
                {{
                ruleoutput | default([]) 
                  + [ item | combine({'destCidr': item.destCidr}) | combine({'netname': details.0.Destination})]
                }} 
      loop: "{{ rules | list}}"
      vars:
        po_id: >- 
            {{
              input |items2dict(key_name='subnetname',
                                              value_name='po_id')
            }}
        DNS: "{{ po_id.DNS | default([])}}"  
        NTP: "{{ po_id.NTP | default([])}}" 
        NET: "{{ po_id.NET | default([])}}"

Input.yml

[
    {
        
        "id": "11155588779966",
        "subnetname": "DNS"
        
    },
    {  
        "id": "99996688778855",
        "subnetname": "NTP"
    },
    {
        "id": "123456789101112",
        "subnetname": "NET"
        
    }
]

rules.yml

rules:
         -    rule number: "1" 
              destCidr: "OBJ({{DNS}}) , 10.22.22.0/24"
                  

         -    rule number: "2"
              destCidr: "OBJ({{ NTP }}) , 10.33.33.0/24"
              

         -    rule number: "3"
              destCidr: "OBJ({{ NET }}), GRP({{ NTP }}) , 10.33.33.0/24"

预期输出

[
    {
        "rule number": "1",
        "destCidr": "OBJ(11155588779966), 10.22.22.0/24 "
    },
    {
        "rule number": "2",
        "destCidr": "OBJ(99996688778855), 10.33.33.0/24"
    },
    {    
        "rule number": "3",
        "destCidr": "OBJ(123456789101112), GRP(99996688778855), 10.33.33.0/24 "
    }
]

试试这个解决方案:

- name: "make this working"
  hosts: localhost
  vars:
    input: "{{ lookup('file', './input.yml') | from_json }}"
    rules:
      - rule number: "1" 
        destCidr: "OBJ({{po_id.DNS}}) , 10.22.22.0/24"
      - rule number: "2"
        destCidr: "OBJ({{ po_id.NTP }}) , 10.33.33.0/24"
      - rule number: "3"
        destCidr: "OBJ({{ po_id.NET }}), GRP({{ NTP }}) , 10.33.33.0/24"
  tasks:
    - set_fact:
         po_id: >- 
            {{
              input |items2dict(key_name='subnetname',
                                              value_name='id')
            }}
    
    - set_fact:
        ruleoutpout: "{{ rules }}"

    - debug:
        var: ruleoutpout

结果:

ok: [localhost] => {
    "ruleoutpout": [
        {
            "destCidr": "OBJ(11155588779966) , 10.22.22.0/24",
            "rule number": "1"
        },
        {
            "destCidr": "OBJ(99996688778855) , 10.33.33.0/24",
            "rule number": "2"
        },
        {
            "destCidr": "OBJ(123456789101112), GRP(99996688778855) , 10.33.33.0/24",
            "rule number": "3"
        }
    ]
}