zoukankan      html  css  js  c++  java
  • 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 8 – StringJoiner example
    Java – Generate random integers in a rangejava获取某个范围内的一个随机数
    Eclipse 中选中一个单词 ,其他相同的单词颜色就会变化
    JAR,WAR,EAR区别
    eclipse中java项目转成Web项目
    备忘
    iphone openssh
    如何解决Cydia提示错误
    加密备忘
    Ubuntu系统安装VMware Tools的简单方法
  • 原文地址:https://www.cnblogs.com/mhc-fly/p/7122873.html
Copyright © 2011-2022 走看看