Based on extra vars
parameter I Need to write variable value in ansible playbook
ansible-playbook playbook.yml -e \"param1=value1 param
I am sure there is a smarter way for doing what you want but this should work:
- name : Test var
hosts : all
gather_facts : no
vars:
myvariable : false
tasks:
- name: param1
set_fact:
myvariable: "{{param1}}"
when: param1 is defined
- name: param2
set_fact:
myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
when: param2 is defined
- name: param3
set_fact:
myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
when: param3 is defined
- name: default
set_fact:
myvariable: "default"
when: not myvariable
- debug:
var=myvariable
Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
my_var: the variable declared
VAR: the variable, whose value is to be checked
param_1, param_2: values of the variable VAR
value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var
my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"