In Ansible, I am trying to use regex_replace to update some numeric parameters (example is to add 3 all version numbers: "version=3" should become "version=6", "version=2" should become "version=5", ...)

In Python, I can pass a lambda function to re.sub like this:

re.sub("version=(\d+)", lambda m: "version=" + str(int(m.group(1))+3), "version=3 blah blah blah whatever version=4")

Which gives this as desired:

'version=6 blah blah blah whatever version=7'

Can't seem to convince Ansible with the right syntax.
I tried this:

{{ stringvariable | regex_replace('version=(\\d+)', lambda m: 'version=' + str(int(m.group(1)) + 3) }}

1 Answers

0
Matthew L Daniel On

In Ansible, I am trying to use regex_replace to update some numeric parameters (example is to add 3 all version numbers: "version=3" should become "version=6", "version=2" should become "version=5", ...)

There's nothing magic that needs to take place if you just have one string version=2 and you want to emit version=5:

- debug:
    msg: >-
      version={{ (stringvar | regex_replace("^version=", "") | int) + 3 }}
  vars:
    stringvar: version=2

The tricky bit would be when you have multiple of them:

- debug:
    msg: >-
      {% for it in (stringvars | map("regex_replace", "^version=", "") | map("int")) %}
      version={{ it + 3 }}
      {% endfor %}
  vars:
    stringvars:
    - version=2
    - version=5
    - version=7