Debian Codegraph @

ansible_collections/pcg/alpaca_operator/plugins/modules/alpaca_agent.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the Ansible project
5 # Apache License, Version 2.0 (see LICENSE or https://www.apache.org/licenses/LICENSE-2.0)
6
7
8 from __future__ import (absolute_import, division, print_function)
9
10 __metaclass__ = type
11
12 DOCUMENTATION = r'''
13 ---
14 module: alpaca_agent
15
16 short_description: Manage ALPACA Operator agents via REST API
17
18 version_added: '1.0.0'
19
20 extends_documentation_fragment:
21 - pcg.alpaca_operator.api_connection
22
23 description: This module allows you to create, update or delete ALPACA Operator agents using the REST API.
24
25 options:
26 name:
27 description: Unique name (hostname) of the agent.
28 version_added: '1.0.0'
29 required: true
30 type: str
31 new_name:
32 description: >
33 Optional new name for the agent. If the agent specified in O(name) exists,
34 it will be renamed to this value. If the agent does not exist, a new agent will
35 be created using this value.
36 version_added: '1.0.0'
37 required: false
38 type: str
39 description:
40 description: Unique description of the agent.
41 version_added: '1.0.0'
42 required: false
43 type: str
44 escalation:
45 description: Escalation configuration.
46 version_added: '1.0.0'
47 required: false
48 type: dict
49 suboptions:
50 failures_before_report:
51 description: Number of failures before reporting.
52 version_added: '2.0.0'
53 required: false
54 type: int
55 default: 0
56 mail_enabled:
57 description: Whether mail notification is enabled.
58 version_added: '2.0.0'
59 required: false
60 type: bool
61 default: false
62 mail_address:
63 description: Mail address for notifications.
64 version_added: '2.0.0'
65 required: false
66 type: str
67 default: ""
68 sms_enabled:
69 description: Whether SMS notification is enabled.
70 version_added: '2.0.0'
71 required: false
72 type: bool
73 default: false
74 sms_address:
75 description: SMS address for notifications.
76 version_added: '2.0.0'
77 required: false
78 type: str
79 default: ""
80 ip_address:
81 description: IP address of the agent.
82 version_added: '2.0.0'
83 required: false
84 type: str
85 location:
86 description: Location of the agent. Can be V(virtual), V(local1), V(local2), or V(remote).
87 version_added: '1.0.0'
88 required: false
89 type: str
90 choices: [virtual, local1, local2, remote]
91 default: virtual
92 script_group_id:
93 description: Script Group ID.
94 version_added: '2.0.0'
95 required: false
96 type: int
97 default: -1
98 state:
99 description: Desired state of the agent.
100 version_added: '1.0.0'
101 required: false
102 default: present
103 choices: [present, absent]
104 type: str
105
106 requirements:
107 - ALPACA Operator >= 5.6.0
108
109 attributes:
110 check_mode:
111 description: Can run in check_mode and return changed status prediction without modifying target.
112 support: full
113
114 author:
115 - Jan-Karsten Hansmeyer (@pcg)
116 '''
117
118 EXAMPLES = r'''
119 - name: Ensure agent exists
120 pcg.alpaca_operator.alpaca_agent:
121 name: agent01
122 ip_address: 192.168.1.100
123 location: virtual
124 description: Test agent
125 escalation:
126 failures_before_report: 3
127 mail_enabled: true
128 mail_address: [email protected]
129 sms_enabled: true
130 sms_address: 0123456789
131 script_group_id: 0
132 state: present
133 api_connection:
134 host: localhost
135 port: 8443
136 protocol: https
137 username: secret
138 password: secret
139 tls_verify: False
140
141 - name: Ensure agent is absent
142 pcg.alpaca_operator.alpaca_agent:
143 name: agent01
144 state: absent
145 api_connection:
146 host: localhost
147 port: 8443
148 protocol: https
149 username: secret
150 password: secret
151 tls_verify: False
152
153 - name: Rename an existing agent
154 pcg.alpaca_operator.alpaca_agent:
155 name: agent01
156 new_name: agent_renamed
157 state: present
158 api_connection:
159 host: localhost
160 port: 8443
161 protocol: https
162 username: secret
163 password: secret
164 tls_verify: False
165 '''
166
167 RETURN = r'''
168 msg:
169 description: Status message indicating the result of the operation
170 returned: always
171 type: str
172 version_added: '1.0.0'
173 sample: Agent created
174
175 changed:
176 description: Indicates whether any change was made
177 returned: always
178 type: bool
179 version_added: '1.0.0'
180 sample: true
181
182 agent_config:
183 description: Details of the created, updated, or deleted agent configuration
184 returned: when state is present or absent
185 type: dict
186 version_added: '1.0.0'
187 sample:
188 id: 7
189 hostname: "testagent"
190 description: "Test agent"
191 ip_address: "10.1.1.1"
192 location: "virtual"
193 script_group_id: 2
194 escalation:
195 failures_before_report: 3
196 mail_enabled: true
197 mail_address: "[email protected]"
198 sms_enabled: false
199 sms_address: ""
200
201 changes:
202 description: Dictionary showing differences between the current and desired configuration
203 returned: when state is present and a change occurred
204 type: dict
205 version_added: '1.0.0'
206 sample:
207 ip_address:
208 current: "10.1.1.1"
209 desired: "10.1.1.2"
210 escalation:
211 mail_enabled:
212 current: false
213 desired: true
214 '''
215
216 from ansible_collections.pcg.alpaca_operator.plugins.module_utils._alpaca_api import api_call, get_token, lookup_resource, get_api_connection_argument_spec
217 from ansible.module_utils.basic import AnsibleModule
218
219
220 def build_payload(desired_agent_config, current_agent_config):
221 """
222 Constructs a configuration payload by prioritizing values from the desired configuration
223 dictionary. If a value is not provided in the desired configuration, the function falls
224 back to using the corresponding value from the existing configuration (if available).
225
226 Parameters:
227 desired_agent_config (dict): A dictionary containing the desired configuration values.
228 current_agent_config (dict): A dictionary with existing configuration values.
229
230 Returns:
231 dict: A combined configuration payload dictionary.
232 """
233
234 payload = {
235 "description": desired_agent_config.get('description', None) if desired_agent_config.get('description', None) is not None else current_agent_config.get('description', ''),
236 "escalation": {
237 "failuresBeforeReport": (desired_agent_config.get('escalation') or {}).get('failures_before_report', None) if (desired_agent_config.get('escalation') or {}).get('failures_before_report', None) is not None else current_agent_config.get('escalation', {}).get('failuresBeforeReport', 0),
238 "mailAddress": (desired_agent_config.get('escalation') or {}).get('mail_address', None) if (desired_agent_config.get('escalation') or {}).get('mail_address', None) is not None else current_agent_config.get('escalation', {}).get('mailAddress', ''),
239 "mailEnabled": (desired_agent_config.get('escalation') or {}).get('mail_enabled', None) if (desired_agent_config.get('escalation') or {}).get('mail_enabled', None) is not None else current_agent_config.get('escalation', {}).get('mailEnabled', False),
240 "smsAddress": (desired_agent_config.get('escalation') or {}).get('sms_address', None) if (desired_agent_config.get('escalation') or {}).get('sms_address', None) is not None else current_agent_config.get('escalation', {}).get('smsAddress', ''),
241 "smsEnabled": (desired_agent_config.get('escalation') or {}).get('sms_enabled', None) if (desired_agent_config.get('escalation') or {}).get('sms_enabled', None) is not None else current_agent_config.get('escalation', {}).get('smsEnabled', False),
242 },
243 "hostname": desired_agent_config.get('new_name', None) or desired_agent_config.get('name', None) if desired_agent_config.get('new_name', None) or desired_agent_config.get('name', None) is not None else current_agent_config.get('hostname', ''),
244 "ipAddress": desired_agent_config.get('ip_address', None) if desired_agent_config.get('ip_address', None) is not None else current_agent_config.get('ipAddress', ''),
245 "location": desired_agent_config.get('location', None) if desired_agent_config.get('location', None) is not None else current_agent_config.get('location', 'virtual'),
246 "scriptGroupId": desired_agent_config.get('script_group_id', None) if desired_agent_config.get('script_group_id', None) is not None else current_agent_config.get('scriptGroupId', -1),
247 }
248
249 return payload
250
251
252 def main():
253 module = AnsibleModule(
254 argument_spec=dict(
255 name=dict(type='str', required=True), # = hostname
256 new_name=dict(type='str', required=False), # = hostname
257 description=dict(type='str', required=False),
258 escalation=dict(type='dict', required=False),
259 ip_address=dict(type='str', required=False),
260 location=dict(type='str', required=False, default='virtual', choices=['virtual', 'local1', 'local2', 'remote']),
261 script_group_id=dict(type='int', required=False, default=-1),
262 state=dict(type='str', required=False, default='present', choices=['present', 'absent']),
263 api_connection=get_api_connection_argument_spec()
264 ),
265 supports_check_mode=True,
266 )
267
268 api_url = "{0}://{1}:{2}/api".format(module.params['api_connection']['protocol'], module.params['api_connection']['host'], module.params['api_connection']['port'])
269 token = get_token(api_url, module.params['api_connection']['username'], module.params['api_connection']['password'], module.params['api_connection']['tls_verify'])
270 headers = {"Authorization": "Bearer {0}".format(token)}
271 current_agent = lookup_resource(api_url, headers, "agents", "hostname", module.params['name'], module.params['api_connection']['tls_verify']) or lookup_resource(api_url, headers, "agents", "hostname", module.params['new_name'], module.params['api_connection']['tls_verify'])
272 current_agent_config = api_call(method="GET", url="{0}/agents/{1}".format(api_url, current_agent.get('id', None)), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to get current agent configuration").json() if current_agent else {}
273 agent_payload = build_payload(module.params, current_agent_config)
274 diff = {}
275
276 if module.params['state'] == 'present':
277 if current_agent:
278 # Compare current agent configuration with the desired agent configuration if it already exists
279 for key in agent_payload:
280 if key not in ['escalation']:
281 if agent_payload.get(key, None) != current_agent_config.get(key, None):
282 diff[key] = {
283 'current': current_agent_config.get(key, None),
284 'desired': agent_payload.get(key, None)
285 }
286 if key in ['escalation']:
287 for sub_key in agent_payload.get(key, {}):
288 if agent_payload.get(key, {}).get(sub_key, None) != current_agent_config.get(key, {}).get(sub_key, None):
289 if key not in diff:
290 diff[key] = {}
291 diff[key][sub_key] = {
292 'current': current_agent_config.get(key, {}).get(sub_key, None),
293 'desired': agent_payload.get(key, {}).get(sub_key, None)
294 }
295
296 if diff:
297 if module.check_mode:
298 module.exit_json(changed=True, msg="Agent would be updated", changes=diff)
299
300 # Update agent
301 current_agent_config = api_call("PUT", "{0}/agents/{1}".format(api_url, current_agent['id']), headers=headers, json=agent_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to update agent").json()
302 module.exit_json(changed=True, msg="Agent updated", agent_config=current_agent_config, changes=diff)
303
304 elif not current_agent:
305 if module.check_mode:
306 module.exit_json(changed=True, msg="Agent would be created", agent_config=agent_payload)
307
308 # Create the agent if it doesn't exist
309 current_agent_config = api_call("POST", "{0}/agents".format(api_url), headers=headers, json=agent_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to create agent").json()
310 module.exit_json(changed=True, msg="Agent created", agent_config=current_agent_config)
311
312 module.exit_json(changed=False, msg="Agent already exists with the desired configuration", agent_config=current_agent_config)
313
314 elif module.params['state'] == 'absent':
315 if not current_agent:
316 module.exit_json(changed=False, msg="Agent already absent")
317
318 if module.check_mode:
319 module.exit_json(changed=True, msg="Agent would be unassigned from all systems and deleted", agent_config=current_agent_config)
320
321 # Get all systems
322 systems = api_call(method="GET", url="{0}/systems".format(api_url), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to retrieve systems").json()
323
324 # Iterate through all systems and check for agent assignments and commands
325 for system in systems:
326 # List agents
327 # module.warn("Retrieve agents for system {0}...".format(system['id']))
328 agents = api_call(method="GET", url="{0}/systems/{1}/agents".format(api_url, system['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to retrieve agents").json()
329
330 # Check if the agent ID we are looking for is assigned to this system
331 if any(agent['id'] == current_agent['id'] for agent in agents):
332 # Unassign agent from system
333 # module.warn("Unassign agent {0} from system {1}".format(current_agent['id'], system['id']))
334 api_call(method="DELETE", url="{0}/systems/{1}/agents/{2}".format(api_url, system['id'], current_agent['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to unassign agent")
335
336 # Delete agent with retries
337 api_call("DELETE", "{0}/agents/{1}".format(api_url, current_agent['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to delete agent")
338 module.exit_json(changed=True, msg="Agent deleted", agent_config=current_agent_config)
339
340 module.exit_json(changed=True, msg="Agent state processed")
341
342
343 if __name__ == '__main__':
344 main()