Ansible API调用测试
本文主要作为记录并未实际使用验证
以下代码是博主测试使用的代码,博主测试使用密码来测试,如需秘钥只要将password注释了就可以使用秘钥了。
$ cat test.py
#! /usr/local/bin/python3
# -*- coding: utf-8 -*-
from setup.ansible_api.runner import AdHocRunner, CommandRunner, PlayBookRunner
from setup.ansible_api.inventory import BaseInventory
def TestAdHocRunner():
"""
以yml的形式 执行多个命令
:return:
"""
host_data = [
{
"hostname": "192.168.188.6",
"ip": "192.168.188.6",
"port": 22,
"username": "root",
"password": "admin12",
}
]
inventory = BaseInventory(host_data)
runner = AdHocRunner(inventory)
tasks = [
# {"action": {"module": "cron","args": "name=\"sync time\" minute=\"*/3\" job=\"/usr/sbin/ntpdate time.nist.gov &> /dev/null\"" }, "name": "run_cmd"},
# {"action": {"module": "shell", "args": "ls /root1"}, "name": "run_whoami"},
# {"action": {"module": "copy", "args": "src=/home/23.txt dest=/tmp","mode":"0644"}, "name": "run_whoami"},
# {"action": {"module": "setup", "args": ""}, "name": "run_whoami"},
{"action": {"module": "ping", "args": ""}, "name": "run_whoami"},
# {"action": {"module": "yum", "args": "name=httpd state=latest"}, "name": "run_whoami"},
]
ret = runner.run(tasks, "all")
print(ret.results_summary)
print(ret.results_raw)
def TestCommandRunner():
"""
执行单个命令,返回结果
:return:
"""
host_data = [
{
"hostname": "192.168.188.6",
"ip": "192.168.188.6",
"port": 22,
"username": "root",
"password": "admin12",
},
]
inventory = BaseInventory(host_data)
runner = CommandRunner(inventory)
res = runner.execute('who', 'all')
print(res.results_command)
print(res.results_raw)
print(res.results_command['192.168.188.6']['stdout'])
def TestPlayBookRunner():
"""
以yml的形式 执行多个命令
:return:
"""
host_data = [
{
"hostname": "192.168.188.6",
"ip": "192.168.188.5",
"port": 22,
"username": "root",
"password": "admin12",
}
]
inventory = BaseInventory(host_data)
path = '/etc/ansible/webservice.yml'
runner = PlayBookRunner(playbook_path=path,inventory=inventory)
ret = runner.run()
print(ret)
def TestInventoryRunner():
"""
返回主机信息,组信息,组内主机信息
:return:
"""
host_list = [{
"hostname": "testserver1",
"ip": "102.1.1.1",
"port": 22,
"username": "root",
"password": "password",
"private_key": "/tmp/private_key",
"become": {
"method": "sudo",
"user": "root",
"pass": None,
},
"groups": ["group1", "group2"],
"vars": {"sexy": "yes"},
}, {
"hostname": "testserver2",
"ip": "8.8.8.8",
"port": 2222,
"username": "root",
"password": "password",
"private_key": "/tmp/private_key",
"become": {
"method": "su",
"user": "root",
"pass": "123",
},
"groups": ["group3", "group4"],
"vars": {"love": "yes"},
}]
inventory = BaseInventory(host_list=host_list)
print("#"*10 + "Hosts" + "#"*10)
for host in inventory.hosts:
print(host)
print("#" * 10 + "Groups" + "#" * 10)
for group in inventory.groups:
print(group)
print("#" * 10 + "all group hosts" + "#" * 10)
group = inventory.get_group('all')
print(group.hosts)
if __name__ == "__main__":
TestPlayBookRunner()
TestAdHocRunnerRunner()
TestCommandRunner()
TestInventoryRunner()
下面测试调用AdHoc的测试结果,博主比较懒,只测试一个ping模块,其他模块网友请自行测试。
PLAY [Ansible Ad-hoc] **********************************************************
TASK [ping] ********************************************************************
ok: [192.168.188.6]
{'ok': {'192.168.188.6': {'ping': {'invocation': {'module_args': {'data': 'pong'}}, 'ping': 'pong', '_ansible_parsed': True, '_ansible_no_log': False, 'changed': False}}}, 'failed': {}, 'unreachable': {}, 'skipped': {}}
下面测试调用Command的测试结果,测试在目标机器上面使用who命令,其他命令网友自行测试。另外调用TestCommandRunner()必须是以下模块’shell’, ‘raw’, ‘command’, ‘script’,其他模块,请使用AdHoc。
PLAY [Run command who on 192.168.188.6] ****************************************
TASK [command] *****************************************************************
changed: [192.168.188.6]
{'192.168.188.6': {'cmd': 'who', 'stderr': '', 'stdout': 'root :0 2018-03-10 09:59 (:0)\nroot pts/1 2018-03-10 10:15 (192.168.188.7)', 'rc': 0, 'delta': '0:00:00.017265'}}
{'ok': {'192.168.188.6': {'command': {'changed': True, 'end': '2018-03-10 10:15:21.892560', 'stdout': 'root :0 2018-03-10 09:59 (:0)\nroot pts/1 2018-03-10 10:15 (192.168.188.7)', 'cmd': 'who', 'rc': 0, 'start': '2018-03-10 10:15:21.875295', 'stderr': '', 'delta': '0:00:00.017265', 'invocation': {'module_args': {'warn': True, 'executable': None, '_uses_shell': True, '_raw_params': 'who', 'removes': None, 'creates': None, 'chdir': None, 'stdin': None}}, '_ansible_parsed': True, 'stdout_lines': ['root :0 2018-03-10 09:59 (:0)', 'root pts/1 2018-03-10 10:15 (192.168.188.7)'], 'stderr_lines': [], '_ansible_no_log': False}}}, 'failed': {}, 'unreachable': {}, 'skipped': {}}
root :0 2018-03-10 09:59 (:0)
root pts/1 2018-03-10 10:15 (192.168.188.7)
下面测试调用PlayBook的测试结果。
下面是博主使用的playbook文件,只是简单的touch一个123.txt文件,其他网友自行测试。
- hosts: te
remote_user: root
vars:
- touch_flile: 123.txt
tasks:
- name: touch file
shell: "touch /tmp/{{ touch_flile }}"
以下结果是经过博主json格式转换
{
'results': [{
'task': {
'name': 'Gathering Facts'
},
'hosts': {
'192.168.188.6': {
'invocation': {
'module_args': {
'filter': '*',
'gather_subset': ['all'],
'fact_path': '/etc/ansible/facts.d',
'gather_timeout': 10
}
},
'_ansible_parsed': True,
'_ansible_verbose_override': True,
'_ansible_no_log': False,
'changed': False
}
}
}, {
'task': {
'name': 'touch file'
},
'hosts': {
'192.168.188.6': {
'changed': True,
'end': '2018-03-10 18:14:52.078526',
'stdout': '',
'cmd': 'touch /tmp/123.txt',
'rc': 0,
'start': '2018-03-10 18:14:52.064544',
'stderr': '',
'delta': '0:00:00.013982',
'invocation': {
'module_args': {
'warn': True,
'executable': None,
'_uses_shell': True,
'_raw_params': 'touch /tmp/123.txt',
'removes': None,
'creates': None,
'chdir': None,
'stdin': None
}
},
'warnings': ['Consider using file module with state=touch rather than running touch'],
'_ansible_parsed': True,
'stdout_lines': [],
'stderr_lines': [],
'_ansible_no_log': False
}
}
}],
'status': {
'192.168.188.6': {
'ok': 2,
'failures': 0,
'unreachable': 0,
'changed': 1,
'skipped': 0
}
}
}
下面测试Inventory
##########Hosts##########
testserver1
testserver2
##########Groups##########
all
ungrouped
group1
group2
group3
group4
##########all group hosts##########
[testserver1, testserver2]
网友评论