根据 Ansible 中的特定字符串获取值

Fetch the value based on a particular string in Ansible

我想根据规则yaml文件中提到的关键字获取值。如果 rules.yaml 中的关键字被提及为 OBJ,它应该获取与 input & rules yaml 文件中相同子网匹配的 po_id 的值,如果关键字是 GRP,那么它应该在输入和规则 yaml 文件中获取与相同子网匹配的 pog_id 的值。预期结果如下图。

Input.yml

[
    {
        
        "po_id": "11155588779966",
        "pog_id": "1115558871321649",
        "subnetname": "DNS",
        "netname": "Test1"
    },
    {  
        "po_id": "99996688778855",
        "pog_id": "1115558812345",
        "subnetname": "NTP",
        "netname": "Test2"
    },
    {
        "po_id": "123456789101112",
        "pog_id": "111555880321624",
        "subnetname": "NET",
        "netname": "Test3"  
    }
]

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(1115558812345), 10.33.33.0/24 "
    }
]

同样的逻辑:你指明是否需要po_id or pog_id

- 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({{ pog_id.NTP }}) , 10.33.33.0/24"
  tasks:
    - set_fact:
        po_id: >- 
           {{
             input |items2dict(key_name='subnetname',
                                              value_name='po_id')
           }}

    - set_fact:
        pog_id: >- 
            {{
              input |items2dict(key_name='subnetname',
                                              value_name='pog_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(1115558812345) , 10.33.33.0/24",
            "rule number": "3"
        }
    ]
}

在这里你必须指出你是否使用 po_id or pog_id..如果你不想精确,你必须使用自定义过滤器...如果你想要这个,我建议你打开一个新的通过询问 customfilter 的创建来提问 .. 在这种情况下没有什么可以精确的,只需保留 DNS、NET、NTP 及其 customfilter,它在我们有 OBJ、GRP 或其他之后完成工作..