In the operation of the tool, the choice of using the Ansible API to interact with the server, the purpose of using ansible is simple, and the client does not need to install the agent, server installation after the Ansbile, the new machine can be managed.
In order to combine the asset management system (CMDB), the method of dynamically acquiring inventory is used, which eliminates the need to configure hosts on the Ansible server, all client IP, account numbers, passwords, and ports can be obtained from the CMDB.
The dynamic inventory script must support the following two command-line arguments:
--host (used to list the details of the host)
--list (used to list groups)
Examples of script output results:
[Root@dywl controller]# python test.py--list
{
"All": [
"192.168.1.6",
"192.168.1.10"
]
}
[Root@dywl controller]# python test.py--host 192.168.1.6
{
"Ansible_ssh_host": "192.168.1.6",
"Ansible_ssh_port": 22,
"Ansible_ssh_portansible_ssh_pass": "XXXX",
"Ansible_ssh_user": "Root"
}
Above script source code (in order to test, so the content is written dead in test.py)
#!/usr/bin/env python
#coding: UTF8
Import JSON
Import Sys
DEF group ():
Info_dict = {"All": ["192.168.1.6", "192.168.1.10"]}
Print Json.dumps (info_dict,indent=4)
def host (IP):
Info_dict = {"192.168.1.10": {"Ansible_ssh_host": "192.168.1.10", "Ansible_ssh_port": "Ansible_ssh_user": "Root", "" Ansible_ssh_port "" Ansible_ssh_pass ":" XXXX "}," 192.168.1.6 ": {" Ansible_ssh_host ":" 192.168.1.6 "," Ansible_ssh_port " : "Ansible_ssh_user": "Root", "Ansible_ssh_port" "Ansible_ssh_pass": "XXXX"}
Print Json.dumps (info_dict[ip],indent=4)
If Len (sys.argv) = = 2 and (sys.argv[1] = = '--list '):
Group ()
Elif len (sys.argv) = = 3 and (sys.argv[1] = = '--host '):
Host (Sys.argv[2])
Else
Print "Usage:%s--list or--host Sys.exit (1)
To get from the CMDB, of course, is to query from the database, so, we have to test the output format of the script, the database extracted from the data, the reorganization, in line with the dynamic inventyory rules can
I wrote the script:
#!/usr/bin/env python
#coding: UTF8
__author__ = ' Dairu '
"""
Get all the server's IP, account number, password, port, etc. from the database
"""
Import JSON
Import Sys
Import MySQLdb
Import logging
# Configure MySQL Database
db_name = ' Osyw '
Db_user = ' Osyw '
Db_pass = ' xxxxxx '
db_ip = ' 192.168.1.6 '
Db_port = 3306
def readdb (Sql,db_data= ()):
"""
Connect to MySQL database (from) and make data inquiries
"""
Try
conn = MySQLdb.connect (Db=db_name,user=db_user,passwd=db_pass,host=db_ip,port=int (db_port), charset= "UTF8")
cursor = Conn.cursor ()
Except Exception,e:
Print E
Logging.error (' Database connection failed:%s '% e)
Return False
Try
Cursor.execute (Sql,db_data)
data = [Dict (cursor.description[i][0], value) for I, value in enumerate (row)) for row in Cursor.fetchall ()]
Except Exception,e:
Logging.error (' Data execution failed:%s '% e)
Return False
Finally
Cursor.close ()
Conn.close ()
Return data
#从数据库中查询数据
sql = "Select Wip,nip,username,password from Yw_device"
result = READDB (sql,)
Def grouplist ():
"""
Organize the group information, the format is as follows: {"All": ["192.168.1.6", "192.168.1.10"]}
All of [all] in the corresponding Hosts file, where only 2 host groups are returned under [all]
192.168.1.6 and 192.168.1.10 are all the following aliases, combined with the following hostlist (), I was directly using IP to do the group name
[All]
192.168.1.6
192.168.1.10
[192.168.1.6]
192.168.1.6 ansible_ssh_host=192.168.1.6 ansible_ssh_user=root ansible_ssh_pass= ' xxxx,ansible_ssh_port=22
[192.168.1.10]
192.168.1.10 ansible_ssh_host=192.168.1.10 ansible_ssh_user=root ansible_ssh_pass= ' xxxx,ansible_ssh_port=22
(The above has the wrong also to be corrected ha)
"""
Group_list = []
For host in:
Group_list.append (host["WIP"])
Print Json.dumps ({"All": group_list},indent=4)
def hostList (key):
"""
Organize the host information, and then return the key information after receiving and receiving a key
My idea is to put the server IP as key, the server below the account information as value
The format is probably as follows:
xxx.py--host 192.168.1.6
Return
{
"Ansible_ssh_host": "192.168.1.6",
"Ansible_ssh_port": 22,
"Ansible_ssh_portansible_ssh_pass": "XXXX",
"Ansible_ssh_user": "Root"
}
"""
Host_dict = {}
For host in:
host_dict[host["WIP"] = {"Ansible_ssh_host": host["WIP"], "Ansible_ssh_port": "Ansible_ssh_user": "Root", " Ansible_ssh_pass ": xxxx"}
Print Json.dumps (host_dict[key],indent=4)
#命令行参数简易写法
If Len (sys.argv) = = 2 and (sys.argv[1] = = '--list '):
Grouplist ()
Elif len (sys.argv) = = 3 and (sys.argv[1] = = '--host '):
HostList (Sys.argv[2])
Else
Print "Usage:%s--list or--host Sys.exit (1)
Test (script requires executable permissions, but don't forget, chmod a+x test.py):
[Root@dywl controller]# ansible-i test.py 192.168.1.6-a uptime
192.168.1.6 | Success | Rc=0 >>
20:22:43 up 144 days, 2:14, 2 users, load average:0.18, 0.20, 0.18
If the script does not support--list and--host, the error message might be the following:
[Root@dywl controller]# ansible-i test.py 192.168.1.6-a UPTIME-VVV
Error:problem running/data/www/yw/controller/gethost.py--list ([Errno 2] No such file or directory)
But even if you write to support--list and--host, you may be confused by other strange problems, it is still the error of the above,--list ([Errno 2] No such file or directory), the next question I encountered, I run Python on the command line test.py--list, there is no problem, can normally output group information, but I use ansible-i test.py 192.168.1.6-a uptime, or reported--list ([Errno 2] No such file or Directo RY) error. Later I used direct use./test.py--list, also error, the reason is probably found, is not automatically use Python to parse this person script, so the script output error, will report the above error, looked for a long time did not find the problem, later found that the first line of the script:
(#!/usr/bin/env python) because my script was written with Pycharm and uploaded to the server with SVN, so the problem, now I don't understand exactly why, so I have to use VIM to open the script, delete the first line, and then write back
#!/usr/bin/env python, hehe
No matter what the script says, as long as you meet the inventory specification can, next, I will continue to use the Ansible API to develop operational tools, this set of tools, I should be open source to provide new students to learn to use, please wait a period of time ha, is now under development, almost the time will be released, Or use the Python bottle framework.