Ansible 条件变量和通配符

Ansible 条件变量和通配符

尝试添加带有通配符和 Ansible 变量的条件,但收到错误消息。想法是使用以“android-”开头的容器名称触发 api 请求,这是对 docker 容器创建 playbook 的后续操作。

我的剧本:

---
- name: move agent android
  hosts: server1; server2
  vars:
    containers: "{{ containers }}" #variable in a different file

tasks:
    - name: move agent Android
      command: curl "api request to a server"
      when:  "containers.startswith('android-*')"

错误:

TASK [move agent Android] ******************************************************
  fatal: [server1]: FAILED! => {"msg": "The conditional check 'containers.startswith('android-*')' failed. The error was: error while evaluating conditional (containers.startswith('android-*')): 'list object' has no attribute 'startswith'\n\nThe error appears to be in '/directory/were/the/playbook/is/move-agent-android.yml': line 13, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: move agent Android\n      ^ here\n"}

我尝试将条件更改为不同的版本,但都出现相同的错误。

其他版本:

when:  "containers is match('android-*')"

when:  item.name.startswith('android-*')

when:  "{{ containers }}" is match('android-*')

知道如何解决该错误吗?

答案1

尝试

when: "containers is match('^android-.*$')"

这是一个 Python 正则表达式。星号“*”前面缺少点“.”此外,如果匹配,表达式需要以“^”开头并以“$”结尾。

相关内容