Alucard Hellsing
Alucard Hellsing

Reputation: 13

Get Number from hostname in Ansible

In Puppet I can extract the number of the Hostname with this example:

$host_number = regsubst($hostname, '^\w+(\d\d)', '\1')

Is there something similar in Ansible?

e.g.:
fqdn: test01.whatever
hostname: test01
output -> newvariable: 01

I want to extract only the number out of the Hostname, so I can use it in my Playbook as a variable.

Upvotes: 1

Views: 3685

Answers (3)

burncycl
burncycl

Reputation: 31

This will fetch the inventory_hostname and replace any character text with nothing, leaving the numeric text. Obviously, you can use your imagination to apply whatever regex needed.

Ansible playbook:

vars:
  host_names:
    - {{ inventory_hostname | regex_replace('[^0-9]','') }}

Jinja2 Template:

{% for host in groups['some_group_in_inventory'] %}
Some description of the host where I needed the Number {{ host | regex_replace('[^0-9]','') }}
{% endfor %}

Upvotes: 2

muzafarow
muzafarow

Reputation: 936

If you need to extract only "test01" from hostname, then you can use ansible build in filter "regex_replace". Here is my example:

{{ ansible_hostname | regex_replace('^([a-zA-Z_]+)(\d+)$','\\2') | int }}

Then you get: 1 If you need "01", then delete part to pass to integer - "int"

Upvotes: 0

Kelson Silva
Kelson Silva

Reputation: 532

Theres multiple ways of doing the same thing...

You can use ansible_facts, ansible_hostname, shell commands, etc...

---
- hosts: localhost
  gather_facts: yes
  tasks:
    - debug: var=ansible_facts.hostname
    - debug: var=ansible_hostname

As raVan96 said, you need to explain better what you need and what you expect...

Upvotes: 0

Related Questions