how to use variable in "when" statement in ansible? - ansible

I am trying to use a variable in when statement in ansible ,
my code snippet looks like this :
- name: git repo for non prod env
git:
repo=http://url/repo.git
dest=/opt/dest
version={{ bld_env }}
when: ( "{{ bld_env }}" == "rc" ) or ( "{{ bld_env }}" == "sandbox" ) or ( "{{ bld_env }}" == "dev" ) or ( "{{ bld_env }}" == "qa" )
This is not working and gives an a error as :
The offending line appears to be:
version={{ bld_env }}
when: "{{ bld_env }}" == "rc"
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
Let me know where I am wrong.

I think you don't have to use "{{ bld_env }}" == "rc".
Just compare variable to value bld_env == "rc" and so on as it is written in documentation

Related

Ansible play fails with_items FOO

- name: Debug msg for imagepull {{ ansible_operator_meta.name }}
debug:
msg: "{{ final_resource_checks_pod_status_check_filtered_image }}"
I got an error with below
- name: Debug msg for imagepull {{ ansible_operator_meta.name }}
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"

Ansible how to ignore undefined item in a loop

I'm trying to have list of paths.
The variables folder (web_folder, app_folder or db_folder ) may be undefined and is expected to be undefined.
In this case I just don't want the undefined value in the the list.
- set_fact: root_paths="{{ root_paths | default([]) + [ item ] }}"
loop:
- "{{ web_folder }}"
- "{{ app_folder }}"
- "{{ db_folder }}"
when: item is defined
When I do this I get an error message 'The task includes an option with an undefined variable.'
I can make this work if I define default values e.g. '-' and replace the when condition with
when: item != '-'
I don't like this solution.
I tried a few things like
'when: vars[item] is undefined' from this post, but it didn't work for me.
I also replaces 'loop' with 'with_items' didn't work either
Any suggestions?
The variables folder (web_folder, app_folder or db_folder ) may be undefined and is expected to be undefined.
you could use the default filter to initialize them to an empty array, in case they are not defined:
- set_fact: root_paths="{{ root_paths | default([]) + [ item ] }}"
loop:
- "{{ web_folder | default([]) }}"
- "{{ app_folder | default([]) }}"
- "{{ db_folder | default([]) }}"
when: item is defined
hope it helps.
Q: I get an error message 'The task includes an option with an undefined variable.' I can make this work if I define default values e.g. '-' and replace the when condition with when: item != '-'. I don't like this solution.
A: The expansion of an undefined variable causes the error. Either the variables are tested explicitly or default filter is used.
Testing each variable is cumbersome
tasks:
- set_fact:
folders_defined: []
- set_fact:
folders_defined: "{{ folders_defined + [web_folder] }}"
when: web_folder is defined
- set_fact:
folders_defined: "{{ folders_defined + [app_folder] }}"
when: app_folder is defined
- set_fact:
folders_defined: "{{ folders_defined + [db_folder] }}"
when: db_folder is defined
- debug:
var: folders_defined
The next option (which is very similar to the one you don't like) is to test a default value assigned to undefined variables. For example, the playbook below tests default empty string. If necessary fit this condition to your needs.
- hosts: localhost
vars:
web_folder: /my/web/folder
app_folder: /my/app/folder
folders: [web_folder, app_folder, db_folder]
tasks:
- set_fact:
folders_defined: "{{ folders_defined|default([]) +
[lookup('vars', item)] }}"
loop: "{{ folders }}"
when: lookup('vars', item, default='')|length > 0
- debug:
var: folders_defined
gives
ok: [localhost] => {
"folders_defined": [
"/my/web/folder",
"/my/app/folder"
]
}

Ansible change default value according to a condition

I need to help with Ansible and make variable base on condition with another user defined variable.
I wrote something like this, but I am pretty sure this is wrong script.
So "{{ vcpu_size }}" has to be define base on user defined "{{ vm_size }}" and I don't know how to do it
Thanks for help
---
- name: Deploy VM on XenServer
hosts: XEN_Server
become: true
tasks:
- name: Load VPS specs for chosen type
set_fact:
vcpu_size: "{{ '2' if ({{ vm_size }} == 'S') }}"
vcpu_size: "{{ '4' if ({{ vm_size }} == 'M') }}"
vcpu_size: "{{ '6' if ({{ vm_size }} == 'L') }}"
vcpu_size: "{{ '8' if ({{ vm_size }} == 'XL') }}"
- debug:
msg: "Write {{ vcpu_size }} and to be sure {{ vm_size }}"
You can define the sizes in group_vars/all, or somewhere else (such as vars for the role, or in the playbook itself):
sizes:
S: 2
M: 4
L: 6
XL: 8
Then use it like this:
set_fact:
vcpu_size: "{{ sizes[vm_size] }}"
You can use Jinja expression like this :
vcpu_size: "{% if vm_size == 'S' %}2{% elif vm_size == 'M' %}4{% else %}some_def_value_here{% endif %}"

Ansible condition on dictionary item

I have one dictionary list defined:
members_list:
any:
name: any
username: any
anyone:
name:
username: anyone
In my Ansible playbook, I am running multiple docker containers:
docker_container:
name: "{{ item.key }}"
when: "{{ item.key }} != any"
with_dict: "{{ members_list }}"
But I am getting following error:
The conditional check '{{ item.key }} != any' failed. The
error was: error while evaluating conditional ({{ item.key
}} != any): 'any' is undefined
When I run the playbook without when conditional operator it works fine.
Thanks in advance.
You need to quote the word any, because otherwise it is interpreted as a variable reference. Also, you don't need Jinja templating markers in a when expression (the expression is already evaluated as a jinja expression):
- docker_container:
name: "{{ item.key }}"
when: "item.key != 'any'"
with_dict: "{{ members_list }}"
I find nested quotes like this can be confusing, and often opt for one
of YAMLs alternative quoting mechanisms, e.g.:
- docker_container:
name: "{{ item.key }}"
when: >-
item.key != 'any'
with_dict: "{{ members_list }}"
This is identical to the previous version; I just find it easier to
read and understand.

Conditional ansible to set variable

Tried all luck but doesnot work. I would require to set the environment variable check with a condition and then run a play or task on the main.yml while doing includes and using 2 tasks.
main.yml
- include: createnonprod.yml
when: "{{ environment }}" == 'dev' or "{{ environment }}" == 'qa' or "
{{ environment }}" == 'preprod'
- include: createprod.yml
when: "{{ environment }}" == 'prod'
The environment is set on groups_vars variable file "all"
environment:
"{{ lookup('env','ENVIRONMENT') }}"
But this logic to check fails
(Or)
I need to run this logic so that it calls the task with a condition to check the variable
create.yml
- name: Install all users from IAM of the AWS Account.
shell: "{{ scriptdir }}/install.sh -i {{ iamgroup }},{{ sudogroup }} -s {{ sudogroup }}"
when: "{{ environment }}" == 'dev' or "{{ environment }}" == 'qa' or "{{ environment }}" == 'preprod'
- name: Install all users from IAM of the AWS Account.
shell: "{{ scriptdir }}/install.sh -i {{ iamgroup }},{{ sudogroup }} -s {{ sudogroup }}"
when: "{{ environment }}" == 'prod'
Please help me with a logic that works. I get this error:
fatal: [localhost]: FAILED! => {"failed": true, "reason": "ERROR!
Syntax Error while loading YAML.\n\n\nThe error appears to have been in
'/tmp/ansible/roles/provision/users/tasks/create.yml': line 18, column
22, but may\nbe elsewhere in the file depending on the exact syntax
problem.\n\nThe offending line appears to be:\n\n when:\n - {{
env_type }} == 'dev'\n ^ here\nWe could be wrong,
but this one looks like it might be an issue with\nmissing quotes.
Always quote template expression brackets when they\nstart a value. For
instance:\n\n with_items:\n - {{ foo }}\n\nShould be written
as:\n\n with_items:\n - \"{{ foo }}\"\n"}
The When Statement
The when clause, which contains a raw Jinja2 expression without
double curly braces
when: environment == 'dev' or environment == 'qa' or environment == 'preprod'
when: environment == 'prod'
What if you try this way.
Define a variable to handle the lookup of your environment:
vars:
env_value: "{{ lookup('env', 'ENVIRONMENT') }}"
and then use this variable in the when condition:
when: env_value == "dev"
Simple example:
- hosts: "localhost"
vars:
env_value: "{{ lookup('env', 'ENVIRONMENT') }}"
tasks:
- shell: echo "I've got {{ env_value }} and am not afraid to use it!"
when: env_value == "prd"
Example in your code:
- name: Install all users from IAM of the AWS Account.
shell: "{{ scriptdir }}/install.sh -i {{ iamgroup }},{{ sudogroup }} -s {{ sudogroup }}"
when: env_value == 'dev' or env_value == 'qa' or env_value == 'preprod'
Please, also look at this link about Ansible environment variable name being reserved.

Resources