health_check 2.55 KB
#!/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 = {}):

    ret = {}
    if content_type == 'json':
        r =  requests.post(url, json = json.loads(params))
    else:
        r =  requests.get(url, headers = headers)
    # check http status code
    ret['http_code'] = r.status_code
    #ret['message'] = r.text
    if  r.status_code  == requests.codes.ok:
        # json code
        ret["code"] = r.json()['code']
        ret['err'] = ret["code"]
    else: 
        ret["code"] = r.status_code
        ret["err"] = r.text
    return ret


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['check_name'] = module.params['name']
    result['url'] =  module.params['url']
    result['changed'] = False

    # check result
    ret = check_http_status(url, content_type, params)
    if ret['code'] != 200:
        module.fail_json(msg='Check Failed: http code:%i, json code: %i, err: %s' % (ret['http_code'], ret['code'], ret['err']), **result)
    result['response'] = ret
    module.exit_json(**result)

def main():
    run_module()

if __name__ == '__main__':
    main()