I have written a task as below but can not understand what '|' does?
tasks:
- shell: /usr/bin/foo
register: result
ignore_errors: True
- debug: msg="it failed"
when: result|failed
- debug: msg="it changed"
when: result|changed
Also I have found some examples on web but can not understand what '|' does?
debug: msg={{ ipaddr |replace(",", ".") }}
One more example:
- hosts: localhost
vars:
D:
1 : "one"
2 : "two"
tasks:
- debug: var=D
- debug: msg="D[1] is {{ D[1]|default ('undefined') }}"
Would be great if someone can explain in details or point me to some URL?
Any help would be appreciated.
Thanks.
With the pipe character you pass a value to a filter. There are numerous Jinja 2 filters but Ansible brings some additional filters.
The term filter might be confusing at times because all the filters work very differently. Some for example reduce a result set of a hash/array, some modify contents of a string, but then there are filters which simply return true or false.
A better explanation might be that those are modifiers and they can do anything with your passed data. You can even write your own filters.
Filters can be chained, passing the result from the first filter to the next and so forth. It works exactly like piping commands on a unix shell.
"value" | filter1 | filter2 | filterN
The failed
filter returns true
if the passed result has failed. It simply checks the failed
property from result
.
The changed
filter is the same, but checks if the passed result has changes. It checks the changed
property from result
.
ipaddr | replace(",", ".")
replaces all occurrences of ,
with .
. So a value of 127,0,0,1
will be transformed to 127.0.0.1
.
The default
filter will set a default value if the input was null, e.g. an undefined variable. undefined_var | default("var was undefined")
-> This will either print the contents of undefined_var
or the string "var was undefined". In your given example above you output the value of the 2nd element of D
(D[1]
) and if it does not exist the sting "undefined" instead.