How do I reference variable in Jinja Ternary operation?

Viewed 22

How do I reference a variable inside the ternary operation?

ex: shell: "{{some_conditon == "True" | ternary('/bin/mycommand -F some_str_var', '/bin/myOtherCmmand -S some_str_var') }}"

1 Answers

Concatenate the strings

    - debug:
        msg: "{{ (some_str_var == 'True') | ternary('echo ' ~ some_str_var, 'echo False') }}"

You might want to put the options into a dictionary instead of the long ternary strings. For example, the playbook

shell> cat pb.yml
- hosts: localhost

  vars:

    some_str_var: "False"
    cmd:
      result1: "/bin/mycommand -F True"
      default: "/bin/mycommand -S {{ some_str_var }}"
        
  tasks:

    - debug:
        msg: "{{ cmd[some_condition]|default(cmd.default) }}"

gives

shell> ansible-playbook pb3.yml -e some_condition=result1
...
  msg: /bin/mycommand -F True
shell> ansible-playbook pb3.yml -e some_condition=resultX
...
  msg: /bin/mycommand -S False
Related