Debian Codegraph @

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