I retrieved a version string into 'myvar' like 00001.00022.00333 which I would like to move into my dict as 1.22.333
The regex is pretty simple, but I am unable to reassemble the capture groups. Can someone explain how to fix this?
set_fact:
cacheable: yes
mydict: "{{ mydict | combine({ 'version': myvar | regex_search('0*(\\d+)\\.0*(\\d+)\\.0*(\\d+)', '\\1.\\2.\\3') }) }}"
The output of the code above is [ "1" ] (an array) instead of "1.22.333".
Use regex_replace. No need to escape backslash if you put it into single quotes. For example,
mydict: "{{ {'version': myvar|regex_replace(md_regex, md_replace)} }}"
md_regex: '0*(\d+)\.0*(\d+)\.0*(\d+)'
md_replace: '\1.\2.\3'
gives
mydict:
version: 1.22.333
The same result can be achieved without regex. For example,
mydict: "{{ {'version': myvar.split('.')|map('int')|join('.')} }}"
Example of a complete playbook for testing
- hosts: all
vars:
myvar: 00001.00022.00333
mydict: "{{ {'version': myvar|regex_replace(md_regex, md_replace)} }}"
md_regex: '0*(\d+)\.0*(\d+)\.0*(\d+)'
md_replace: '\1.\2.\3'
mydict2: "{{ {'version': myvar.split('.')|map('int')|join('.')} }}"
tasks:
- debug:
var: mydict
- debug:
var: mydict2
Q: "Show a working example for this all in a task, including vars in the task."
A: Simply put the variables into the vars at the task's level
- debug:
msg: "{{ {'version': myvar|regex_replace(md_regex, md_replace)} }}"
vars:
myvar: 00007.00088.00999
md_regex: '0*(\d+)\.0*(\d+)\.0*(\d+)'
md_replace: '\1.\2.\3'
gives
msg:
version: 7.88.999
See:
Understanding variable precedence
7.3.2. Single-Quoted Style
7.3.1. Double-Quoted Style
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