Hi Team
I am writing a playbook to automate assigning an IP address to a set of hosts, however, I am stuck at pulling IP details from vars_files. below is the code, any pointers will be much helpful to me. thank you.
vars_files:
[root@dljdaprdqmc1v commvault]# cat host_ip.yml
dlabcpdtmdb1v: 172.20.0.63
[root@dljdaprdqmc1v commvault]#
[root@dljdaprdqmc1v commvault]# cat check_ip.yml
vars_files:
[root@dljdaprdqmc1v commvault]# cat host_ip.yml
dlabcpdtmdb1v: 172.20.0.63
[root@dljdaprdqmc1v commvault]#
[root@dljdaprdqmc1v commvault]# cat check_ip.yml
---
- hosts: all
remote_user: root
vars_files:
- host_ip.yml
tasks:
- shell: ip a s | grep DOWN | /bin/awk -F":" '{$2=$2;print}' | /bin/awk
'{print $2}'
register: nic
ignore_errors: yes
- stat: path=/etc/sysconfig/network-scripts/ifcfg-{{nic.stdout}}
register: nicfile
ignore_errors: yes
- lineinfile: path=/tmp/ifcfg-{{nic.stdout}} line={{item}} create=yes
with_items:
- TYPE=Ethernet
- BOOTPROTO=static
- DEFROUTE=yes
- PEERDNS=yes
- PEERROUTES=yes
- IPV4_FAILURE_FATAL=no
- IPV6INIT=no
- IPV6_AUTOCONF=no
- IPV6_DEFROUTE=no
- IPV6_PEERDNS=no
- IPV6_PEERROUTES=no
- IPV6_FAILURE_FATAL=no
- NAME={{nic.stdout}}
- DEVICE={{nic.stdout}}
- ONBOOT=yes
- IPADDR="{{ansible_hostname}}" <== here i need to get value from host_ip.yml which allocate that host
<snip />
changed: [dlabcpdtmdb1v] => (item=IPADDR=dlabcpdtmdb1v)
ok: [dlabcpdtmdb1v] => (item=NETMASK=255.255.252.0)
as you see IP becomes the hostname, since you need the content of the variable with the same name as the host you need to use vars/hostvars/lookup vars.
So {{ vars[ansible_hostname] }} would give you that, but vars is not a documented feature that is schedule for removal.
So you are left with more unreadable code like
{{ hostvars[inventory_hostname][ansible_hostname] }}
or
{{ lookup('vars', ansible_hostname }}
Thanks a lot Kai Stian, it worked well.