ansible jinja2 template delimiters failed if using 'when' - ansible

I have this code, where the first task fails and the second task produces the following warning:
[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{ VRF }} == 17
I am assuming this warning and the failure of the first task are happening for the same reason. From what I understand, the variables are different types. How do I fix this?
---
- name: PE_CE
hosts: localhost
tasks:
- include_vars: /opt/netsec/ansible/orchestration/capabilities/PE_CE/PE_CE_1.yml
- name: Build PE config Cisco
template:
src=/opt/netsec/ansible/orchestration/cisco_templates/PE_CE_CISCO_config_PE.j2
dest=/opt/netsec/ansible/orchestration/config_outputs/new/{{PE_HOSTNAME}}
when: "{{ PX_HOSTNAME }} == None"
- name: Build CE config Cisco
template:
src=/opt/netsec/ansible/orchestration/cisco_templates/PE_CE_CISCO_config_CE.j2
dest=/opt/netsec/ansible/orchestration/config_outputs/new/{{CE_HOSTNAME}}
when: "{{ VRF }} == 17"
What I really want to do is when: "{{ VRF }} == 17" and "{{ PX_HOSTNAME }} == None", or something like {{ PX_HOSTNAME }}|length < 1"

You do not need {{ and }} with when. Do it like this:
when: PX_HOSTNAME == "None" and when: VRF == "17"
Here is some documentation
when: PX_HOSTNAME == "None" will check if PX_HOSTNAME contains the string "None".
If you want to run the task if it is empty, do when: not PX_HOSTNAME or if you want to run the task it it is not empty, do when: PX_HOSTNAME.
You can use the length as well: when: PX_HOSTNAME|length > 0

Related

ansible variables usage - ansible_hostname or {{ ansible_hostname }}

I am new to ansible. What is the correct to call ansible variables? Here are the 3 playbooks, playbook 1 uses "{{ ansible_hostname }}", however, playbook 2 and 3 uses "ansible_hostname" directly. What are the differences? Thanks!
Playbook 1:
tasks:
- name: Jinja2 template
template:
src: template.j2
dest: "/tmp/{{ ansible_hostname }}_template.out"
trim_blocks: true
mode: 0644
Playbook 2:
tasks:
- name: Ansible Jinja2 if
debug:
msg: >
--== Ansible Jinja2 if statement ==--
{# If the hostname is ubuntu-c, include a message -#}
{% if ansible_hostname == "ubuntu-c" -%}
This is ubuntu-c
{% endif %}
Playbook 3:
tasks:
- name: Exploring register
command: hostname -s
when:
- ansible_distribution == "CentOS"
- ansible_distribution_major_version | int >= 8
register: command_register
playbook 1 uses "{{ ansible_hostname }}", however, playbook 2 uses "ansible_hostname"
That's not entirely correct. Both playbooks use the variable name ansible_hostname inside a Jinja templating context.
In the first playbook, it's simple variable substitution, so we use the {{ ... }} markers.
In the second playbook, it's being used in a control expression, so we use the {% ... %} markers.
In the third playbook, you're looking at the clauses of a when expression. From the documentation:
The when clause is a raw Jinja2 expression without double curly braces...
You can read more about Jinja syntax here.

Ansible search sublists for value

A webhook triggers an AWX job and I want to run the deployment on a certain host depending on the service, since they run on different servers. I need to know which server uses that service to set is as a var so it can be used as a host in the following play.
My variable inside vars.yaml looks like this:
staging_hosts:
server1: ['service1', 'service2', 'service3']
server2: ['service4', 'service5', 'service6']
server3: ['service7', 'service8', 'service9']
Playbook:
- name: write deployment hosts
hosts: localhost
vars:
deployment_hosts: absent
vars_files:
- ./group_vars/vars.yaml
tasks:
- set_fact:
modified_repos: (small regex filter to find modified repository)
- set_fact:
deployment_hosts: "{{ item }}"
when: '{{ modified_repos }} in {{ item }}'
with_list:
- "{{ staging_hosts }}"
- name: connect to Cluster
hosts: "{{ hostvars['localhost']['deployment_hosts'] }}"
What can I do against this warning and error?
[WARNING]: conditional statements should not include jinja2 templating
delimiters such as {{ }} or {% %}. Found: {{ modified_repos }} in {{ item }}
fatal: [localhost]: FAILED! => {"msg": "The conditional check '{{ modified_repos }} in {{ item }}' failed. True {% else %} False {% endif %}): unhashable type: 'list'
Oh I forgot to mention. It is important, that deployment_hosts could also contain two hosts if modified repos include for example service1 and service4.
Q: "deployment_hosts could also contain two hosts if modified repos include for example service1 and service4."
A: Use intersect filter. For example, the playbook
- hosts: localhost
vars:
staging_hosts:
server1: ['service1', 'service2', 'service3']
server2: ['service4', 'service5', 'service6']
server3: ['service7', 'service8', 'service9']
modified_repos: ['service1', 'service4']
tasks:
- set_fact:
deployment_hosts: "{{ deployment_hosts|default([]) + [item.key] }}"
loop: "{{ staging_hosts|dict2items }}"
when: modified_repos|intersect(item.value)|length > 0
- debug:
var: deployment_hosts
gives
deployment_hosts:
- server1
- server2

Ansible condtional statement with stdout and variable

I am trying to use a condition to verify the MD5_hash value from the std output with the stored value in the host file.
- block:
- name: Install OS
nxos_install_os:
provider: "{{ creds }}"
system_image_file: "{{bin}}"
issu: no
timeout: 500
when: md5_result.stdout[0] == "{{ MD5_Hash }}"
[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found:
md5_result.stdout[0] == "{{ MD5_bin5 }}"
I found a suggestion of using [] instead of {{}}, but I am just getting the condition result is FALSE.
Please suggest.

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 %}"

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