• Ansible develop module


    def cnf(action,configs,path):
    message = "Modify %s " %path
    changed = False
    if action == "get":
    with open(path,"r") as f:
    message = f.read()
    return changed,message
    if not os.path.exists(path):
    message += "%s do not exist, create it " %path
    cnf = Mycnf(path)
    if action == "update":
    changed,msg = cnf.set_all(configs)
    message += msg
    elif action == "delete":
    changed, msg = cnf.delete_all(configs)
    message += msg
    else:
    message = "Invalid action"
    return changed,message

    def main():
    module = AnsibleModule(
    argument_spec=dict(
    type=dict(default="cnf"),
    action=dict(default="update"),
    configs=dict(),
    path=dict(default="/etc/my.cnf"),
    ),
    supports_check_mode=True
    )

    type = module.params["type"]
    action = module.params["action"]
    configs = module.params["configs"]
    path = module.params["path"]

    if type not in TYPE:
    module.fail_json(msg="Invalid type %s,must be in %s" %(type,str(TYPE)))
    if action not in ACTION:
    module.fail_json(msg="Invalid action %s,must be in %s" %(action,str(ACTION)))
    try:
    configs = json.loads(configs)
    except:
    module.fail_json(msg="configs must be a json type")
    if action == "get" and not os.path.exists(path):
    module.fail_json(msg="%s do not exist" %path)
    try:
    cmd = globals()[type]
    changed, msg = cmd(action,configs,path)
    module.exit_json(changed=changed, stdout=msg)
    except Exception as e:
    module.fail_json(msg=e.message)

    from ansible.module_utils.basic import *

    if __name__ == '__main__':
    main()


    ======================================================================
    - hosts: localhost
      tasks:
     
      - name: test my module
        config_file:
          type: cnf
          action: delete
          configs: '{"mysqld":{"mhc":"2b"}}'
          path: /root/test/ansible_test/mhc_test/my.cnf
        register: mhc
     
      - debug: var=mhc

       
  • 相关阅读:
    java strtus2 拦截器(Interceptors)
    java ssm框架入门(三)正式项目的web.xml配置
    java Web监听器导图详解
    java web hello world(二)基于Servlet理解监听
    java ssm框架入门(二)添加语言滤器
    java web 自定义filter
    Java内存分配全面浅析
    Velocity !$ 和$!区别
    spring ioc原理(看完后大家可以自己写一个spring)
    Spring的AOP简单理解
  • 原文地址:https://www.cnblogs.com/mhc-fly/p/7122873.html
Copyright © 2020-2023  润新知