Question:
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
1 2 3 4 5 6 |
- set_fact: config: "{{ asg.results|json_query('[*].launch_configuration_name') }}" - debug: var: config |
Answer:
another option is ansibles regular expression filter, you find here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#regular-expression-filters
1 2 3 4 5 6 |
vars: var: dos-e1-south-209334567829102380 tasks: - debug: msg: '{{ var | regex_replace("^(.*)-[^-]+$", "\\1") }}' |
has the same result:
1 2 |
"msg": "dos-e1-south" |
Explanation for the regex:
1 2 |
^(.*) |
keep everything from the start of the string in the first backreference
1 2 |
-[^-]+$ |
find the last “-” followed by non-“-” characters till the end of string.
1 2 |
\\1 |
replaces the string with the first backreference.