Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2021 Paul Aiton, < @paultaiton >
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_managementgroup_info
14
15 version_added: "1.5.0"
16
17 short_description: Get Azure Management Group facts
18
19 description:
20 - Get facts for a specific Management Group or all Management Groups.
21
22 options:
23 name:
24 description:
25 - Limit results to a specific management group by name.
26 - Mutually exclusive with I(id).
27 aliases:
28 - management_group_name
29 type: str
30 id:
31 description:
32 - Limit results to a specific management group by id.
33 - Mutually exclusive with I(name).
34 type: str
35 flatten:
36 description:
37 - If c(True) then child management_groups and subscriptions will be copied to the root
38 of the management_groups and subscriptions return list respectively.
39 - By default c(False), child elements will only apear in the nested complex.
40 - Option only matters when I(children) is c(True), and will otherwise be silently ignored.
41 type: bool
42 default: False
43 children:
44 description:
45 - If c(False), then only I(name) or I(id) group will be fetched, or only the list of root groups.
46 - If c(True), then the children groups will also be returned.
47 type: bool
48 default: False
49 recurse:
50 description:
51 - By default, c(False), only the direct children are returned if I(children) is c(True).
52 - If c(True), then all descendants of the heirarchy are returned.
53 - Option only matters when I(children) is c(True), and will otherwise be silently ignored.
54 type: bool
55 default: False
56
57 notes:
58 - azure_rm_managementgroup_info - The roles assigned to the principal executing the playbook will determine what is
59 a root management_group. You may also be able to request the details of a parent management group, but unable to
60 fetch that group. It is highly recommended that if I(children) is set c(True) that specific management groups are
61 requested since a list of all groups will require an additional Azure API call for each returned group.
62
63 seealso:
64 - module: azure.azcollection.azure_rm_subscription_info
65 description: module to look up more in depth information on subscriptions; for example tags.
66 - module: azure.azcollection.azure_rm_roleassignment_info
67 description: module to look up RBAC role assignments, which can use management group id as scope.
68
69 extends_documentation_fragment:
70 - azure.azcollection.azure
71
72 author:
73 - Paul Aiton (@paultaiton)
74 '''
75
76 EXAMPLES = '''
77 - name: Get facts for all root management groups for authenticated principal
78 azure_rm_managementgroup_info:
79
80 - name: Get facts for one management group by id with direct children
81 azure_rm_managementgroup_info:
82 id: /providers/Microsoft.Management/managementGroups/contoso-group
83 children: true
84
85 - name: Get facts for one management group by name with all children, flattened into top list
86 azure_rm_managementgroup_info:
87 name: "contoso-group"
88 children: true
89 recurse: true
90 flatten: true
91 '''
92
93 RETURN = '''
94 management_groups:
95 description:
96 - List of Management Group dicts.
97 returned: always
98 type: list
99 contains:
100 display_name:
101 description: Management Group display name.
102 returned: always
103 type: str
104 sample: "My Management Group"
105 id:
106 description: Management Group fully qualified id.
107 returned: always
108 type: str
109 sample: "/providers/Microsoft.Management/managementGroups/group-name"
110 name:
111 description: Management Group display name.
112 returned: always
113 type: str
114 sample: group-name
115 tenant_id:
116 description: Management Group tenant id
117 returned: always
118 type: str
119 sample: "00000000-0000-0000-0000-000000000000"
120 type:
121 description: Management Group type
122 returned: always
123 type: str
124 sample: "/providers/Microsoft.Management/managementGroups"
125 children:
126 description: Child management groups or subscriptions.
127 returned: if I(children) is c(True)
128 type: list
129 sample: Nested list of children. Same as top groups, but without tenant_id.
130 subscriptions:
131 description:
132 - List of subscription objects.
133 returned: if I(children) and I(flatten) are both c(True)
134 type: list
135 contains:
136 display_name:
137 description: subscription display name.
138 returned: always
139 type: str
140 sample: "some-subscription-name"
141 id:
142 description: subscription fully qualified id.
143 returned: always
144 type: str
145 sample: "/subscriptions/00000000-0000-0000-0000-feedc0ffee000000"
146 subscription_id:
147 description: subscription guid.
148 returned: always
149 type: str
150 sample: "00000000-0000-0000-0000-feedc0ffee000000"
151 type:
152 description: Management Group type
153 returned: always
154 type: str
155 sample: "/subscriptions"
156 '''
157
158
159 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
160
161
162 class AzureRMManagementGroupInfo(AzureRMModuleBase):
163 def __init__(self):
164 self.module_arg_spec = dict(
165 children=dict(type='bool', default=False),
166 flatten=dict(type='bool', default=False),
167 id=dict(type='str'),
168 name=dict(type='str', aliases=['management_group_name']),
169 recurse=dict(type='bool', default=False)
170 )
171
172 self.results = dict(
173 changed=False,
174 management_groups=[]
175 )
176
177 self.children = None
178 self.flatten = None
179 self.id = None
180 self.name = None
181 self.recurse = None
182
183 mutually_exclusive = [['name', 'id']]
184
185 super(AzureRMManagementGroupInfo, self).__init__(self.module_arg_spec,
186 supports_check_mode=True,
187 supports_tags=False,
188 mutually_exclusive=mutually_exclusive,
189 facts_module=True)
190
191 def exec_module(self, **kwargs):
192 for key in self.module_arg_spec:
193 setattr(self, key, kwargs[key])
194
195 response = []
196
197 if self.name or self.id:
198 response = [self.get_item()]
199 else:
200 response = self.list_items()
201
202 if self.flatten and self.children:
203 self.results['subscriptions'] = []
204 for group in response:
205 new_groups = []
206 new_subscriptions = []
207 self.results['management_groups'].append(group)
208 new_groups, new_subscriptions = self.flatten_group(group)
209 self.results['management_groups'] += new_groups
210 self.results['subscriptions'] += new_subscriptions
211 else:
212 self.results['management_groups'] = response
213
214 return self.results
215
216 def get_item(self, mg_name=None):
217 if not mg_name:
218 # The parameter to SDK's management_groups.get(group_id) is not correct,
219 # it only works with a bare name value, and not the fqid.
220 if self.id and not self.name:
221 mg_name = self.id.split('/')[-1]
222 else:
223 mg_name = self.name
224
225 expand = 'children' if self.children else None
226 try:
227 response = self.management_groups_client.management_groups.get(group_id=mg_name,
228 expand=expand,
229 recurse=self.recurse)
230 except Exception as e:
231 self.log('No Management group {0} found. msg: {1}'.format(mg_name, e))
232 response = []
233
234 return self.to_dict(response)
235
236 def list_items(self):
237 self.log('List all management groups.')
238
239 results = []
240 response = []
241
242 try:
243 response = self.management_groups_client.management_groups.list()
244 except Exception as e:
245 self.log('No Management groups found.msg: {0}'.format(e))
246 pass # default to response of an empty list
247
248 if self.children:
249 # list method cannot return children, so we must iterate over root management groups to
250 # get each one individually.
251 results = [self.get_item(mg_name=item.name) for item in response]
252 else:
253 results = [self.to_dict(item) for item in response]
254
255 return results
256
257 def to_dict(self, azure_object):
258 if not azure_object:
259 return []
260 if azure_object.type == 'Microsoft.Management/managementGroups':
261 return_dict = dict(
262 display_name=azure_object.display_name,
263 id=azure_object.id,
264 name=azure_object.name,
265 type=azure_object.type
266 )
267
268 # If group has no children, then property will be set to None type.
269 # We want an empty list so that it can be used in loops without issue.
270 if self.children and azure_object.as_dict().get('children'):
271 return_dict['children'] = [self.to_dict(item) for item in azure_object.children]
272 elif self.children:
273 return_dict['children'] = []
274
275 if azure_object.as_dict().get('details', {}).get('parent'):
276 parent_dict = azure_object.as_dict().get('details', {}).get('parent')
277 return_dict['parent'] = dict(
278 display_name=parent_dict.get('display_name'),
279 id=parent_dict.get('id'),
280 name=parent_dict.get('name')
281 )
282
283 elif azure_object.type == '/subscriptions':
284 return_dict = dict(
285 display_name=azure_object.display_name,
286 id=azure_object.id,
287 subscription_id=azure_object.name,
288 type=azure_object.type
289 )
290 else:
291 # In theory if the Azure API is updated to include another child type of management groups,
292 # the code here will prevent an exception. But there should be logic added in an update to take
293 # care of a new child type of management groups.
294 return_dict = dict(
295 state="This is an unknown and unexpected object. "
296 + "You should report this as a bug to the ansible-collection/azcollection "
297 + "project on github. Please include the object type in your issue report, "
298 + "and @ the authors of this module. ",
299 type=azure_object.as_dict().get('type', None)
300 )
301
302 if azure_object.as_dict().get('tenant_id'):
303 return_dict['tenant_id'] = azure_object.tenant_id
304
305 return return_dict
306
307 def flatten_group(self, management_group):
308 management_group_list = []
309 subscription_list = []
310 if management_group.get('children'):
311 for child in management_group.get('children', []):
312 if child.get('type') == '/providers/Microsoft.Management/managementGroups':
313 management_group_list.append(child)
314 new_groups, new_subscriptions = self.flatten_group(child)
315 management_group_list += new_groups
316 subscription_list += new_subscriptions
317 elif child.get('type') == '/subscriptions':
318 subscription_list.append(child)
319 return management_group_list, subscription_list
320
321
322 def main():
323 AzureRMManagementGroupInfo()
324
325
326 if __name__ == '__main__':
327 main()