Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018 Hai Cao, <[email protected]>, Yunge Zhu <[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 DOCUMENTATION = '''
11 ---
12 module: azure_rm_cdnprofile
13 version_added: "0.1.2"
14 short_description: Manage a Azure CDN profile
15 description:
16 - Create, update and delete a Azure CDN profile.
17
18 options:
19 resource_group:
20 description:
21 - Name of a resource group where the CDN profile exists or will be created.
22 required: true
23 type: str
24 name:
25 description:
26 - Name of the CDN profile.
27 required: true
28 type: str
29 location:
30 description:
31 - Valid Azure location. Defaults to location of the resource group.
32 type: str
33 sku:
34 description:
35 - The pricing tier, defines a CDN provider, feature list and rate of the CDN profile.
36 - Detailed pricing can be find at U(https://azure.microsoft.com/en-us/pricing/details/cdn/).
37 type: str
38 choices:
39 - standard_verizon
40 - premium_verizon
41 - custom_verizon
42 - standard_akamai
43 - standard_chinacdn
44 - standard_microsoft
45 - standard_azurefrontdoor
46 - premium_azurefrontdoor
47 - standard_955bandwidth_chinacdn
48 - standard_avgbandwidth_chinacdn
49 - standardplus_chinacdn
50 - standardplus_955bandwidth_chinacdn
51 - standardplus_avgbandwidth_chinacdn
52 state:
53 description:
54 - Assert the state of the CDN profile. Use C(present) to create or update a CDN profile and C(absent) to delete it.
55 default: present
56 type: str
57 choices:
58 - absent
59 - present
60
61 extends_documentation_fragment:
62 - azure.azcollection.azure
63 - azure.azcollection.azure_tags
64 - azure.azcollection.azure_identity_multiple
65
66 author:
67 - Hai Cao (@caohai)
68 - Yunge Zhu (@yungezz)
69 '''
70
71 EXAMPLES = '''
72 - name: Create a CDN profile
73 azure_rm_cdnprofile:
74 resource_group: myResourceGroup
75 name: myCDN
76 sku: standard_akamai
77 tags:
78 testing: testing
79
80 - name: Delete the CDN profile
81 azure_rm_cdnprofile:
82 resource_group: myResourceGroup
83 name: myCDN
84 state: absent
85 '''
86 RETURN = '''
87 id:
88 description: Current state of the CDN profile.
89 returned: always
90 type: dict
91 example:
92 id: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.Cdn/profiles/myCDN
93 '''
94 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
95 import uuid
96
97 try:
98 from azure.mgmt.cdn.models import Profile, Sku, ManagedServiceIdentity, UserAssignedIdentity, ProfileUpdateParameters
99 except ImportError as ec:
100 # This is handled in azure_rm_common
101 pass
102
103
104 def cdnprofile_to_dict(cdnprofile):
105 return dict(
106 id=cdnprofile.id,
107 name=cdnprofile.name,
108 type=cdnprofile.type,
109 location=cdnprofile.location,
110 sku=cdnprofile.sku.name,
111 resource_state=cdnprofile.resource_state,
112 provisioning_state=cdnprofile.provisioning_state,
113 tags=cdnprofile.tags,
114 identity=cdnprofile.identity.as_dict() if cdnprofile.identity else None
115 )
116
117
118 class AzureRMCdnprofile(AzureRMModuleBaseExt):
119
120 def __init__(self):
121 self.module_arg_spec = dict(
122 resource_group=dict(
123 type='str',
124 required=True
125 ),
126 name=dict(
127 type='str',
128 required=True
129 ),
130 location=dict(
131 type='str'
132 ),
133 state=dict(
134 type='str',
135 default='present',
136 choices=['present', 'absent']
137 ),
138 sku=dict(
139 type='str',
140 choices=[
141 'standard_verizon', 'premium_verizon', 'custom_verizon', 'standard_akamai', 'standard_chinacdn',
142 'standard_microsoft', 'standard_azurefrontdoor', 'premium_azurefrontdoor',
143 'standard_955bandwidth_chinacdn', 'standard_avgbandwidth_chinacdn', 'standardplus_chinacdn',
144 'standardplus_955bandwidth_chinacdn', 'standardplus_avgbandwidth_chinacdn'
145 ]
146 ),
147 identity=dict(
148 type="dict",
149 options=self.managed_identity_multiple_spec
150 )
151 )
152
153 self.resource_group = None
154 self.name = None
155 self.location = None
156 self.state = None
157 self.tags = None
158 self.sku = None
159 self.identity = None
160 self._managed_identity = None
161
162 required_if = [
163 ('state', 'present', ['sku'])
164 ]
165
166 self.results = dict(changed=False)
167
168 super(AzureRMCdnprofile, self).__init__(derived_arg_spec=self.module_arg_spec,
169 supports_check_mode=True,
170 supports_tags=True,
171 required_if=required_if)
172
173 @property
174 def managed_identity(self):
175 if not self._managed_identity:
176 self._managed_identity = {
177 "identity": ManagedServiceIdentity,
178 "user_assigned": UserAssignedIdentity,
179 }
180 return self._managed_identity
181
182 def exec_module(self, **kwargs):
183 """Main module execution method"""
184
185 for key in list(self.module_arg_spec.keys()) + ['tags']:
186 setattr(self, key, kwargs[key])
187
188 to_be_updated = False
189
190 resource_group = self.get_resource_group(self.resource_group)
191 if not self.location:
192 self.location = resource_group.location
193
194 response = self.get_cdnprofile()
195
196 if self.state == 'present':
197
198 curr_identity = response["identity"] if response else None
199 update_identity = False
200 if self.identity:
201 update_identity, self.identity = self.update_managed_identity(curr_identity=curr_identity, new_identity=self.identity, patch_support=True)
202
203 if not response:
204 self.log("Need to create the CDN profile")
205
206 if not self.check_mode:
207 new_response = self.create_cdnprofile()
208 self.results['id'] = new_response['id']
209
210 self.results['changed'] = True
211
212 else:
213 self.log('Results : {0}'.format(response))
214 update_tags, response['tags'] = self.update_tags(response['tags'])
215
216 if response['provisioning_state'] == "Succeeded":
217 if update_tags or update_identity:
218 to_be_updated = True
219
220 if to_be_updated:
221 self.log("Need to update the CDN profile")
222
223 if not self.check_mode:
224 new_response = self.update_cdnprofile()
225 self.results['id'] = new_response['id']
226
227 self.results['changed'] = True
228
229 elif self.state == 'absent':
230 if not response:
231 self.fail("CDN profile {0} not exists.".format(self.name))
232 else:
233 self.log("Need to delete the CDN profile")
234 self.results['changed'] = True
235
236 if not self.check_mode:
237 self.delete_cdnprofile()
238 self.results['id'] = response['id']
239
240 return self.results
241
242 def create_cdnprofile(self):
243 '''
244 Creates a Azure CDN profile.
245
246 :return: deserialized Azure CDN profile instance state dictionary
247 '''
248 self.log("Creating the Azure CDN profile instance {0}".format(self.name))
249
250 parameters = Profile(
251 location=self.location,
252 sku=Sku(name=self.sku),
253 tags=self.tags,
254 identity=self.identity
255 )
256
257 xid = str(uuid.uuid1())
258
259 try:
260 poller = self.cdn_client.profiles.begin_create(self.resource_group,
261 self.name,
262 parameters)
263 response = self.get_poller_result(poller)
264 return cdnprofile_to_dict(response)
265 except Exception as exc:
266 self.log('Error attempting to create Azure CDN profile instance.')
267 self.fail("Error Creating Azure CDN profile instance: {0}".format(exc.message))
268
269 def update_cdnprofile(self):
270 '''
271 Updates a Azure CDN profile.
272
273 :return: deserialized Azure CDN profile instance state dictionary
274 '''
275 self.log("Updating the Azure CDN profile instance {0}".format(self.name))
276
277 try:
278 parameters = ProfileUpdateParameters(
279 tags=self.tags,
280 identity=self.identity
281 )
282 poller = self.cdn_client.profiles.begin_update(
283 self.resource_group,
284 self.name,
285 parameters
286 )
287 response = self.get_poller_result(poller)
288 return cdnprofile_to_dict(response)
289 except Exception as exc:
290 self.log('Error attempting to update Azure CDN profile instance.')
291 self.fail("Error updating Azure CDN profile instance: {0}".format(exc.message))
292
293 def delete_cdnprofile(self):
294 '''
295 Deletes the specified Azure CDN profile in the specified subscription and resource group.
296
297 :return: True
298 '''
299 self.log("Deleting the CDN profile {0}".format(self.name))
300 try:
301 poller = self.cdn_client.profiles.begin_delete(
302 self.resource_group, self.name)
303 self.get_poller_result(poller)
304 return True
305 except Exception as e:
306 self.log('Error attempting to delete the CDN profile.')
307 self.fail("Error deleting the CDN profile: {0}".format(e.message))
308 return False
309
310 def get_cdnprofile(self):
311 '''
312 Gets the properties of the specified CDN profile.
313
314 :return: deserialized CDN profile state dictionary
315 '''
316 self.log(
317 "Checking if the CDN profile {0} is present".format(self.name))
318 try:
319 response = self.cdn_client.profiles.get(self.resource_group, self.name)
320 self.log("Response : {0}".format(response))
321 self.log("CDN profile : {0} found".format(response.name))
322 return cdnprofile_to_dict(response)
323 except Exception:
324 self.log('Did not find the CDN profile.')
325 return False
326
327
328 def main():
329 """Main execution"""
330 AzureRMCdnprofile()
331
332
333 if __name__ == '__main__':
334 main()