Ansible API调用测试

Ansible API调用测试

本文主要作为记录并未实际使用验证

以下代码是博主测试使用的代码,博主测试使用密码来测试,如需秘钥只要将password注释了就可以使用秘钥了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
$ 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模块,其他模块网友请自行测试。

1
2
3
4
5
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。

1
2
3
4
5
6
7
8
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文件,其他网友自行测试。

1
2
3
4
5
6
7
- hosts: te
remote_user: root
vars:
- touch_flile: 123.txt
tasks:
- name: touch file
shell: "touch /tmp/{{ touch_flile }}"

以下结果是经过博主json格式转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{
'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

1
2
3
4
5
6
7
8
9
10
11
12
##########Hosts##########
testserver1
testserver2
##########Groups##########
all
ungrouped
group1
group2
group3
group4
##########all group hosts##########
[testserver1, testserver2]

原文地址

本文标题:Ansible API调用测试

文章作者:shuke

发布时间:2020年04月20日 - 20:04

最后更新:2020年04月20日 - 20:04

原始链接:https://shuke163.github.io/2020/04/20/Ansible-API%E8%B0%83%E7%94%A8%E6%B5%8B%E8%AF%95/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------本文结束感谢您的阅读-------------

本文标题:Ansible API调用测试

文章作者:shuke

发布时间:2020年04月20日 - 20:04

最后更新:2020年04月20日 - 20:04

原始链接:https://shuke163.github.io/2020/04/20/Ansible-API%E8%B0%83%E7%94%A8%E6%B5%8B%E8%AF%95/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%