how to split value in Ansible with delimiter
38,959
Solution 1
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"
Explanation for the regex:
^(.*)
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.
Solution 2
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('-') }}"
Author by
sherri
Updated on July 07, 2020Comments
-
sherri almost 4 years
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
-
sherri about 5 yearsThank you so much for the detailed explanation.