Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016 Matt Davis, <[email protected]>
4 # Chris Houseknecht, <[email protected]>
5 #
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 ---
14 module: azure_rm_resourcegroup
15 version_added: "0.1.2"
16 short_description: Manage Azure resource groups
17 description:
18 - Create, update and delete a resource group.
19 options:
20 force_delete_nonempty:
21 description:
22 - Remove a resource group and all associated resources.
23 - Use with I(state=absent) to delete a resource group that contains resources.
24 type: bool
25 aliases:
26 - force
27 default: 'no'
28 location:
29 description:
30 - Azure location for the resource group. Required when creating a new resource group.
31 - Cannot be changed once resource group is created.
32 type: str
33 name:
34 description:
35 - Name of the resource group.
36 required: true
37 type: str
38 state:
39 description:
40 - Assert the state of the resource group. Use C(present) to create or update and C(absent) to delete.
41 - When C(absent) a resource group containing resources will not be removed unless the I(force) option is used.
42 default: present
43 type: str
44 choices:
45 - absent
46 - present
47 extends_documentation_fragment:
48 - azure.azcollection.azure
49 - azure.azcollection.azure_tags
50
51 author:
52 - Chris Houseknecht (@chouseknecht)
53 - Matt Davis (@nitzmahone)
54
55 '''
56
57 EXAMPLES = '''
58 - name: Create a resource group
59 azure_rm_resourcegroup:
60 name: myResourceGroup
61 location: westus
62 tags:
63 testing: testing
64 delete: never
65
66 - name: Delete a resource group
67 azure_rm_resourcegroup:
68 name: myResourceGroup
69 state: absent
70
71 - name: Delete a resource group including resources it contains
72 azure_rm_resourcegroup:
73 name: myResourceGroup
74 force_delete_nonempty: true
75 state: absent
76 '''
77 RETURN = '''
78 contains_resources:
79 description:
80 - Whether or not the resource group contains associated resources.
81 returned: always
82 type: bool
83 sample: True
84 state:
85 description:
86 - Current state of the resource group.
87 returned: always
88 type: complex
89 contains:
90 id:
91 description:
92 - Resource ID.
93 returned: always
94 type: str
95 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup"
96 location:
97 description:
98 - Azure location for the resource group.
99 returned: always
100 type: str
101 sample: westus
102 name:
103 description:
104 - The resource group name.
105 returned: always
106 type: str
107 sample: Testing
108 provisioning_state:
109 description:
110 - Provisioning state of the resource group.
111 returned: always
112 type: str
113 sample: Succeeded
114 tags:
115 description:
116 - The resource group's tags.
117 returned: always
118 type: dict
119 sample: {
120 "delete": "on-exit",
121 "testing": "no"
122 }
123 '''
124
125 try:
126 from azure.core.exceptions import ResourceNotFoundError
127 except ImportError:
128 pass
129
130 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase, normalize_location_name
131
132
133 def resource_group_to_dict(rg):
134 return dict(
135 id=rg.id,
136 name=rg.name,
137 location=rg.location,
138 tags=rg.tags,
139 provisioning_state=rg.properties.provisioning_state
140 )
141
142
143 class AzureRMResourceGroup(AzureRMModuleBase):
144
145 def __init__(self):
146 self.module_arg_spec = dict(
147 name=dict(type='str', required=True),
148 state=dict(type='str', default='present', choices=['present', 'absent']),
149 location=dict(type='str'),
150 force_delete_nonempty=dict(type='bool', default=False, aliases=['force'])
151 )
152
153 self.name = None
154 self.state = None
155 self.location = None
156 self.tags = None
157 self.force_delete_nonempty = None
158
159 self.results = dict(
160 changed=False,
161 contains_resources=False,
162 state=dict(),
163 )
164
165 super(AzureRMResourceGroup, self).__init__(self.module_arg_spec,
166 supports_check_mode=True,
167 supports_tags=True)
168
169 def exec_module(self, **kwargs):
170
171 for key in list(self.module_arg_spec.keys()) + ['tags']:
172 setattr(self, key, kwargs[key])
173
174 results = dict()
175 changed = False
176 rg = None
177 contains_resources = False
178
179 try:
180 self.log('Fetching resource group {0}'.format(self.name))
181 rg = self.rm_client.resource_groups.get(self.name)
182 self.check_provisioning_state(rg, self.state)
183 contains_resources = self.resources_exist()
184
185 results = resource_group_to_dict(rg)
186 if self.state == 'absent':
187 self.log("CHANGED: resource group {0} exists but requested state is 'absent'".format(self.name))
188 changed = True
189 elif self.state == 'present':
190 update_tags, results['tags'] = self.update_tags(results['tags'])
191 self.log("update tags %s" % update_tags)
192 self.log("new tags: %s" % str(results['tags']))
193 if update_tags:
194 changed = True
195
196 if self.location and normalize_location_name(self.location) != results['location']:
197 self.fail("Resource group '{0}' already exists in location '{1}' and cannot be "
198 "moved.".format(self.name, results['location']))
199 except ResourceNotFoundError:
200 self.log('Resource group {0} does not exist'.format(self.name))
201 if self.state == 'present':
202 self.log("CHANGED: resource group {0} does not exist but requested state is "
203 "'present'".format(self.name))
204 changed = True
205
206 self.results['changed'] = changed
207 self.results['state'] = results
208 self.results['contains_resources'] = contains_resources
209
210 if self.check_mode:
211 return self.results
212
213 if changed:
214 if self.state == 'present':
215 if not rg:
216 # Create resource group
217 self.log("Creating resource group {0}".format(self.name))
218 if not self.location:
219 self.fail("Parameter error: location is required when creating a resource group.")
220 if self.name_exists():
221 self.fail("Error: a resource group with the name {0} already exists in your subscription."
222 .format(self.name))
223 params = self.rm_models.ResourceGroup(
224 location=self.location,
225 tags=self.tags
226 )
227 else:
228 # Update resource group
229 params = self.rm_models.ResourceGroup(
230 location=results['location'],
231 tags=results['tags']
232 )
233 self.results['state'] = self.create_or_update_resource_group(params)
234 elif self.state == 'absent':
235 if contains_resources and not self.force_delete_nonempty:
236 self.fail("Error removing resource group {0}. Resources exist within the group. "
237 "Use `force_delete_nonempty` to force delete. "
238 "To list resources under {0}, use `azure_rm_resourcegroup_facts` module with `list_resources` option.".format(self.name))
239 self.delete_resource_group()
240
241 return self.results
242
243 def create_or_update_resource_group(self, params):
244 try:
245 result = self.rm_client.resource_groups.create_or_update(self.name, params)
246 except Exception as exc:
247 self.fail("Error creating or updating resource group {0} - {1}".format(self.name, str(exc)))
248 return resource_group_to_dict(result)
249
250 def delete_resource_group(self):
251 try:
252 poller = self.rm_client.resource_groups.begin_delete(self.name)
253 self.get_poller_result(poller)
254 except Exception as exc:
255 self.fail("Error delete resource group {0} - {1}".format(self.name, str(exc)))
256
257 # The delete operation doesn't return anything.
258 # If we got here, assume all is good
259 self.results['state']['status'] = 'Deleted'
260 return True
261
262 def resources_exist(self):
263 found = False
264 try:
265 response = self.rm_client.resources.list_by_resource_group(self.name)
266 except AttributeError:
267 response = self.rm_client.resource_groups.list_resources(self.name)
268 except Exception as exc:
269 self.fail("Error checking for resource existence in {0} - {1}".format(self.name, str(exc)))
270
271 for item in response:
272 found = True
273 break
274 return found
275
276 def name_exists(self):
277 try:
278 exists = self.rm_client.resource_groups.check_existence(self.name)
279 except Exception as exc:
280 self.fail("Error checking for existence of name {0} - {1}".format(self.name, str(exc)))
281 return exists
282
283
284 def main():
285 AzureRMResourceGroup()
286
287
288 if __name__ == '__main__':
289 main()