Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_containerregistrywebhook.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Zim Kalinowski, <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_containerregistrywebhook
14 version_added: "0.1.2"
15 short_description: Manage Webhook instance.
16 description:
17 - Create, update and delete instance of Webhook.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group to which the container registry belongs.
23 required: True
24 type: str
25 registry_name:
26 description:
27 - The name of the container registry.
28 required: True
29 type: str
30 webhook_name:
31 description:
32 - The name of the webhook.
33 required: True
34 type: str
35 location:
36 description:
37 - Resource location. If not set, location from the resource group will be used as default.
38 type: str
39 service_uri:
40 description:
41 - The service URI for the webhook to post notifications.
42 type: str
43 custom_headers:
44 description:
45 - Custom headers that will be added to the webhook notifications.
46 type: dict
47 status:
48 description:
49 - The status of the webhook at the time the operation was called.
50 type: str
51 choices:
52 - 'enabled'
53 - 'disabled'
54 scope:
55 description:
56 - "The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository 'foo'. 'foo:bar' m
57 eans events for 'foo:bar' only. 'foo' is equivalent to 'foo:latest'. Empty means all events."
58 type: str
59 actions:
60 description:
61 - The list of actions that trigger the webhook to post notifications.
62 type: list
63 elements: str
64 state:
65 description:
66 - Assert the state of the Container registery replication.
67 - Use C(present) to create or update Container registery replication and C(absent) to delete it.
68 default: present
69 type: str
70 choices:
71 - absent
72 - present
73
74 extends_documentation_fragment:
75 - azure.azcollection.azure
76
77 author:
78 - "Zim Kalinowski (@zikalino)"
79
80 '''
81
82 EXAMPLES = '''
83 - name: Create (or update) Webhook
84 azure_rm_containerregistrywebhook:
85 resource_group: myResourceGroup
86 registry_name: myRegistry
87 webhook_name: myWebhook
88 location: eastus
89 service_uri: http://test123.com
90 scope: test123
91 custom_headers:
92 Key: Value1
93 actions:
94 - push
95 '''
96
97 RETURN = '''
98 id:
99 description:
100 - The resource ID.
101 returned: always
102 type: str
103 sample: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ContainerRegistry/registries/myRegistry/w
104 ebhooks/myWebhook"
105 status:
106 description:
107 - "The status of the webhook at the time the operation was called. Possible values include: 'enabled', 'disabled'"
108 returned: always
109 type: str
110 sample: enabled
111 '''
112
113 import time
114 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
115
116 try:
117 from azure.core.exceptions import ResourceNotFoundError
118 from azure.core.polling import LROPoller
119 except ImportError:
120 # This is handled in azure_rm_common
121 pass
122
123
124 def create_webhook_dict(webhook):
125 if webhook is None:
126 return None
127 results = dict(
128 id=webhook.id,
129 name=webhook.name,
130 location=webhook.location,
131 provisioning_state=webhook.provisioning_state,
132 tags=webhook.tags,
133 status=webhook.status
134 )
135 return results
136
137
138 class Actions:
139 NoAction, Create, Update, Delete = range(4)
140
141
142 class AzureRMWebhooks(AzureRMModuleBase):
143 """Configuration class for an Azure RM Webhook resource"""
144
145 def __init__(self):
146 self.module_arg_spec = dict(
147 resource_group=dict(
148 type='str',
149 required=True
150 ),
151 registry_name=dict(
152 type='str',
153 required=True
154 ),
155 webhook_name=dict(
156 type='str',
157 required=True
158 ),
159 location=dict(
160 type='str'
161 ),
162 service_uri=dict(
163 type='str'
164 ),
165 custom_headers=dict(
166 type='dict'
167 ),
168 status=dict(
169 type='str',
170 choices=['enabled',
171 'disabled']
172 ),
173 scope=dict(
174 type='str'
175 ),
176 actions=dict(
177 type='list',
178 elements='str'
179 ),
180 state=dict(
181 type='str',
182 default='present',
183 choices=['present', 'absent']
184 )
185 )
186
187 self.resource_group = None
188 self.registry_name = None
189 self.webhook_name = None
190 self.parameters = dict()
191
192 self.results = dict(changed=False)
193 self.state = None
194 self.to_do = Actions.NoAction
195
196 super(AzureRMWebhooks, self).__init__(derived_arg_spec=self.module_arg_spec,
197 supports_check_mode=True,
198 supports_tags=False)
199
200 def exec_module(self, **kwargs):
201 """Main module execution method"""
202
203 for key in list(self.module_arg_spec.keys()):
204 if hasattr(self, key):
205 setattr(self, key, kwargs[key])
206 elif kwargs[key] is not None:
207 if key == "location":
208 self.parameters["location"] = kwargs[key]
209 elif key == "service_uri":
210 self.parameters["service_uri"] = kwargs[key]
211 elif key == "custom_headers":
212 self.parameters["custom_headers"] = kwargs[key]
213 elif key == "status":
214 self.parameters["status"] = kwargs[key]
215 elif key == "scope":
216 self.parameters["scope"] = kwargs[key]
217 elif key == "actions":
218 self.parameters["actions"] = kwargs[key]
219
220 old_response = None
221 response = None
222
223 resource_group = self.get_resource_group(self.resource_group)
224
225 if 'location' not in self.parameters:
226 self.parameters['location'] = resource_group.location
227
228 old_response = self.get_webhook()
229
230 if not old_response:
231 self.log("Webhook instance doesn't exist")
232 if self.state == 'absent':
233 self.log("Old instance didn't exist")
234 else:
235 self.to_do = Actions.Create
236 else:
237 self.log("Webhook instance already exists")
238 if self.state == 'absent':
239 self.to_do = Actions.Delete
240 elif self.state == 'present':
241 self.log("Need to check if Webhook instance has to be deleted or may be updated")
242 self.to_do = Actions.Update
243
244 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
245 self.log("Need to Create / Update the Webhook instance")
246
247 if self.check_mode:
248 self.results['changed'] = True
249 return self.results
250
251 response = self.create_update_webhook()
252
253 if not old_response:
254 self.results['changed'] = True
255 else:
256 self.results['changed'] = old_response.__ne__(response)
257 self.log("Creation / Update done")
258 elif self.to_do == Actions.Delete:
259 self.log("Webhook instance deleted")
260 self.results['changed'] = True
261
262 if self.check_mode:
263 return self.results
264
265 self.delete_webhook()
266 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
267 # for some time after deletion -- this should be really fixed in Azure
268 while self.get_webhook():
269 time.sleep(20)
270 else:
271 self.log("Webhook instance unchanged")
272 self.results['changed'] = False
273 response = old_response
274
275 if response:
276 self.results["id"] = response["id"]
277 self.results["status"] = response["status"]
278
279 return self.results
280
281 def create_update_webhook(self):
282 '''
283 Creates or updates Webhook with the specified configuration.
284
285 :return: deserialized Webhook instance state dictionary
286 '''
287 self.log("Creating / Updating the Webhook instance {0}".format(self.webhook_name))
288
289 try:
290 if self.to_do == Actions.Create:
291 response = self.containerregistry_client.webhooks.begin_create(resource_group_name=self.resource_group,
292 registry_name=self.registry_name,
293 webhook_name=self.webhook_name,
294 webhook_create_parameters=self.parameters)
295 else:
296 response = self.containerregistry_client.webhooks.begin_update(resource_group_name=self.resource_group,
297 registry_name=self.registry_name,
298 webhook_name=self.webhook_name,
299 webhook_update_parameters=self.parameters)
300 if isinstance(response, LROPoller):
301 response = self.get_poller_result(response)
302
303 except Exception as exc:
304 self.log('Error attempting to create the Webhook instance.')
305 self.fail("Error creating the Webhook instance: {0}".format(str(exc)))
306 return create_webhook_dict(response)
307
308 def delete_webhook(self):
309 '''
310 Deletes specified Webhook instance in the specified subscription and resource group.
311
312 :return: True
313 '''
314 self.log("Deleting the Webhook instance {0}".format(self.webhook_name))
315 try:
316 response = self.containerregistry_client.webhooks.begin_delete(resource_group_name=self.resource_group,
317 registry_name=self.registry_name,
318 webhook_name=self.webhook_name)
319 self.get_poller_result(response)
320 except Exception as e:
321 self.log('Error attempting to delete the Webhook instance.')
322 self.fail("Error deleting the Webhook instance: {0}".format(str(e)))
323
324 return True
325
326 def get_webhook(self):
327 '''
328 Gets the properties of the specified Webhook.
329
330 :return: deserialized Webhook instance state dictionary
331 '''
332 self.log("Checking if the Webhook instance {0} is present".format(self.webhook_name))
333 found = False
334 try:
335 response = self.containerregistry_client.webhooks.get(resource_group_name=self.resource_group,
336 registry_name=self.registry_name,
337 webhook_name=self.webhook_name)
338 found = True
339 self.log("Response : {0}".format(response))
340 self.log("Webhook instance : {0} found".format(response.name))
341 except ResourceNotFoundError as e:
342 self.log('Did not find the Webhook instance: {0}'.format(str(e)))
343 if found is True:
344 return response.as_dict()
345
346 return False
347
348
349 def main():
350 """Main execution"""
351 AzureRMWebhooks()
352
353
354 if __name__ == '__main__':
355 main()