Heres my if else Ansible logic ..
- name: Check certs exist
stat: path=/etc/letsencrypt/live/{{ rootDomain }}/fullchain.pem
register: st
- include: ./_common/check-certs-renewable.yaml
when: st.stat.exists
- include: ./_common/create-certs.yaml
when: not st.stat.exists
This code boils down to:
IF certs exist
renew certs
ELSE
create certs
END IF
Is this the correct approach or is there a better approach to the IF ELSE construct in ansible?
What you have there should work and is one way of doing it.
Alternatively, you could use a Jinja query to reduce it to 2 tasks, such that:
- name: Check certs exist
stat: path=/etc/letsencrypt/live/{{ rootDomain }}/fullchain.pem
register: st
- include: "{{ './_common/check-certs-renewable.yaml' if st.stat.exists else './_common/create-certs.yaml' }}"
However, it's more a matter of personal preference than anything else, and your way is more readable, so I would just stick with that IMHO.
What about the following
condition_arg: >-
{%- if ansible_distribution == 'Ubuntu' -%}
'param for ubuntu'
{%- elif ansible_distribution == "Debian" -%}
'params for debian'
{%- else -%}
'what else'
{%- end %-}
kind of if-else statement.. ? They have been used in some projects with ansible.
This form isn't available from the official docs, but from an active thread on stackexchange
The following can be used if you want to search if a register is empty. The msg Unavailable is printed if php -version info is not found.If it is found, it prints the output of the command.
- name: Check php
shell: php -version
register: result
- name: Print register
debug:
msg: '{{ (result.stdout) | ternary( (result.stdout),"Unavailable") }}'
Related
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' }}"
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 have written jinja2 template in ansible. What i am trying to achieve is that if the service_name is not mentioned and if service_name already exists on the remote machine, ansible should not change the service_name with default name mentioned in the template. However, when the service_name is not defined, ansible replaces service name with "abc" on remote machine even service_name exists. Any help would be appreciated.
active={{ active_status}}
instrument={{ instrument_status }}
{% if service_name is defined %}
service_name={{ service_name }}
{% else %}
service_name=abc
{% endif %}
Thanks
Following my above comment, here is a possible example implementation to meet your requirements. test_template.j2 is the exact copy of your current template. You can pass the service name as an extra variable to test (-e service_name=my_service)
Basically, if service_name is not defined, we:
Check if the remote file already exists and slurp its content into a var
Look for the relevant line in the file. Note: the regex_replace('None', '') is here to make sure we get an empty string if previous search/matches did not return anything.
Set the service name only if something relevant was found in the prior tasks
Once this check/setting is done correctly, you simply have to copy your template, what ever the case is.
---
- name: Conditional writing of template
hosts: localhost
gather_facts: false
vars:
my_dest: /tmp/test_file.txt
active_status: some active value
instrument_status: some instrument value
tasks:
- name: Try to read service name from existing file when it is not defined
when: service_name is not defined
block:
- name: Check if file exists
stat:
path: "{{ my_dest }}"
register: my_file
- name: Try to read target file if exists
slurp:
src: "{{ my_dest }}"
when: my_file.stat.exists
register: my_file_slurp
- name: Look for service name if there
set_fact:
looked_service: >-
{{
my_file_slurp.content
| b64decode
| regex_search('^service_name=.*$', multiline=true)
| regex_replace('^service_name=(.*)$', '\1')
| regex_replace('None', '')
}}
when: my_file.stat.exists
- name: Update service name if found
set_fact:
service_name: "{{ looked_service }}"
when: looked_service | default('') | length > 0
- name: Copy template file to destination
template:
src: test_template.j2
dest: "{{ my_dest }}"
We need to go through this structure
Zone spec
https://gist.github.com/git001/9230f041aaa34d22ec82eb17d444550c
I was able to run the following snipplet but now I'm stucked at the error checking.
playbook
--
- hosts: all
gather_facts: no
vars_files:
- "../doc/application-zone-spec.yml"
roles:
- { role: ingress_add, customers: "{{ application_zone_spec }}" }
role
- name: check if router exists
shell: "oc get dc -n default {{ customers.zone_name }}-{{ item.type }}"
with_items: "{{ customers.ingress }}"
ignore_errors: True
register: check_router
- name: Print ingress hostnames
debug: var=check_router
- name: create new router
shell: "echo 'I will create a router'"
with_items: "{{ customers.ingress }}"
when: check_router.rc == 1
Output of a ansible run
https://gist.github.com/git001/dab97d7d12a53edfcf2a69647ad543b7
The problem is that I need to go through the ingress items and I need to map the error of the differnt types from the "check_router" register.
It would be nice to make something like.
Pseudo code.
Iterate through the "customers.ingress"
check in "check_router" if the rc is ! 0
execute command.
We use.
ansible-playbook --version
ansible-playbook 2.1.0.0
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
You can replace the second loop with:
- name: create new router
shell: "echo 'I will create a router with type {{ item.item }}'"
with_items: "{{ check_router.results }}"
when: item.rc == 1
This will iterate over every step of check_route loop and you can access original items via item.item.
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 }}"