ansible模块自定义开发

自定义参数

自定义参数是在使用ansible模块时需要传递给ansible模块的变量,比如复制文件需要的src、dest、status等参数。具体参数类型如下:

参数类型 描述 示例
字符串 (str) 接受文本字符串作为参数。 "example"
整数 (int) 接受整数值作为参数。 42
浮点数 (float) 接受浮点数值作为参数。 3.14
布尔值 (bool) 接受布尔值 (TrueFalse) 作为参数。 True
列表 (list) 接受包含多个值的列表作为参数。 [1, 2, 3]
字典 (dict) 接受包含多个键值对的字典作为参数。 {"key": "value"}
路径 (path) 接受文件路径作为参数。 /path/to/file.txt
选择 (choices) 限制参数的取值范围,从预定义选项中选择。 "option"
默认值 (default) 为参数设置默认值,如果用户未提供参数,则使用默认值。 "default_value"
必需 (required) 指定参数是否必需,如果未提供则模块失败。 truefalse

示例代码

  1. 将需要的参数类型封装到AnsibleModule对象中
  2. 将需要传递给代码的参数变量通过module.params获取
  3. 通过if __name__ == '__main__':调用main函数,实现调用模块的方法
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(type='str', required=True),
state=dict(type='str', choices=['present', 'absent'], default='present')
)
)

path = module.params['path']
state = module.params['state']
if state == 'present':
if not os.path.exists(path):
open(path, 'w').close()
module.exit_json(changed=True, msg="File created successfully")
else:
module.exit_json(changed=False, msg="File already exists")
if __name__ == '__main__':
main()

模块返回结果

模块的返回结果通过module.exit_json()module.fail_json()方法返回,返回的参数如下:

字段名 类型 描述
changed 布尔值 指示是否发生了变更。如果任务执行导致实际变更,则为 true;否则为 false
msg 字符串 提供有关任务执行的描述性消息,以便用户了解任务结果。通常包括成功或失败的消息。
failed 布尔值 指示任务是否失败。如果任务失败,则为 true;如果任务成功,则为 false
  1. 通常会把要返回的数据封装到result字典中然后通过module.exit_json(**result)将结果返回给ansible;
  2. 如果返回正常的结果返回给module.exit_json()
  3. 如果结果异常返回给module.fail_json();

示例代码

if state == 'present':
if not os.path.exists(path):
changed = create_file(path)
if changed:
module.exit_json(changed=True, msg="File created successfully")
else:
module.fail_json(msg="Failed to create file")
else:
module.exit_json(changed=False, msg="File already exists")
elif state == 'absent':
if os.path.exists(path):
changed = delete_file(path)
if changed:
module.exit_json(changed=True, msg="File deleted successfully")
else:
module.fail_json(msg="Failed to delete file")
else:
module.exit_json(changed=False, msg="File does not exist")

自定义模块路径

如果使用ansible-playbook剧本,在项目根目录下创建library目录并且将写好的ansible模块放到改目录下即可

文章作者: 慕容峻才
文章链接: https://www.acaiblog.top/ansible模块自定义开发/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿才的博客
微信打赏
支付宝打赏