如何在Ansible中使用变量进行正则表达式搜索

时间:2019-06-18 18:21:42

标签: regex ansible

我正在尝试使用脚本开头初始化的变量在Ansible(2.7)中进行正则表达式匹配

用于正则表达式匹配的变量-

group: 12

以下是应该进行匹配的代码行

set_fact: run_pc="{{ lacp_output|select("match","Po{{ group }}") | list}}"

输入是下面编写的列表-

lacp_output = 
["Flags:  D - Down        P - Up in port-channel (members)",
        "        I - Individual  H - Hot-standby (LACP only)",
        "        s - Suspended   r - Module-removed",
        "        S - Switched    R - Routed",
        "        U - Up (port-channel)",
        "        M - Not in use. Min-links not met",
        "--------------------------------------------------------------------------------",
        "Group Port-       Type     Protocol  Member Ports",
        "      Channel",
        "--------------------------------------------------------------------------------",
        "10    Po10(SD)    Eth      NONE      --",
        "11    Po11(SU)    Eth      LACP      Eth1/1(P)    Eth1/2(P)    ",
        "12    Po12(SU)    Eth      LACP      Eth1/3(P)    Eth1/4(P)    ",
        "100   Po100(SD)   Eth      NONE      --",
        "121   Po121(SD)   Eth      NONE      --",
        "122   Po122(SD)   Eth      LACP      Eth2/1(D)    ",
        "123   Po123(SD)   Eth      NONE      --",
        "125   Po125(SD)   Eth      NONE      --",
        "322   Po322(SD)   Eth      NONE      --",
        "323   Po323(SD)   Eth      NONE      --",
        "345   Po345(SD)   Eth      NONE      --",
        "456   Po456(SD)   Eth      NONE      --",
        "777   Po777(SD)   Eth      NONE      --" ]

我正在尝试从上面的列表中完全匹配Po12。

实际输出-

TASK [assert] ***************************************************************************************************
fatal: [localhost]: FAILED! => {
    "assertion": "run_pc | length>0",
    "changed": false,
    "evaluated_to": false,
    "msg": "Can not find port channel 12"
}

预期产量

TASK [debug] ****************************************************************************************************
ok: [localhost] => {
    "run_pc": [
        "12    Po12(SU)    Eth      LACP      Eth1/3(P)    Eth1/4(P)    "
    ]
}

1 个答案:

答案 0 :(得分:0)

尝试

- set_fact:
    run_pc: "{{ run_pc|default([]) + [ item ] }}"
  loop: "{{ lacp_output }}"
  when: item is search('Po' ~ group ~ '\(')

带有select的固定任务在下面

- set_fact:
    run_pc: "{{ lacp_output|select('search','Po' ~ group ~ '\\(')|list }}"