Home > Net >  ansible crop a substring with jinja2
ansible crop a substring with jinja2

Time:09-25

I want to crop a sting in ansible, preferably with the replace command. "db-FFREG.domain.inet" should be changed to "db-FFREG". I already found a solution with split, that is working. But I want to do this with regex

The solution working, but its not so elegant:

---
- hosts: localhost
  gather_facts: no
  vars:
    hostname: db-FFREG.domain.inet

  tasks:
    - name: Change hostname into ORACLE SID
      set_fact:
        myOracleSid: "{{hostname.split('.') }}"

    - debug:
        msg:
          -  "ORACLE_SID: {{ myOracleSid[0] }}"

The solution which I´d prefer is with jinja2 - no error message, but doesn´t crop anything:

---
- hosts: localhost
  gather_facts: no
  vars:
    hostname: db-FFREG.domain.inet

  tasks:
    - name: Change hostname into ORACLE SID
      set_fact:
        myOracleSid: "{{hostname  |  replace('^(. ).domain.inet$','') }}"

    - debug:
        msg:
          -  "ORACLE_SID: {{ myOracleSid }}"

CodePudding user response:

If you wanted to remove .domain.inet from the end of the string, you need to use a regex:

{{ hostname | regex_replace('\.domain\.inet$', '') }}

Note the regex_replace function is used, the dots are escaped to match literal dots and the $ is used to match the end of string.

To remove all after the first dot, use

{{ hostname | regex_replace('\..*', '') }}

where \. matches a literal . and .* matches any zero or more chars other than line break chars as many as possible.

CodePudding user response:

well, this one worked! It is easier, than I thought!

---
- hosts: localhost
  gather_facts: no
  vars:
    hostname: db-FFREG.domain.inet

  tasks:
    - name: Change hostname into ORACLE SID
      set_fact:
        myOracleSid: "{{hostname  |  replace('.domain.inet','') }}"

    - debug:
        msg:
          -  "ORACLE_SID: {{ myOracleSid }}"
  • Related