I have a list of proxies that need to be selected based on the cluster location. For example, my cluster names are 'abc' and 'def'. All nodes on clusters start with the cluster name (e.g. abc1023.net for abc etc.)
I want to select the proxies for pip based on the current inventory_hostname and provide it in the arguments. I tried to use the map of with_items and 'creating' the when condition within the map as per the code below:
- name: run pip on proxy
pip:
name: <package_name>
extra_args: "--proxy item.proxy"
when: "item.when"
with_items:
- {proxy: 'http:abc_proxy:port', when: "'abc' in {{inventory_hostname|lower}}"}
- {proxy: 'http:def_proxy:port', when: "'def' in {{inventory_hostname|lower}}"}
The problem I am facing is that this condition is always perceived as true. I tried replacing when: "'abc' in {{inventory_hostname|lower}}" to when: false and that actually works. That is, making it an explicit false actually returns false but not when I check the condition in string quotes. I think this when within the map is just perceived as true if it contains any value.
How do I explicitly check this condition in the when map? Removing the quotes does not help as it throws syntactical error:
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 }}"
exception type: <class 'yaml.parser.ParserError'>
Other solutions tried
Added the vars within the task
- name: run pip on proxy
vars:
abc_status: "{{ true if 'abc' in {{inventory_hostname|lower}} else false }}"
def_status: "{{ true if 'def' in {{inventory_hostname|lower}} else false }}"
pip:
name: <package_name>
extra_args: "--proxy item.proxy"
when: "item.when"
with_items:
- {proxy: 'http:abc_proxy:port', when: abc_status}
- {proxy: 'http:def_proxy:port', when: def_status}
2.Added the task to set_fact
- set_fact:
abc_status: true
when: inventory_hostname|lower is match('abc.*')
- set_fact:
def_status: true
when: inventory_hostname|lower is match('def.*')
Tested the false case
I tested the false case in the following ways on abc cluster:
- name: run pip on proxy
vars:
abc_status: "{{ true if 'abc' in {{inventory_hostname|lower}} else false }}"
def_status: "{{ true if 'def' in {{inventory_hostname|lower}} else false }}"
pip:
name: <package_name>
extra_args: "--proxy item.proxy"
when: "item.when"
with_items:
- {proxy: 'http:def_proxy:port', when: def_status}
This should always fail as the proxy as well as the when condition is checking on def cluster whereas it is running on abc cluster. But I get the following Ansible output:
TASK [<project> : run pip on proxy] ************************************************
changed: [abc1023.net] => (item={u'when': u'def_status', u'proxy': u'http:def_proxy:port'})
This is the output I always get with other tried solutions as well.
Question
Even after trying above different solutions, when: "item.when" always return true (even when it should return false). How can I fix this? Is there any better solution to implement my use case?
For completeness, I am using ansible 2.4.1.0.
TL;DR;
Here, you are trying to assess that the string "item.when" is a boolean that is true, which it is, because, a non empty string will result in a true statement.
Remove your doubles quotes around the when condition and you should be good to go.
The warning you get from Ansible is about when and only this statement, which is always a raw Jinja2 expression.
This is easy to do in Ansible with the when clause, which contains a raw Jinja2 expression without double curly braces (see group_by – Create Ansible groups based on facts).
Source: https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement, emphasis, mine.
Given your actual playbook, a possible solution could be:
- name: run pip on proxy
pip:
name: <package_name>
extra_args: "--proxy {{ item.proxy }}"
when: item.proxy_ref in inventory_hostname|lower
with_items:
- proxy: 'http:abc_proxy:port'
proxy_ref: 'abc'
- proxy: 'http:def_proxy:port'
proxy_ref: 'def'
Another one could be:
- name: run pip on proxy
pip:
name: <package_name>
extra_args: "--proxy {{ item.proxy }}"
when: item.when
with_items:
- proxy: 'http:abc_proxy:port'
when: "{{ 'abc' in inventory_hostname|lower }}"
- proxy: 'http:def_proxy:port'
when: "{{ 'def' in inventory_hostname|lower }}"
So, in short, here, you are trying to assess that the string "item.when" is a boolean that is true, which it is, because, a non empty string will result in a true statement.
Remove your doubles quotes around the when condition and you should be good to go.
PS: try not to mix the JSON syntax with the YAML one, when possible
Q: "Is there any better solution to implement my use case?"
A: You might be better off with the concatenation of the proxy. For example
- name: run pip on proxy
pip:
name: "{{ package_name }}"
extra_args: "--proxy {{ my_proxy }}"
vars:
my_prefix: "{{ inventory_hostname[0:3] }}"
my_proxy: "{{ 'http:' ~ my_prefix ~ '_proxy:port' }}"
Related
I'm trying to create ansible playbook that will use variables if they are defined without using "while:" and manually typing the undefined variables & duplicating tasks.
For example I have the below variables:
vars:
service_List:
- 1:
state: present
address_type: ipv4
ip: 10.0.0.0
- 2:
state: present
jump: true
ip: 10.5.5.0
hold_true: yes
- 3:
state: present
address_type: ipv4
is_enabled: true
dhcp: none
I want to have a single task that will use the above variables on a specific module.
example of a task: (notice the with_dict)
tasks:
- name: task name here
some_module:
**This here will include the code for adding the variables form vars**
**So for example, for 1st dict it will include state, address_type and ip**
**for 2nd dict it will include variables state,jump,ip,hold_true**
**example: state: "{{ item.value.state }}"
with_dict: "{{ service_List }}"
Please help with missing code inside the task
It depends on the some_module use case. In particular, whether the parameters are required or not. And, if required, whether there is a default value or not. There are three options if a parameter is missing in the dictionary
The parameter is not required. Use default(omit)
The parameter is required. Use default(defaul_value_of_this_param)
The parameter is required but there is no default. The module will crash.
For example,
tasks:
- name: task name here
some_module:
state: "{{ item.value.state }}"
address_type: "{{ item.value.address_type|default('ipv4') }}"
ip: "{{ item.value.ip|default(omit) }}"
jump: "{{ item.value.jump|default(False) }}"
hold_true: "{{ item.value.hold_true|default(omit) }}"
with_dict: "{{ service_List }}"
In addition to this, you can use Module defaults.
I'm having hard time trying to figure it out what I'm doing wrong with my Ansible playbook.
I've got a bunch of tasks, which define or not some variables according to context, depending of the result, some task will be ignored or not.
For this specific case, I check if a VlanID already exists, if it doesn't then I create one, and retrieve the new VlanID from the result.
Here is the playbook :
---
#Tasks for portGroup_add
- name: Get all portgroups in dvswitch vDS
community.vmware.vmware_dvs_portgroup_find:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
dvswitch: "{{ vcenter_dvSwitch }}"
validate_certs: False
register: portGroup_infos
when: (OLD_VLANID is not defined) or (OLD_VLANID|length < 1)
#Get last VLAN ID for HDS client, and set VLANID + 1
- name: get portGroup_infos
set_fact:
VLANID: "{{ item.vlan_id }}"
with_items: "{{ portGroup_infos.dvs_portgroups}}"
when:
- (portGroup_infos is defined) and (portGroup_infos|length > 0)
- item.name | regex_search("\(HDS :\s*")
While everything is working pretty well for most of the tasks, this one fires the following error :
The conditional check 'item.name | regex_search("\(HDS :\s*")' failed.
The error was: error while evaluating conditional (item.name | regex_search("\(HDS :\s*")): 'item' is undefined
Which is pretty obvious, because the dict portGroup_infos, is not defined.
In order to get the new VlanID, I'm using a "when" conditionnal , which check if in the item, the value "(HDS :" , is present.
But I don't want the task to launch if the portGroup_infos variable defined above is not set, I though I'd should use nested "when", but can't succeed.
Ansible version : 2.10.7
python version : 3.7.3
Thank you for your help.
Put both tasks into a block, e.g.
- block:
- name: Get all portgroups in dvswitch vDS
...
- name: get portGroup_infos
...
when: OLD_VLANID|default('')|length == 0
I would like to install Apache on several linux server. Apache package has not the same name on RedHat or Debian operating system (apache2 vs httpd): Is it a way to use an ansible fact variable ("ansible_os_family") as a key of a dictionary variable ?
Something like that (but this doesn't work) :
---
- name: playbook1
hosts: all
become: yes
vars:
apache_packages: {
"RedHat": "httpd",
"Debian": "apache2"
}
tasks:
- name: Install Apache server
package:
name: "{{ apache_packages['{{ ansible_os_family }}'] }}"
state: present
...
Nesting Jinja delimiters inside another Jinja delimiter is never a good idea.
Another rule is ‘moustaches don’t stack’. We often see this:
{{ somevar_{{other_var}} }}
The above DOES NOT WORK as you expect, if
you need to use a dynamic variable use the following as appropriate:
{{ hostvars[inventory_hostname]['somevar_' + other_var] }}
For ‘non host vars’ you can use the vars lookup plugin:
{{ lookup('vars', 'somevar_' + other_var) }}
Source: https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#when-should-i-use-also-how-to-interpolate-variables-or-dynamic-variable-names
If you don't surround something with quotes, it will be assumed as being a variable, so in this case, this is as simple as:
name: "{{ apache_packages[ansible_os_family] }}"
try this: you define packages as a dict of list (based on os family)
- name: playbook1
hosts: localhost
become: yes
vars:
packages:
debian:
- apache2
redhat:
- httpd
tasks:
- name: Install Apache server
package:
name: "{{ item }}"
state: present
loop: "{{ packages.get(ansible_os_family|lower) }}"
I would do some thing like below to reduce the lines
- hosts: localhost
become: yes
tasks:
- package:
name: "{{ 'apache2' if ansible_os_family == 'Debian' else ('httpd' if ansible_os_family == 'RedHat') }}"
state: present
I have a playbook (CIS compliance standard) with multiple tasks and I want to produce a "success" or "failed" depending on the ansible return code.
---
- name: 2.2.# Ensure ### Server is not enabled
block:
- name: Check if ### exists
stat: path=/usr/lib/systemd/system/###.service
register: exists
- name: Disable if exists
service:
name: ###
state: stopped
enabled: no
when: exists.stat.exists
register: result
- name: To File
block:
- name: Success
lineinfile:
dest: ./results/{{ customer }}-{{ scan_type }}-{{ inventory_hostname }}.txt
line: "{{ inventory_hostname }} 2.2.9 success"
insertafter: EOF
delegate_to: localhost
check_mode: False
when: ((result is skipped) or (result.enabled == false))
- name: Failed
lineinfile:
dest: ./results/{{ customer }}-{{ scan_type }}-{{ inventory_hostname }}.txt
line: "{{ inventory_hostname }} 2.2.9 failed"
insertafter: EOF
delegate_to: localhost
check_mode: False
when: ((result is not skipped) or (result.enabled == true))
From my observation, 'result' can have two different outputs depending on if the "Disable if exists" block is triggered.
If it is triggered, it'll give an output based on the "service" module.
If it is skipped, it'll give the generic Ansible output.
I'm fine with that, but what I can't seem to work out is the conditional statement.
when: ((result is not skipped) or (result.enabled == true))
This will always try to resolve both options, so if the module triggers, it will fail because "skipped" is not an attribute of the service module. If it skips, it'll pass, but obviously fail if it ever gets triggered. It's like it wants all conditions to exist before evaluating despite the "or" statement.
What am I doing wrong?
Do you mean result is skipped rather than result is not skipped? In any case, you can solve this using the default filter, which provides a default value if the input expression is undefined. For example:
when: result.enabled|default(false) == true
Of course, since that's a boolean, you can further simplify it to:
when: result.enabled|default(false)
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 }}"