How to filter ipaddress and hostname and store it to different variable

I have a variable that contains short hostname, FQDN and IP addresses.
I need to filter sort hostname/FQDNs and it should store to a variable and also IP addresses should store to an another variable(this am able to do using ipaddr)
Please help me to filter hostnames and store to a variable.

system: >
1.1.1.1
myhost.example.com
myhost

You should be able to use a regular expression to filter hostnames

Ok Thanks.

I tried below tasks but it’s giving error on regex task.
Can you help me to get the pattern to filter only the item starts with the alphabet.

  • set_fact:
    ip_list: “{{ ip_addr.split(\n) | ipaddr }}”
  • debug: var=ip_list
  • set_fact:
    host_list: “{{ ip_addr.split(\n) | regex_search(‘[1].*’) }}”
  • debug: var=host_list

  1. a-z ↩︎

What is the error, and what does the 'ip_addr' variable look like?

My variable looks below.

ip_addr: |
  1.12.6.9
  myhost
  Myhost.example.com

And the error is…?

The error is

TASK [set_fact] *****************************************************************************************************
fatal: [lab1]: FAILED! => {“msg”: “Unexpected templating type error occurred on ({{ ip_addr.split(\n) | regex_search(‘[1].*’) }}): expected string or buffer”}
to retry, use: --limit @/playbooks/var_check.retry


  1. a-z ↩︎

You didn't quote the newline.
But, you don't really need that as the default is to split by white space.

For the literal IPv4 address it's indeed easy, as you can just use the
ipaddr filter.
For the hostname you can use the select() test, in combination with
some regular expression that needs to match.
Depending on how formal/exact you want to define "a hostname", the
regex can simple or really complex.
A simple example:

  tasks:
    - set_fact:
        ip_list: "{{ ip_addr.split() | ipaddr }}"
    - debug: var=ip_list
    - set_fact:
        host_list: "{{ ip_addr.split() | select('match',
'^([a-zA-Z]+(-[a-zA-Z]+)*\\.)+[a-zA-Z]{2,}$') | list }}"
    - debug: var=host_list

This should give you some results.

Dick

Below regex is working perfectly for my requirement. Thanks a lot, Dick for your help.

  • set_fact:
    ip_list: “{{ ip_addr.split() | ipaddr }}”

  • debug: var=ip_list

  • set_fact:
    host_list: “{{ ip_addr.split() | select(‘match’,‘^([a-zA-Z].*)’) | list }}”

  • debug: var=host_list