I have a question, with optional input of A or B in vars_prompt can the command be executed in a playbook task.
example
name: checking the switchshow
value_command:
command_set:
command: switchdisable
command: switchshow
Like with vars_prompt if we select A 1st command need to execute if B second command need to execute
Can this be achieved with Ansible ?
Rahul_Puli
(Rahul Puli)
October 22, 2020, 9:27am
2
Yes, this can be achievable. You can use when condition.
can we have multiple when conditions in a single task?
vars_prompt:
name: input
prompt: Please enter the option A,B,C
private: no
name: checking the switchshow
value_command:
command_set:
command: ipaddr
command: ifconfig
command: freespace -m
command: yum repolist
With the above options input A, B, C specific commands associated with that option need to be executed. All the commands are there in a single task.
A - ipaddr
B - ifconfig
C - freespace -m , yum repolist
vbotka
(Vladimir Botka)
October 22, 2020, 10:11am
4
can we have multiple when conditions in a single task?
vars_prompt:
- name: input
prompt: Please enter the option A,B,C
private: no
- name: checking the switchshow
value_command:
command_set:
- command: ipaddr
- command: ifconfig
- command: freespace -m
- command: yum repolist
Instead of a list, put the commands into a dictionary. Test with
debug first. For example
vars:
command_set:
B: ifconfig
C: freespace -m
D: yum repolist
vars_prompt:
- name: input
prompt: Please enter the option {{ command_set.keys()|list }}
private: no
tasks:
- debug:
msg: Command {{ command_set[input] }}
when: input in command_set.keys()|list
You'll be better off with "Data driven programming" in similar
use-cases. See
https://stackoverflow.com/questions/1065584/what-is-data-driven-programming
Thank you @Vladimir for the solution. I will test this and share you the update. value_command is the module, do we need to add the vars in the module ?
vars:
command_set:
B: ifconfig
C: freespace -m
D: yum repolist
vars_prompt:
name: input
prompt: Please enter the option {{ command_set.keys()|list }}
private: no
tasks:
vbotka
(Vladimir Botka)
October 22, 2020, 11:58am
6
... value_command is the module, do we need to add the vars in the
module ?
vars:
command_set:
A: ipaddr
B: ifconfig
C: freespace -m
D: yum repolist
It's up to you where you put the variables. Yes, module is one of the
options. Mind the indentation. For example
- command: "{{ command_set[input] }}"
vars:
command_set:
B: ifconfig
C: freespace -m
D: yum repolist
But, the point here is to manage the control-flow by data. Using the
hard-coded data you get rid of this advantage. See
"Variable precedence: Where should I put a variable?"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable
Thank you @Vladimir provided solution worked for me. But do we have an option to pass both commands with a single option input like:
D: freespace -m
yum repolist