How to get backup ip and assign to a variable

Hi,

How to search for a IPv4 starting with “192.168.x.x” from ansible_all_ipv4_addresses and assign to variable. If not, assign default ipv4.

The use case is, I need to get backup ip and assign to a variable. I need to use this variable in some configuration file.

[root@xxxx agents_deploy]# cat get_backupip.yml

Hi,

How to search for a IPv4 starting with "192.168.x.x" from ansible_all_ipv4_addresses and assign to variable. If not,
assign default ipv4.

The use case is, I need to get backup ip and assign to a variable. I need to use this variable in some configuration file.

[root@xxxx agents_deploy]# cat get_backupip.yml
---
- hosts: "{{ hosts_prompt }}"
become: yes
gather_facts: no

vars_files:
- /var/lib/ansible_playbooks/inventory/password.yml

vars_prompt:
- name: "hosts_prompt"
prompt: "hostname or host group need to run with Playbook"
private: no
default: dev

pre_tasks:
- setup:
filter: ansible_*

tasks:
- name: backup ip
debug:
msg: "{{ ansible_all_ipv4_addresses }}"

- name: search backup ip which starts with '192.168',assign to some other variable. If not, assign primary ip
set_fact:
backupip: "{% for ip in {{ ansible_all_ipv4_addresses }} %}
{% if ip | regex_search('192.168.*.*') %}
{{ ip }}
{% else % }
{{ ip[0] }}
{% endif %}
{% endfor %}"

This should be do the trick:

"{{ ansible_all_ipv4_addresses | select('search', '192.168.*.*') | first | default(ansible_all_ipv4_addresses[0]) }}"

However, the regular expression is not accurate as means ".*" match ANY character.

Your original error code is caused by using {{ ... }} inside of the {% for ... %}.

Regards
        Racke

Hi Racket/All,

Ok, thanks for letting me know the other way of the trick. I’ll verify what you suggested and update in the group.

I wanted to know is there any syntax or logic issues in my original post. Any valuable inputs are appreciated.

  • set_fact:
    backupip: “{% for ip in {{ ansible_all_ipv4_addresses }} %}
    {% if ip | regex_search(‘192.168..’) %}
    {{ ip }}
    {% else % }
    {{ ip[0] }}
    {% endif %}
    {% endfor %}”