In ansible, how can I assign values to variable based on conditions? - ansible

I want to assign a value to a variable based on my env name. If env=e1, some variable name "var" should get the value as "x". If env=e2, "var" should get the value as "y".
Let me know your suggestions!

Say you have an env var called FOO.
- hosts: localhost
gather_facts: "False"
vars:
my_env_var: "{{ lookup('env','FOO') }}"
tasks:
- name: "set e1"
set_fact:
my_ansible_var: "x"
when: my_env_var == "e1"
- name: "set e2"
set_fact:
my_ansible_var: "y"
when: my_env_var == "e2"
You can now reference the {{ my_ansible_var }} value anywhere it is needed.

Related

Ansible to print the variable value having another variable inside it

In a.yml file, I have stored data like below
---
Server:
"Node1" : ["Node1", "Owner1", "ID1"]
"Node2" : ["Node2", "Owner2", "ID2"]
Now, in xyz.yml playbook, I tried to debug a variable as below and I am passing the Node_Name in commandline (ansible-playbook xyz.yml -e "Node_Name=Node1")
---
- name: "Print Variable value"
hosts: all
gather_facts: no
vars:
Node_Name: Node
ID_Name: "{{ Server.{{ Node_Name }}[2] }}"
tasks:
- name: "Print the id"
debug:
msg:
- "The id is {{ ID_Name }}"
But this is failing with error - Template error while templating string :expected name or number
Can someone please help to fix this and let me know how can I get the ID printed as output. Here expected output is ID1
You never nest {{...}} markers.
Recall that to access a nested variable. the syntax Server.Node1 is exactly equivalent to Server["Node1"]. The second syntax allows us to make use of variables (and string interpolation) on the key, so we can write:
Server[Node_Name]
In other words:
- name: "Print Variable value"
hosts: all
gather_facts: no
vars:
Node_Name: Node
ID_Name: "{{ Server[Node_Name][2] }}"
tasks:
- name: "Print the id"
debug:
msg:
- "The id is {{ ID_Name }}"

How to restrict scope of set_fact variable in ansible

below is my ansible playbook for validation of objects - I am first using validateip role and under that executing login,validation and then logout tasks.
- name: validate object
vars:
mserver: [1.1.1.1,2.2.2.2]
domain: [3.3.3.3,4.4.4.4]
tasks:
- include_role:
name: validateip
when: object_type == "ip"
with_together:
- "{{ mserver_hostname }}"
- "{{ domain }}"
- name: Checking Network objects
uri:
url: "https://{{item.0}}/web_api/show-objects"
validate_certs: False
method: POST
headers:
x-chkp-sid: "{{ login.json.sid }}"
body:
type: host
filter: "{{ip}}"
ip-only: true
body_format: json
register: check_host_result
when: item.0 != ""
- debug:
var: check_host_result
- name: Checking if Network Object exists
set_fact:
item_ip_exists: true
obj_name: "{{ item2['name'] }}"
loop: "{{ check_host_result.json.objects }}"
loop_control:
loop_var: item2
when:
- item2['ipv4-address'] is defined and item2['ipv4-address'] == ip
- debug:
msg: "Network Object exists with name [{{obj_name}}]"
when: item_ip_exists is defined
- debug:
msg: " Network Object ({{ip}}) will be created"
when: item_ip_exists is not defined
I am facing issue for set_fact variable like obj_name and item_ip_exists
so when loop runs on first item and if object is present so it set both the variable (obj_name and item_ip_exists ) and print the correct debug messages.
but when 2nd item executed and there if object is not present so it is printing the wrong debug message due to the set_fact variables( obj_name and item_ip_exists) which has already the value from the first items execution
so how i can restrict the scope of set_fact variables ( obj_name and item_ip_exists ) so when second item execute the variables take the value from there not from previously set_fact values.
I am totally stuck here.
Please help me. Thanks in advance.
Alas, the variable that is set by set_fact stays defined (for the same host) and keeps the value that had been assigned on the previous loop's pass.
As a solution (which is pretty ugly, to be frank) you may want to redefine the variable's value in the very beginning of the loop and set it to None by something like this:
- set_fact:
my_variable:
Then you'll have to check if it's equal or unequal to None. Alas, no one could undefine a previously defined variable in Ansible, that's why your condition won't be my_variable is undefined, but will be my_variable | default(None) == None.
Ugly, right.

Ansible variable precedence - Reset overriden variable value back to the group_vars value

How Can I reset an overriden variable in a playbook back to the value that is defined in group_vars for that variable
So for example, If I have variable name: "Hello from group_vars" defined in group vars, but during the executin playbook I override it base on some condition with set fact
set_fact:
name: "Overriden somewhere in playbook only for the next task"
when: << some condition that is ture >>
name: Next task
debug:
msg: "Name is {{ name }}" # This will show value from the set_fact
but for the next task I would want to reset the name to the value to the one that has beeen set in group_vars while still in the same playbook execution
set_fact:
name: << How to reset it to group_vars value logic >>
Name: Show the value
debug:
msg: "Nanme is {{ namne }}" # This now should show the value set in group_vars "Hello from group vars"
Any ideas on how to achieve this. Thanks
Generally, once you set_fact for a host, you can't go back, unless you store a copy of the original value and set_fact again later, or re-gather the facts layer (by using a different play in your play book, for example).
If you can, use a specialized fact (and maybe defaults) to achieve a similar goal.
For example:
- name: conditionally set fact
set_fact:
special_name: "overridden value"
when: my_condition
- name: use fact or default
debug:
msg: "Name is {{ special_name | default(name)}}"
If you want to use your overridden value more frequently, you might use a second variable to handle the assignment:
- name: conditionally set fact
set_fact:
special_name: "overridden value"
when: my_condition
- name: use default globally
set_fact:
special_name: "{{ special_name | default(name) }}"
- name: use fact or default
debug:
msg: "Name is {{ special_name }}"
It's a little longer, but it gets you a value you can count on in multiple locations without having to put the default in multiple places.

Set Ansible role defaults conditionally

Pseudocode:
If env is de, set variable name to hello else if env is prod, set variable name to bye.
I tried https://serverfault.com/questions/715769/ansible-change-default-value-according-to-a-condition
- name: setting variable
set_fact: name="hello"
when: "{{ env }}" == "de"
- name: setting variable
set_fact: name="bye"
when: "{{ env }}" == "prod"
ERROR! The default/main.yml file for role 'trial' must contain a
dictionary of variables
As per my requirement, it needs to be done in role.So it is done as follows:
name: "{% if env == 'de' %}hello{% elif env == 'prod' %}bye{% endif %}"

Conditionally define variable in Ansible

I want to conditionally define a variable in an Ansible playbook like this:
my_var: "{{ 'foo' if my_condition}}"
I would like the variable to remain undefined if the condition does not resolve to true.
Ansible gives the following error if I try to execute the code:
fatal: [foo.local] => {'msg': 'AnsibleUndefinedVariable: One or more undefined
variables: the inline if-expression on line 1 evaluated
to false and no else section was defined.', 'failed': True}
Why is this an error anyway?
The complete case looks like this:
{role: foo, my_var: "foo"}
If my_var is defined, the role does something special. In some cases, I don't want the role to do this. I could use when: condition, but then I would have to copy the whole role block. I could also use an extra bool variable, but I would like a solution without having to change the "interface" to the role.
Any ideas?
You could use something like this:
my_var: "{{ 'foo' if my_condition else '' }}"
The 'else' will happen if condition not match, and in this case will set a empty value for the variable. I think this is a short, readable and elegant solution.
This code may help you to define a variable with condition.
- hosts: node1
gather_facts: yes
tasks:
- name: Check File
shell: ls -ld /etc/postfix/post-install
register: result
ignore_errors: yes
- name: Define Variable
set_fact:
exists: "{{ result.stdout }}"
when: result|success
- name: Display Variable
debug: msg="{{ exists }}"
ignore_errors: yes
So here the exists will display only if the condition is true.
My example, after https://stackoverflow.com/a/43403229/5025060:
vars:
sudoGroup: "{{ 'sudo' if ansible_distribution == 'Ubuntu' else 'wheel' }}"
Because of the different sudo conventions used by Ubuntu versus other platforms, here I am telling Ansible to set a variable named sudoGroup to sudo if the platform is Ubuntu, otherwise set it to wheel.
Later in my playbook, I combine the variable with Ansible's user module to add either sudo or wheel to an account's secondary groups depending on the OS Ansible is running on:
- name: Add or update bob account
user:
name: bob
uid: 3205
groups: "{{ sudoGroup }}"
append: yes
NOTES:
Double quotes around the {{ variable }} are required in the user: groups: definition above.
Once I define sudoGroup as above in my playbook's global vars: section, Ansible configures it at run time (based on ansible_distribution) for each target I define in my hosts: section.
I believe you're after the default(omit) filter. (Reference).
As per the example, mode will behave like it wasn't set at all for the first two items in the loop.
- name: touch files with an optional mode
file:
dest: "{{item.path}}"
state: touch
mode: "{{item.mode|default(omit)}}"
loop:
- path: /tmp/foo
- path: /tmp/bar
- path: /tmp/baz
mode: "0444"
This can be set as with bool:
- name: Conditional (true and false)
set_fact:
my_boolean_set_to_be: "{{ 'true' if my_var == 'foo' else 'false' }}"
- name: Display Variable
debug: msg="{{ my_boolean_set_to_be }}"
This can be set as for more conditionals like 'if-ifelse-else' statements:
- name: Conditional for 'my_var' (2 options and one default)
set_fact:
my_var_set_to_be: "{{ 'breakfast' if my_var == 'morning' else 'lunch' if my_var == 'afternoon' else 'dinner' }}"
- name: Display Variable
debug: msg="{{ my_var_set_to_be }}"

Resources