zcoder
zcoder

Reputation: 72

how to filter/trim a particular variable value in ansible

I have a requirement where I have to extract/filter particular length of a string in ansible. For example:-

My node machine has following hostname:- jpujenkins, jpunessus.

So in fact variable we will have.

{{ ansible_hostname }} --> jpujenkins.

{{ ansible_hostname }} --> jpunessus

But I want to remove first three letter say 'jpu' from the all node hostname.

Desired output :- jenkins, nessus

Also can be capitalize the letter say JENKINS, NESSUS?

Upvotes: 2

Views: 16883

Answers (1)

vkozyrev
vkozyrev

Reputation: 1988

You could use regex_replace Ansible filter to fulfill your need. https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#regular-expression-filters

For example, my hostname is ip-192-168-1-65.

---
- hosts: all
  tasks:
    - debug: msg="{{ ansible_hostname | regex_replace('^ip-', '') }}"

When I execute the playbook it returns the hostname where '^ip-' part is replaced with an empty string ''.

TASK [debug] *********************************************************************************************************************************************************************
Tuesday 28 April 2020  11:18:24 +0300 (0:00:07.281)       0:00:07.498 *********
ok: [localhost] =>
  msg: 192-168-1-65

Upvotes: 2

Related Questions