'Set a variable according to another variable

I am working on a gitlab-ci project.
I have a variable A that I retrieve from a form.
I have to set another variable B in my playbook.

If A matches a certain regex, B should be ' -p A' else B should be an empty string ''.
This should be written in an Ansible file.

I have tried

- set_fact: 
  B="{{ ' -p ' + A}}"
  when: A is regex("^\\d{1,8}$")

but it didn't work.
Can someone help me?



Solution 1:[1]

Q: "If A matches a certain regex, B should be ' -p A' else B should be an empty string ''."

A: Use the filter ternary, e.g.

  B: "{{ (A is regex('^\\d{1,8}$'))|ternary(' -p ' ~ A, '') }}"

Test it

    - debug:
        msg: 'A: {{ A }} -> B: "{{ B }}"'
      loop:
        - 1234567
        - 12345678
        - 123456789
        - xyz12345
      loop_control:
        loop_var: A

gives (abridged)

  msg: 'A: 1234567 -> B: " -p 1234567"'
  msg: 'A: 12345678 -> B: " -p 12345678"'
  msg: 'A: 123456789 -> B: ""'
  msg: 'A: xyz12345 -> B: ""'

Q: "This should be written in an Ansible file."

A: You can put it into a file if you want to, e.g.

shell> cat set_B.yml 
B: "{{ (A is regex('^\\d{1,8}$'))|ternary(' -p ' ~ A, '') }}"

Then you can use it in many ways, e.g. use include_vars

    - include_vars: set_B.yml

or put it into the group_vars, host_vars, ... See Variable precedence: Where should I put a variable?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vladimir Botka