AUser
AUser

Reputation: 37

Ansible task - Evaluate when with or and

I have vars like this:

   vars:
     src_wls: "{{ source_database.src_wls_password }}"
     src_pwd: "{{ source_database.src_password }}"
     tgt_secondary_servers: "{{ inventory_hostname }}"

I want it to run this part if the env is 003 or 004 and the secondary server is like *app02*

I've tried a few iterations, but can't get it to work. Thanks for looking.

- name: Performing managed server 
  shell: "cd {{ dest }}; {{ dest }}/script_app.sh {{ src_pwd }} {{ src_wls }}"
  when:
    - target_clone == '003' or target_clone == '004' 
    - tgt_secondary_servers | regex_search("*app02")

fatal: [lebapp02]: FAILED! => {"msg": "The conditional check 'tgt_secondary_servers | regex_search("*app02")' failed. The error was: nothing to repeat\n\nThe error appears to be in 'main.yml': line 27, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Performing managed server)\n ^ here\n"}

expecting it to run on 003 or 004 if server is like *app02

Upvotes: 0

Views: 43

Answers (1)

Zeitounator
Zeitounator

Reputation: 44615

As a start, 2 enhancements that are not the source of your error:

  • your first condition can be simplified for performance, readability and scalability by checking for the presence of a value in a list with the in test rather than making all tests one after the other.
  • you're not using default values in case your vars are undefined which can lead to more errors when running (i.e. variable xxxx is undefined)

Your real problem is the second condition which:

  • is applying a filter returning a string rather than making a boolean test (e.g. is <some_test>, == 'some_value', ...)
  • receives as a parameter something that is not a regex (or at least not the one you seem to be looking for)

Since you're just looking for a substring, the most straightforward way is to use search.

Here is a fixed version:

  when:
    - target_clone | d('') in ['003', '004']
    - tgt_secondary_servers | d('') is search('app02')

References:

Upvotes: 2

Related Questions