【问题标题】:How to evaluate a when condition for Ansible task如何评估 Ansible 任务的 when 条件
【发布时间】:2015-12-23 06:27:03
【问题描述】:

我有一个具有以下值的变量:

   name_prefix: stage-dbs

我的剧本中有一个任务,它必须检查这个变量并查看它是否包含 *-dbs ,如果满足条件,那么它应该处理。我写了这样的东西:

- name: Ensure deployment directory is present
  file:
    path=/var/tmp/deploy/paTestTool
    state=directory
  when: name_prefix =="*-dbs" # what condition is required here to evaulate the rest part of variable?? 

这里应该使用什么正则表达式模式或如何使用正则表达式?

【问题讨论】:

    标签: regex ansible ansible-playbook


    【解决方案1】:

    无需使用正则表达式进行模式搜索。您可以像这样使用搜索:

    when: name_prefix | search("stage-dbs")
    

    一定会成功的。

    【讨论】:

    • 我很难在 Ansible 文档中找到这个,隐藏在 Playbooks > Jinja2 过滤器 > 其他有用的过滤器 - 部分:docs.ansible.com/ansible/…
    • 这避免了正则表达式有时非常有用的事实 - 例如:“[Jj]ava *[Kk]ey[Ss]tore” not in cmd.stdout 比假设间距和大写更安全持续的。所以“不需要使用正则表达式”是没有意义的,(以及不定冠词)IMO。
    • @GrahamNicholls search("stage-dbs") 在答案中可能应该是 regex_search("*-dbs")
    • @ws_e_c421:实际上,我相信您的正则表达式有一个错误:“*-dbs”表示 0 个或多个空无,后跟“-dbs”。我怀疑你的意思是(“。*-dbs”),其中前导“。”表示任何单个字符。
    • @ws_e_c421 - 对不起,如果我过于迂腐了!
    【解决方案2】:

    不确定过滤器 search 今天是否存在?

    https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#searching-strings-with-regular-expressions 的解决方案:

    when: name_prefix | regex_search("^stage-dbs(.*)$")
    

    【讨论】:

    • 我非常感谢你!谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2013-10-29
    • 2020-06-06
    相关资源
    最近更新 更多