Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract last two number of IP in ansible

Tags:

python

ansible

I need some help coming up with a very simple way of extracting the last two numbers from an IP address in ansible. My playbook currently looks like this

---
- hosts: localhost
  tasks:
   - name: install dns resolver
     yum: name=python-dns

   - debug: msg={{ lookup('dig','google.com.') }}

Running this playbook yields the following

TASK [install dns resolver] ****************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "172.217.7.142"

Is there a way in ansible to just return the last two numbers of that IP? i.e.42

I actually have to embed this in a template which ultimately would have a format like so:

last_two_numbers_of_IP={{ lookup('dig','google.com.') }}

Output in template should look like so:

 last_two_numbers_of_IP=42
like image 306
crusadecoder Avatar asked Mar 10 '23 14:03

crusadecoder


1 Answers

Get the last octet and then last two chars of last octet. If the last octet has only one number, it will return just that number.

  vars:
    ip: 192.168.1.123

  tasks:
   - name: install dns resolver
     debug: msg={{ ip.split('.')[-1][-2:] }}

Output

TASK [install dns resolver] ****************************************************
ok: [localhost] => {
    "msg": "23"
}
like image 139
helloV Avatar answered Mar 20 '23 22:03

helloV