Here is my playbook
---
- name: This is a hello-world example
hosts: localhost
vars:
mystr: "I.To.Be.war"
tasks:
- name: Hi
debug:
msg: "{{ mystr.split('.') | first | trim }}"
Output:
I
The trim filter is to get rid of \r\n at the end of the variable incase it has.
However, I wish a generic solution that should print everything before the last element of the split delimiter, i.e.: ..
Expected output:
I.To.Be
Note: I do not want a solutions like "{{ mystr.split('.')[0][1][2] }}" as it is not generic in nature.
trim filter to every element of your list using the map filter$ ansible localhost -m debug \
-a "msg={{ (mystr.split('.') | map('trim'))[:-1] | join('.') }}" \
-e "mystr=I.to.be.war"
localhost | SUCCESS => {
"msg": "I.to.be"
}
Alternatively, you can use a regex to match the first part of the string
$ ansible localhost -m debug \
-a 'msg={{ mystr | regex_replace("^(.*)\\.[^.]*$", "\\1") }}' \
-e "mystr=I.to.be.war"
localhost | SUCCESS => {
"msg": "I.to.be"
}
Since your requirement seems to be about getting the name of a file without its extension, mind that there is a extra Jinja filter, splitext, purposed for that:
Where, the task
- debug:
var: "'I.To.Be.war' | splitext | first | trim"
will give your expected
ok: [localhost] =>
'''I.To.Be.war'' | splitext | first | trim': I.To.Be
While the filter splitext is actually returning a tuple, more convenient than a regular split:
ok: [localhost] =>
'''I.To.Be.war'' | splitext | trim': ('I.To.Be', '.war')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With