Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split value in Ansible with delimiter

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
like image 371
sherri Avatar asked Nov 29 '22 21:11

sherri


2 Answers

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('-') }}"
like image 83
Vladimir Botka Avatar answered Dec 04 '22 01:12

Vladimir Botka


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.

like image 26
Oliver Gaida Avatar answered Dec 04 '22 01:12

Oliver Gaida