首页 > 代码库 > Ansible develop module
Ansible develop module
def cnf(action,configs,path):
message = "Modify %s\n" %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\n" %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
Ansible develop module
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。