1

I have an extra variable in my command to execute the Ansible playbook. I would like to assign another variable only if the extra variable has the prefix database + "/"

For example:

ansible-playbook ./test.yml -e "branch=database/1.3.4"

The variable(branch) has prefix database + "/" I would like to assign one more variable(version) as 1.3.4

  tasks:
  - name: Extract Version Number
    ansible.builtin.set_fact:
      version: "V{{ branch.split('/')[1] }}"
    when: "{{ branch | regex_search('release/') }}"

But I received this error message:

FAILED! => {"msg": "The conditional check '{{ branch | regex_search('database/') }}' failed.

I am very new to Ansible, any help is appreciated!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
ITnewbie
  • 460
  • 6
  • 23

2 Answers2

2

you could do something like this:

  tasks:
    - name: setfact
      set_fact:
        version: "V{{ branch.split('/')[1] }}"
      when: branch | d('') | regex_search('database/')
    
    - debug:  
        msg: "{{ version if version is defined else 'nothing'}} - {{branch | d('') }}"
Frenchy
  • 16,386
  • 3
  • 16
  • 39
1

Q: Assign another variable only if the variable has the prefix 'database + /'

A: If you want to use the regex_search filter to test the condition start searching from the beginning of the string. Note the '^' character in the regex. For example,

    - debug:
        var: branch
    - set_fact:
        version: "{{ branch.split('/')[1] }}"
      when: branch|regex_search('^database/')
    - debug:
        var: version

regex_search returns an empty string if it cannot find a match. This works as expected because, in a condition, an empty string evaluates to False and any non-empty string evaluates to True

  branch: database/1.3.4
  version: 1.3.4

If you omit the leading '^' the filter will return any match in the string. This is not what you want. For example,

   - debug:
        var: branch
    - set_fact:
        version: "{{ branch.split('/')[1] }}"
      when: branch|regex_search('database/')
    - debug:
        var: version

regex_search matches the regex also behind the prefix 'sql-'

  branch: sql-database/1.3.4
  version: 1.3.4

But, instead of using the filter regex_search, you might want to simply compare the strings. For example, the task below also gives what you want

    - set_fact:
        version: "{{ arr.1|d('undef') }}"
      when: arr.0 == 'database'
      vars:
        arr: "{{ branch|d('undef')|split('/') }}"

If you need more complex conditions see Testing strings.

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63