Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2019 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_devtestlab
14 version_added: "0.1.2"
15 short_description: Manage Azure DevTest Lab instance
16 description:
17 - Create, update and delete instance of Azure DevTest Lab.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group.
23 required: True
24 type: str
25 name:
26 description:
27 - The name of the lab.
28 required: True
29 type: str
30 location:
31 description:
32 - The location of the resource.
33 type: str
34 storage_type:
35 description:
36 - Type of storage used by the lab. It can be either C(premium) or C(standard).
37 type: str
38 choices:
39 - 'standard'
40 - 'premium'
41 premium_data_disks:
42 description:
43 - Allow creation of premium data disks.
44 type: bool
45 state:
46 description:
47 - Assert the state of the DevTest Lab.
48 - Use C(present) to create or update an DevTest Lab and C(absent) to delete it.
49 default: present
50 type: str
51 choices:
52 - absent
53 - present
54
55 extends_documentation_fragment:
56 - azure.azcollection.azure
57 - azure.azcollection.azure_tags
58
59 author:
60 - Zim Kalinowski (@zikalino)
61
62 '''
63
64 EXAMPLES = '''
65 - name: Create (or update) DevTest Lab
66 azure_rm_devtestlab:
67 resource_group: myResourceGroup
68 name: mylab
69 storage_type: standard
70 '''
71
72 RETURN = '''
73 id:
74 description:
75 - The identifier of the resource.
76 returned: always
77 type: str
78 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/mylab
79 '''
80
81 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
82 from ansible.module_utils.common.dict_transformations import _snake_to_camel
83
84 try:
85 from azure.core.polling import LROPoller
86 from azure.core.exceptions import ResourceNotFoundError
87 from azure.mgmt.devtestlabs import DevTestLabsClient
88 except ImportError:
89 # This is handled in azure_rm_common
90 pass
91
92
93 class Actions:
94 NoAction, Create, Update, Delete = range(4)
95
96
97 class AzureRMDevTestLab(AzureRMModuleBase):
98 """Configuration class for an Azure RM DevTest Lab resource"""
99
100 def __init__(self):
101 self.module_arg_spec = dict(
102 resource_group=dict(
103 type='str',
104 required=True
105 ),
106 name=dict(
107 type='str',
108 required=True
109 ),
110 location=dict(
111 type='str'
112 ),
113 storage_type=dict(
114 type='str',
115 choices=['standard',
116 'premium']
117 ),
118 premium_data_disks=dict(
119 type='bool'
120 ),
121 state=dict(
122 type='str',
123 default='present',
124 choices=['present', 'absent']
125 )
126 )
127
128 self.resource_group = None
129 self.name = None
130 self.lab = {}
131
132 self.results = dict(changed=False)
133 self.mgmt_client = None
134 self.state = None
135 self.to_do = Actions.NoAction
136
137 super(AzureRMDevTestLab, self).__init__(derived_arg_spec=self.module_arg_spec,
138 supports_check_mode=True,
139 supports_tags=True)
140
141 def exec_module(self, **kwargs):
142 """Main module execution method"""
143
144 for key in list(self.module_arg_spec.keys()) + ['tags']:
145 if hasattr(self, key):
146 setattr(self, key, kwargs[key])
147 elif kwargs[key] is not None:
148 self.lab[key] = kwargs[key]
149
150 if self.lab.get('storage_type'):
151 self.lab['lab_storage_type'] = _snake_to_camel(self.lab['storage_type'], True)
152 self.lab.pop('storage_type', None)
153 if self.lab.get('premium_data_disks') is not None:
154 self.lab['premium_data_disks'] = 'Enabled' if self.lab['premium_data_disks'] else 'Disabled'
155
156 response = None
157
158 self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient,
159 base_url=self._cloud_environment.endpoints.resource_manager,
160 api_version='2018-10-15')
161
162 resource_group = self.get_resource_group(self.resource_group)
163 if self.lab.get('location') is None:
164 self.lab['location'] = resource_group.location
165
166 old_response = self.get_devtestlab()
167
168 if not old_response:
169 self.log("DevTest Lab instance doesn't exist")
170 if self.state == 'absent':
171 self.log("Old instance didn't exist")
172 else:
173 self.to_do = Actions.Create
174 else:
175 self.log("DevTest Lab instance already exists")
176 if self.state == 'absent':
177 self.to_do = Actions.Delete
178 elif self.state == 'present':
179 if self.lab.get('lab_storage_type') is not None and \
180 self.lab.get('lab_storage_type').lower() != old_response.get('lab_storage_type', '').lower():
181 self.to_do = Actions.Update
182 if (self.lab.get('premium_data_disks') is not None and
183 self.lab.get('premium_data_disks').lower() != old_response.get('premium_data_disks').lower()):
184 self.to_do = Actions.Update
185
186 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
187 self.log("Need to Create / Update the DevTest Lab instance")
188 self.results['changed'] = True
189
190 if self.check_mode:
191 return self.results
192
193 response = self.create_update_devtestlab()
194 self.log("Creation / Update done")
195 elif self.to_do == Actions.Delete:
196 self.log("DevTest Lab instance deleted")
197 self.results['changed'] = True
198
199 if self.check_mode:
200 return self.results
201
202 self.delete_devtestlab()
203 # This currently doesnt' work as there is a bug in SDK / Service
204 if isinstance(response, LROPoller):
205 response = self.get_poller_result(response)
206 else:
207 self.log("DevTest Lab instance unchanged")
208 self.results['changed'] = False
209 response = old_response
210
211 if self.state == 'present':
212 self.results.update({
213 'id': response.get('id', None)
214 })
215 return self.results
216
217 def create_update_devtestlab(self):
218 '''
219 Creates or updates DevTest Lab with the specified configuration.
220
221 :return: deserialized DevTest Lab instance state dictionary
222 '''
223 self.log("Creating / Updating the DevTest Lab instance {0}".format(self.name))
224
225 try:
226 response = self.mgmt_client.labs.begin_create_or_update(resource_group_name=self.resource_group,
227 name=self.name,
228 lab=self.lab)
229 if isinstance(response, LROPoller):
230 response = self.get_poller_result(response)
231
232 except Exception as exc:
233 self.log('Error attempting to create the DevTest Lab instance.')
234 self.fail("Error creating the DevTest Lab instance: {0}".format(str(exc)))
235 return response.as_dict()
236
237 def delete_devtestlab(self):
238 '''
239 Deletes specified DevTest Lab instance in the specified subscription and resource group.
240
241 :return: True
242 '''
243 self.log("Deleting the DevTest Lab instance {0}".format(self.name))
244 try:
245 response = self.mgmt_client.labs.begin_delete(resource_group_name=self.resource_group,
246 name=self.name)
247 except Exception as e:
248 self.log('Error attempting to delete the DevTest Lab instance.')
249 self.fail("Error deleting the DevTest Lab instance: {0}".format(str(e)))
250
251 return True
252
253 def get_devtestlab(self):
254 '''
255 Gets the properties of the specified DevTest Lab.
256
257 :return: deserialized DevTest Lab instance state dictionary
258 '''
259 self.log("Checking if the DevTest Lab instance {0} is present".format(self.name))
260 found = False
261 try:
262 response = self.mgmt_client.labs.get(resource_group_name=self.resource_group,
263 name=self.name)
264 found = True
265 self.log("Response : {0}".format(response))
266 self.log("DevTest Lab instance : {0} found".format(response.name))
267 except ResourceNotFoundError as e:
268 self.log('Did not find the DevTest Lab instance.')
269 if found is True:
270 return response.as_dict()
271
272 return False
273
274
275 def main():
276 """Main execution"""
277 AzureRMDevTestLab()
278
279
280 if __name__ == '__main__':
281 main()