如何评估Ansible任务的when条件

Nis*_*ngh 6 regex ansible ansible-playbook

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

   name_prefix: stage-dbs
Run Code Online (Sandbox Code Playgroud)

我在我的剧本中有一个任务,必须检查这个变量并查看它是否包含*-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?? 
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*aux 18

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

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

when: name_prefix | regex_search("^stage-dbs(.*)$")
Run Code Online (Sandbox Code Playgroud)


koh*_*ohi 14

无需使用正则表达式进行模式搜索.您可以使用以下搜索:

when: name_prefix | search("stage-dbs")
Run Code Online (Sandbox Code Playgroud)

它肯定会奏效.

  • 这避免了正则表达式有时非常有用的事实 - 例如:“[Jj]ava *[Kk]ey[Ss]tore”不在 cmd.stdout 中比假设间距和大小写一致更安全。因此,“无需使用正则表达式”没有抓住重点,(以及不定冠词)IMO。 (2认同)
  • @GrahamNicholls `search("stage-dbs")` 在答案中可能应该是 `regex_search("*-dbs")`。 (2认同)
  • @ ws_e_c421:实际上,我相信你的正则表达式有一个错误:"\* - dbs"表示0或更多没有任何后跟"-dbs".我怀疑你是指(".* - dbs"),其中领先的"." 是指任何单个字符. (2认同)