I am setting a fact in Ansible and that variable has a value with hyphens, like this "dos-e1-south-209334567829102380". i want to split , so i only get "dos-e1-south"
Here is the play
- set_fact:
config: "{{ asg.results|json_query('[*].launch_configuration_name') }}"
- debug:
var: config
An option would be to use split()
. The tasks below
vars:
var1: dos-e1-south-209334567829102380
tasks:
- set_fact:
var2: "{{ var1.split('-') }}"
- debug:
msg: "{{ var2.0 }}-{{ var2.1 }}-{{ var2.2 }}"
give
"msg": "dos-e1-south"
To concatenate the items, it's also possible to use join()
. The task below gives the same result
- debug:
msg: "{{ var2[0:3] | join('-') }}"
another option is ansibles regular expression filter, you find here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#regular-expression-filters
vars:
var: dos-e1-south-209334567829102380
tasks:
- debug:
msg: '{{ var | regex_replace("^(.*)-[^-]+$", "\\1") }}'
has the same result:
"msg": "dos-e1-south"
^(.*)
keep everything from the start of the string in the first backreference
-[^-]+$
find the last "-" followed by non-"-" characters till the end of string.
\\1
replaces the string with the first backreference.
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