Extract and split string in ansible

Viewed 652

I have a machine where the variable contains the a number that I want to extract and then split to build an IP address using ansible.

variable = machine240dev

I want to be able to extract 240 then split it to fill in the two middle octets of an ip address

e.g. 10.2.40.170

I have tried various ways such as:

var: machine240dev

10.{{  var | regex_replace('[^0-9]','')[0] }}.{{ var | regex_replace('[^0-9]','')[-2:] }}.170

which fails as it doesn't like the [0] after the regex_replace filter.

I was just wondering if anyone has done this before or know a clean way to do it.

EDIT:

I have set a fact to first set the variable for the vlan before extracting the specific parts of the string.

- name: Setting vlan fact
  set_fact: vlan="{{  var | regex_replace('[^0-9]','') }}"

Then in my template i set:

IPADDR=10.{{ vlan[0] }}.{{ vlan[-2:] }}.170

However I am still open to suggestions on how this could be improved

2 Answers

Ansible allows you to create intermediate variables with the scope of the task, e.g.

    - set_fact:
        IPADDR: "10.{{ vlan[0] }}.{{ vlan[-2:] }}.170"
      vars:
        vlan: "{{ var | regex_replace('[^0-9]','') }}"

You can use a regex_replace solution like:

10.{{  var | regex_replace('.*([0-9])([0-9]{2}).*', '\\1.\\2') }}.170

Here,

  • .* - matches any zero or more chars other than line break chars, as many as possible
  • ([0-9])([0-9]{2}) - Captures a digit into Group 1 and then two digits into Group 2
  • .* - matches any zero or more chars other than line break chars, as many as possible

The \1.\2 replacement replaces the matched string with Group 1 + . + Group 2 values.

See this regex demo.

Or, a regex_search based solution:

10.{{  var | regex_search('[0-9]') }}.{{ var | regex_search('(?<=[0-9])[0-9]{2}') }}.170

Output:

10.2.40.170

Here,

  • regex_search('[0-9]') extracts the first digit
  • regex_search('(?<=[0-9])[0-9]{2}') - extracts two digits after a digit.
Related