Ansible develop module

本文介绍了一个Ansible自定义模块的实现,该模块能够执行获取、更新或删除指定路径下配置文件的操作。通过传递不同的参数,可以灵活地管理配置项。
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

   

转载于:https://www.cnblogs.com/mhc-fly/p/7122873.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值