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