将精确字符串与数组/列表匹配 - Ansible

问题描述 投票:0回答:1

service_name
变量打印以下内容。

"msg": [
    "BLAH PEX",
    "BLAH AEX non prod",
    "BLAH BIND",
    "BLAH DBFactory"
]

我想匹配包含字符串

BSA
的变量
BLAH BIND
。我尝试过这样的事情:

- debug:
    msg: "Match found"
  when: "BSA in service_name"

有效!但问题是,如果

BSA
包含字符串
BLAH
,它也会匹配。我希望它仅在完全匹配的情况下才匹配。现在我猜它是逐字匹配的。

预期输出:它应该跳过调试任务,因为当

BSA
包含字符串
BLAH
时,它不应该与
service_name
列表中的任何字符串匹配。

有关如何实现匹配数组中的整个精确字符串的任何帮助。

我使用的是ansible 2.7

ansible ansible-2.x
1个回答
3
投票

问:“预期输出:它应该跳过调试任务,因为当 BSA 包含字符串 BLAH 时,它不应该与 service_name 列表中的任何字符串匹配。”

A:它正在按预期工作。字符串“BLAH”不匹配,调试任务被跳过。

- hosts: localhost
  vars:
    service_name: [ "BLAH PEX", "BLAH AEX non prod", "BLAH BIND", "BLAH DBFactory" ]
    BSA: "BLAH"

  tasks:
    - debug:
        var: service_name
    - debug:
        var: BSA
    - debug:
        msg: "Match found"
      when: "BSA in service_name"
    - debug:
        msg: "Continue"

给予

shell> ansible-playbook playbook.yml

PLAY [localhost] ***

TASK [debug] ***
ok: [localhost] => {
    "service_name": [
        "BLAH PEX", 
        "BLAH AEX non prod", 
        "BLAH BIND", 
        "BLAH DBFactory"
    ]
}

TASK [debug] ***
ok: [localhost] => {
    "BSA": "BLAH"
}

TASK [debug] ***
skipping: [localhost]

TASK [debug] ***
ok: [localhost] => {
    "msg": "Continue"
}

PLAY RECAP ***
localhost: ok=3  changed=0  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0

更新

以下播放中的同等内容无需引用

shell> cat pb.yml
- hosts: localhost

  vars:

    service_name: [BLAH PEX, BLAH AEX non prod, BLAH BIND, BLAH DBFactory]
    BSA: BLAH

  tasks:

    - debug:
        var: service_name
    
    - debug:
        var: BSA
        
    - debug:
        msg: Match found
      when: BSA in service_name
      
    - debug:
        msg: Continue

并且回调community.general.yaml也不需要引号来显示YAML

shell> ANSIBLE_STDOUT_CALLBACK=yaml ansible-playbook pb.yml

PLAY [localhost] ****************************************************************************************************

TASK [debug] ********************************************************************************************************
ok: [localhost] => 
  service_name:
  - BLAH PEX
  - BLAH AEX non prod
  - BLAH BIND
  - BLAH DBFactory

TASK [debug] ********************************************************************************************************
ok: [localhost] => 
  BSA: BLAH

TASK [debug] ********************************************************************************************************
skipping: [localhost]

TASK [debug] ********************************************************************************************************
ok: [localhost] => 
  msg: Continue

© www.soinside.com 2019 - 2024. All rights reserved.