health_check
2.5 KB
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
#!/usr/bin/python
# -*- coding: UTF-8 -*-
ANSIBLE_METADATA = {
'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'chunhua.zhang'
}
DOCUMENTATION = '''
---
module: health_check
short_description: 检查有货java的服务健康状态
'''
EXAMPLES = '''
# order
- hosts: java-order
tasks:
- health_check:
name: 获取商品详情
url: "http://127.0.0.1:8084/order/orderInfo/getOrderList"
content-type: json
params: '{"param":439486}'
'''
from ansible.module_utils.basic import *
import requests
import json
'''
检查http服务的状态
'''
def check_http_status(url, content_type, params, headers):
if content_type == 'json':
r = requests.post(url, json = json.loads(params))
else:
r = requests.get(url, headers = headers)
# check http status code
if r.status_code != requests.codes.ok:
print("status check failed with status code: %i " % r.status_code )
return False, "status code [%i] failed" %r.status_code
# check json response
json_r = r.json()
if json_r['code'] != 200:
print("response body check failed: %s " % r.text )
return False, "response check failed %s" % r.text
return True, 'OK'
def run_module():
# 定义参数
module_args = dict(
name=dict(type='str', required=True),
url=dict(type='str', required=True),
content_type=dict(type='str', required=False),
params=dict(type='str', required=False)
)
# seed the result dict in the object
# we primarily care about changed and state
# change is if this module effectively modified the target
# state will include any data that you want your module to pass back
# for consumption, for example, in a subsequent task
result = dict(
changed=False,
original_message='',
message=''
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
if module.check_mode:
return result
url = module.params['url']
name = module.params['name']
content_type = module.params['content_type']
params = module.params['params']
result['original_message'] = module.params['name']
result['message'] = '%s' % module.params
r, msg = check_http_status(url, content_type, params)
if not r:
module.fail_json(msg='Check Failed: %s' %msg, **result)
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()