DebugFactor.com | Forum

How to assign variable with inline if-else condition in Ansible?

I have two similar tasks with different condition. Is there a way to merge this in a single task. I am trying to avoid repetition of code.

For example:

- set_fact:
  port: 22
  when: protocol == 'ssh'

- set_fact:
  port: 21
  when: protocol == 'ftp'

Yes, you can do it. Please see below.

- set_fact:
  port: "{{ '22' if protocol == 'ssh' else '21' if protocol == 'ftp'}}"
  

Hope this helps!