編寫Ansible模組並自訂Facts例子

來源:互聯網
上載者:User

背景介紹:
Ansible內建的Facts有很多,但很多時候並不夠用。
比如,Ansible就沒有ansible_private_ipv4_address這樣一個Facts,用來儲存私網IP地址。
而我們恰恰就需要這樣的一個Facts,因為我們有很多伺服器的預設網卡並非是eth0,有的是bond0,eth1,em0,em1等,而公網IP地址與私網IP地址也並沒有固定的綁定在某個網卡上,很多時候還是虛擬網卡。
還好,我們可以通過編寫Ansible模組並自訂Facts來實現。

具體步驟:

 代碼如下 複製代碼

[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 $1}' |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 $1}'""" % (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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.