1

Been trying to add a conditional with a wildcard and an Ansible variable and getting an error message. The idea is to trigger the api request with the container name starts with "android-", this is a follow-up to a docker container creation playbook.

My 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-*')"

the error:

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"}

I have tried to change the conditionals to different versions and all gething the same error.

other versions:

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

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

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

Any idea how to solve the error?

Saptronic
  • 13
  • 1
  • 4

1 Answers1

2

Try

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

It is a Python regex. The dot '.' was missing in front of the star '*'. Also, you need to start '^' and end "$" the expression in case of matching.

Vladimir Botka
  • 5,138
  • 8
  • 20
  • 1
    While it doesn't hurt, technically you only ever need to anchor the end for `match`, as it's implicitly anchored to the beginning. In this particular case the end anchor is also pointless, since `.*` will always match to the end anyway. The easiest solution is actually to leave off the `*`: `is match('android-')` will match all strings that start with `android-`, which is the desired outcome. – flowerysong Oct 27 '21 at 18:01
  • 1
    It is constructive criticism on how you can improve your post. You are not required to take it. – flowerysong Oct 27 '21 at 18:30