[Root@idc-server2 ~]# Ifconfig Eth0 Link encap:ethernet hwaddr 1b:2b:3b:4b:5b:6b inet addr:172.16.1.2 bcast:172.16.1.255 mask:255.255.252.0 ... eth1 Link encap:ethernet hwaddr 1a:2a:3a:4a:5a:6a inet addr:100.100.100.100 bcast:100.100.100.255 mask:255.255.255.240 ... Lo Link encap:local Loopback inet addr:127.0.0.1 mask:255.0.0.0 ... [Root@idc-server1 ansible]# Vim Myfacts.yml --- -Hosts:idc-server2 Roles -Myfacts [Root@idc-server1 ansible]# mkdir-p Roles/myfacts/{tasks,templates} [Root@idc-server1 ansible]# Vim Roles/myfacts/tasks/main.yml --- -Name:run myfacts module to get customized facts Myfacts:get_facts=yes -Name:update file with the customized facts Template:src=myfacts.txt.j2 Dest=/tmp/myfacts.txt [Root@idc-server1 ansible]# Vim Roles/myfacts/templates/myfacts.txt.j2 Ansible_private_ipv4_address: {{ansible_private_ipv4_address}} [Root@idc-server1 ansible]# Mkdir/usr/share/ansible/heylinux [Root@idc-server1 ansible]# Vim/usr/share/ansible/heylinux/myfacts #!/usr/bin/python Import Sys Import JSON Import Shlex Import commands Import re Def get_ansible_private_ipv4_address (): Iprex = "(^192.168) | (^10.) | (^172.1[6-9]) | (^172.2[0-9]) | (^172.3[0-1]) " Output = Commands.getoutput ("" "/sbin/ifconfig |grep" Link encap "|awk ' {print} ' |grep-wv ' lo '" ") NICs = Output.split (' n ') T_nic_info = "" For I in NICs: IPAddr = Commands.getoutput (""/sbin/ifconfig%s |grep-w "inet addr" |cut-d:-f2 | awk ' {print '} ' "'% (i) If Re.match (IPREX,IPADDR): Ansible_private_ipv4_address = ipaddr Return ansible_private_ipv4_address Args_file = sys.argv[1] Args_data = File (args_file). Read () arguments = Shlex.split (args_data) For ARG in arguments: If "=" in arg: (key, value) = Arg.split ("=") If key = = "Get_facts" and value = "Yes": Ansible_private_ipv4_address = Get_ansible_private_ipv4_address ()
Print Json.dumps ({ "Changed": False, "Ansible_facts": { "Ansible_private_ipv4_address": ansible_private_ipv4_address } }) Sys.exit (0) Print Json.dumps ({ "Changed": False }) [Root@idc-server1 ansible]# ansible-playbook-u Root myfacts.yml-i hosts Play [Idc1-server2] *************************************************************** Gathering FACTS *************************************************************** OK: [Idc1-server2] TASK: [myfacts | run myfacts module to get customized facts] ************** OK: [Idc1-server2] TASK: [myfacts | update file with the customized facts] ********************* Changed: [Idc1-server2] Play Recap ******************************************************************** Idc1-server2:ok=3 changed=1 unreachable=0 failed=0 [Root@idc-server1 ansible]# ssh idc1-server2 ' cat/tmp/myfacts.txt ' ansible_private_ipv4_address:172.16.1.2 |