使用ansible.module_utils.basic中的AnsibleModule()创建模块
Ansible是一款非常强大的自动化工具,它允许用户通过编写Playbooks和模块来实现主机的自动化配置和部署。Ansible模块是Ansible Playbooks中最基本的组件之一,它定义了Ansible与主机进行交互的方式。
Ansible模块库中有一个非常有用的工具类模块basic中的AnsibleModule,这个工具类可以帮助我们更方便地编写自定义Ansible模块。
以下是一个使用AnsibleModule创建模块的例子:
#!/usr/bin/env python
# coding=utf-8
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True),
age=dict(type='int', required=True),
city=dict(type='str', required=False, default=''),
),
supports_check_mode=True
)
name = module.params['name']
age = module.params['age']
city = module.params['city']
# 检查模块是否在check模式下运行
if module.check_mode:
module.exit_json(
changed=False,
msg="Check mode: module would have made the following changes"
)
# 实现模块的逻辑操作
result = dict(
name=name,
age=age,
city=city,
success=True,
msg="Module execution successful"
)
# 返回结果给Ansible引擎
module.exit_json(**result)
if __name__ == '__main__':
main()
上面的例子中,我们首先导入了AnsibleModule类,并定义了模块的输入参数。通过argument_spec参数,我们指定了模块需要接收的参数以及每个参数的类型和是否必需。在这个例子中,我们定义了三个参数:name,age和city。
然后,我们创建了一个AnsibleModule实例,并传入了参数argument_spec和supports_check_mode=True。supports_check_mode=True表示模块支持Ansible的check模式,即在这个模式下,Ansible会执行模块的逻辑操作前先检查一下是否需要进行操作。
接着,我们通过module.params属性获取模块的输入参数。在这个例子中,我们获取了name,age和city参数的值。
然后,我们检查模块是否在check模式下运行,如果是的话,我们通过module.exit_json返回给Ansible引擎一条消息,告诉它模块会执行什么操作。
最后,我们实现了模块的逻辑操作,这里我们简单地将输入参数返回给Ansible引擎,然后通过module.exit_json返回执行结果。
在使用这个模块时,我们需要在Ansible的Playbook中调用它,例如:
- name: Test custom module
hosts: localhost
gather_facts: False
tasks:
- name: Run custom module
my_module:
name: John
age: 30
city: New York
register: result
- debug:
var: result
这个Playbook中,我们首先指定了要运行的主机,然后调用我们自定义的模块my_module,传入了参数name,age和city。接着,我们将模块的返回结果存储到result变量中,并通过debug模块打印出来。
以上就是使用AnsibleModule创建模块的示例。通过使用AnsibleModule工具类,我们可以更方便地编写自定义的Ansible模块,实现各种自动化操作。
