Does anybody have a very basic (demo-style) implementation of an Ansible module and associated Python back-end service which use a connection: httpapi?
During trainings I’d like to be able to demonstrate a play with a task or two which speak httpapi to a backend, such as when Fortigate or VMware tasks are used. It should be as basic as possible.
#!/usr/bin/python
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list
def run_module():
module_args = dict(
name=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['present', 'absent'])
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
name = module.params['name']
state = module.params['state']
result = dict(
changed=False,
original_message='',
message=''
)
# This is where you would implement the logic to interact with your httpapi backend
if module.check_mode:
module.exit_json(**result)
# Example of calling the service
from ansible.module_utils.connection import Connection
connection = Connection(module._socket_path)
if state == 'present':
response = connection.send_request('POST', '/api/v1/resources', {'name': name})
if response['status'] == 'success':
result['changed'] = True
result['message'] = f"Resource {name} added"
elif state == 'absent':
response = connection.send_request('DELETE', f'/api/v1/resources/{name}')
if response['status'] == 'success':
result['changed'] = True
result['message'] = f"Resource {name} removed"
if 'error' in response:
module.fail_json(msg=f"Error: {response['error']}")
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()