下面来看一个编写Ansible模块并自定义Facts例子,希望例子能帮助到各位.
背景介绍:Ansible自带的Facts有很多,但很多时候并不够用,比如,Ansible就没有ansible_private_ipv4_address这样一个Facts,用来保存私网IP地址.
而我们恰恰就需要这样的一个Facts,因为我们有很多服务器的默认网卡并非是eth0,有的是bond0,eth1,em0,em1等,而公网IP地址与私网IP地址也并没有固定的绑定在某个网卡上,很多时候还是虚拟网卡.
还好,我们可以通过编写Ansible模块并自定义Facts来实现,具体步骤,代码如下:
- [root@idc-server2~]#ifconfig
- eth0Linkencap:EthernetHWaddr1B:2B:3B:4B:5B:6B
- inetaddr:172.16.1.2Bcast:172.16.1.255Mask:255.255.252.0
- ...
- eth1Linkencap:EthernetHWaddr1A:2A:3A:4A:5A:6A
- inetaddr:100.100.100.100Bcast:100.100.100.255Mask:255.255.255.240
- ...
- loLinkencap:LocalLoopback
- inetaddr:127.0.0.1Mask:255.0.0.0
- ...
- [root@idc-server1ansible]#vimmyfacts.yml
- ---
- -hosts:idc-server2
- roles:
- -myfacts
- [root@idc-server1ansible]#mkdir-proles/myfacts/{tasks,templates}
- [root@idc-server1ansible]#vimroles/myfacts/tasks/main.yml
- ---
- -name:runmyfactsmoduletogetcustomizedfacts
- myfacts:get_facts=yes
- -name:updatefilewiththecustomizedfacts
- template:src=myfacts.txt.j2dest=/tmp/myfacts.txt
- [root@idc-server1ansible]#vimroles/myfacts/templates/myfacts.txt.j2
- ansible_private_ipv4_address:{{ansible_private_ipv4_address}}
- [root@idc-server1ansible]#mkdir/usr/share/ansible/heylinux
- [root@idc-server1ansible]#vim/usr/share/ansible/heylinux/myfacts
- #!/usr/bin/python
- importsys
- importjson
- importshlex
- importcommands
- importre
- defget_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"Linkencap"|awk'{print$1}'|grep-wv'lo'""")
- nics=output.split('n')
- t_nic_info=""
- foriinnics:
- ipaddr=commands.getoutput("""/sbin/ifconfig%s|grep-w"inetaddr"|cut-d:-f2|awk'{print$1}'"""%(i))
- ifre.match(iprex,ipaddr):
- ansible_private_ipv4_address=ipaddr
- returnansible_private_ipv4_address
- args_file=sys.argv[1]
- args_data=file(args_file).read()
- arguments=shlex.split(args_data)
- forarginarguments:
- if"="inarg:
- (key,value)=arg.split("=")
- ifkey=="get_facts"andvalue=="yes":
- ansible_private_ipv4_address=get_ansible_private_ipv4_address()
- printjson.dumps({
- "changed":False,
- "ansible_facts":{
- "ansible_private_ipv4_address":ansible_private_ipv4_address
- }
- })
- sys.exit(0)
- printjson.dumps({
- "changed":False
- })
- [root@idc-server1ansible]#ansible-playbook-urootmyfacts.yml-ihosts
- PLAY[idc1-server2]***************************************************************
- GATHERINGFACTS***************************************************************
- ok:[idc1-server2]
- TASK:[myfacts|runmyfactsmoduletogetcustomizedfacts]**************
- ok:[idc1-server2]
- TASK:[myfacts|updatefilewiththecustomizedfacts]*********************
- changed:[idc1-server2]
- PLAYRECAP********************************************************************
- idc1-server2:ok=3changed=1unreachable=0failed=0--phpfensi.com
- [root@idc-server1ansible]#sshidc1-server2'cat/tmp/myfacts.txt'
- ansible_private_ipv4_address:172.16.1.2