Home > Software design >  Ansible define variable if match in regex
Ansible define variable if match in regex

Time:06-11

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!

CodePudding user response:

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('') }}"
  • Related