Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2020 Paul Aiton, (@paultaiton)
4 # Copyright (c) 2018 Yunge Zhu, (@yungezz)
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_roleassignment
15 version_added: "0.1.2"
16 short_description: Manage Azure Role Assignment
17 description:
18 - Create and delete instance of Azure Role Assignment.
19
20 options:
21 assignee_object_id:
22 description:
23 - The object id of assignee. This maps to the ID inside the Active Directory.
24 - It can point to a user, service principal or security group.
25 - Required when creating role assignment.
26 type: str
27 aliases:
28 - assignee
29 id:
30 description:
31 - Fully qualified id of assignment to delete or create.
32 - Mutually Exclusive with I(scope) and I(name)
33 type: str
34 name:
35 description:
36 - Unique name of role assignment.
37 - The role assignment name must be a GUID, sample as "3ce0cbb0-58c4-4e6d-a16d-99d86a78b3ca".
38 - Mutually Exclusive with I(id)
39 type: str
40 role_definition_id:
41 description:
42 - The role definition id used in the role assignment.
43 - Required when creating role assignment.
44 type: str
45 scope:
46 description:
47 - The scope of the role assignment to create.
48 - For example, use /subscriptions/{subscription-id}/ for subscription.
49 - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name} for resource group.
50 - /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name} for resource.
51 - Mutually Exclusive with I(id)
52 type: str
53 state:
54 description:
55 - Assert the state of the role assignment.
56 - Use C(present) to create or update a role assignment and C(absent) to delete it.
57 - If C(present), then I(role_definition_id) and I(assignee_object_id) are both required
58 default: present
59 type: str
60 choices:
61 - absent
62 - present
63
64 extends_documentation_fragment:
65 - azure.azcollection.azure
66
67 author:
68 - Yunge Zhu(@yungezz)
69 - Paul Aiton(@paultaiton)
70
71 '''
72
73 EXAMPLES = '''
74 - name: Create a role assignment
75 azure_rm_roleassignment:
76 scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
77 assignee_object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
78 role_definition_id:
79 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleDefinitions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
80
81 - name: Create a role assignment
82 azure_rm_roleassignment:
83 name: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
84 scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
85 assignee_object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
86 role_definition_id:
87 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleDefinitions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
88
89 - name: Delete a role assignment
90 azure_rm_roleassignment:
91 name: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
92 scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
93 state: absent
94
95 - name: Delete a role assignment
96 azure_rm_roleassignment:
97 id: /subscriptions/xxx-sub-guid-xxx/resourceGroups/rgname/providers/Microsoft.Authorization/roleAssignments/xxx-assign-guid-xxx"
98 state: absent
99
100 - name: Delete a role assignment
101 azure_rm_roleassignment:
102 scope: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
103 assignee_object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
104 role_definition_id:
105 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleDefinitions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
106 state: absent
107 '''
108
109 RETURN = '''
110 id:
111 description:
112 - Id of current role assignment.
113 returned: always
114 type: str
115 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleAssignments/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
116 name:
117 description:
118 - Name of role assignment.
119 type: str
120 returned: always
121 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
122 type:
123 description:
124 - Type of role assignment.
125 type: str
126 returned: always
127 sample: Microsoft.Authorization/roleAssignments
128 assignee_object_id:
129 description:
130 - Principal Id of the role assignee.
131 type: str
132 returned: always
133 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
134 principal_type:
135 description:
136 - Principal type of the role assigned to.
137 type: str
138 returned: always
139 sample: ServicePrincipal
140 role_definition_id:
141 description:
142 - Role definition id that was assigned to principal_id.
143 type: str
144 returned: always
145 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleDefinitions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
146 scope:
147 description:
148 - The role assignment scope.
149 type: str
150 returned: always
151 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
152 '''
153
154 try:
155 import uuid
156 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
157
158 except ImportError:
159 # This is handled in azure_rm_common
160 pass
161
162
163 class AzureRMRoleAssignment(AzureRMModuleBase):
164 """Configuration class for an Azure RM Role Assignment"""
165
166 def __init__(self):
167 self.module_arg_spec = dict(
168 assignee_object_id=dict(type='str', aliases=['assignee']),
169 id=dict(type='str'),
170 name=dict(type='str'),
171 role_definition_id=dict(type='str'),
172 scope=dict(type='str'),
173 state=dict(type='str', default='present', choices=['present', 'absent'])
174 )
175
176 self.assignee_object_id = None
177 self.id = None
178 self.name = None
179 self.role_definition_id = None
180 self.scope = None
181 self.state = None
182
183 self.results = dict(
184 changed=False,
185 id=None,
186 )
187
188 mutually_exclusive = [['name', 'id'], ['scope', 'id']]
189 required_one_of = [['scope', 'id']]
190 required_if = [
191 ["state", "present", ["assignee_object_id", "role_definition_id"]]
192 ]
193
194 super(AzureRMRoleAssignment, self).__init__(derived_arg_spec=self.module_arg_spec,
195 supports_check_mode=True,
196 supports_tags=False,
197 required_one_of=required_one_of,
198 required_if=required_if,
199 mutually_exclusive=mutually_exclusive)
200
201 def exec_module(self, **kwargs):
202 """Main module execution method"""
203
204 for key in self.module_arg_spec:
205 setattr(self, key, kwargs[key])
206
207 if self.name and not self.scope:
208 self.fail("Parameter Error: setting name requires a scope to also be set.")
209
210 existing_assignment = None
211 response = None
212
213 existing_assignment = self.get_roleassignment()
214
215 if existing_assignment:
216 self.set_results(existing_assignment)
217
218 if self.state == 'present':
219 # check if the role assignment exists
220 if not existing_assignment:
221 self.log("Role assignment doesn't exist in this scope")
222
223 self.results['changed'] = True
224
225 if self.check_mode:
226 return self.results
227 response = self.create_roleassignment()
228 self.set_results(response)
229
230 else:
231 self.log("Role assignment already exists, not updatable")
232 self.log('Result: {0}'.format(existing_assignment))
233
234 elif self.state == 'absent':
235 if existing_assignment:
236 self.log("Delete role assignment")
237 self.results['changed'] = True
238
239 if self.check_mode:
240 return self.results
241
242 self.delete_roleassignment(existing_assignment.get('id'))
243
244 self.log('role assignment deleted')
245
246 else:
247 # If assignment doesn't exist, that's the desired state.
248 self.log("role assignment {0} does not exist.".format(self.name))
249
250 return self.results
251
252 def create_roleassignment(self):
253 '''
254 Creates role assignment.
255
256 :return: deserialized role assignment
257 '''
258 self.log("Creating role assignment {0}".format(self.name))
259
260 response = None
261 try:
262 # pylint: disable=missing-kwoa
263 parameters = self.authorization_models.RoleAssignmentCreateParameters(role_definition_id=self.role_definition_id,
264 principal_id=self.assignee_object_id)
265 if self.id:
266 response = self.authorization_client.role_assignments.create_by_id(role_id=self.id,
267 parameters=parameters)
268 elif self.scope:
269 if not self.name:
270 self.name = str(uuid.uuid4())
271 response = self.authorization_client.role_assignments.create(scope=self.scope,
272 role_assignment_name=self.name,
273 parameters=parameters)
274
275 except Exception as exc:
276 self.log('Error attempting to create role assignment.')
277 self.fail("Error creating role assignment: {0}".format(str(exc)))
278 return self.roleassignment_to_dict(response)
279
280 def delete_roleassignment(self, assignment_id):
281 '''
282 Deletes specified role assignment.
283
284 :return: True
285 '''
286 self.log("Deleting the role assignment {0}".format(self.name))
287 try:
288 response = self.authorization_client.role_assignments.delete_by_id(role_id=assignment_id)
289 except Exception as e:
290 self.log('Error attempting to delete the role assignment.')
291 self.fail("Error deleting the role assignment: {0}".format(str(e)))
292
293 return True
294
295 def get_roleassignment(self):
296 '''
297 Gets the properties of the specified role assignment.
298
299 :return: deserialized role assignment dictionary
300 '''
301 self.log("Checking if the role assignment {0} is present".format(self.name))
302
303 role_assignment = None
304
305 if self.id:
306 try:
307 response = self.authorization_client.role_assignments.get_by_id(role_id=self.id)
308 role_assignment = self.roleassignment_to_dict(response)
309 if role_assignment and self.assignee_object_id and role_assignment.get('assignee_object_id') != self.assignee_object_id:
310 self.fail('State Mismatch Error: The assignment ID exists, but does not match the provided assignee.')
311
312 if role_assignment and self.role_definition_id and (role_assignment.get('role_definition_id').split('/')[-1].lower()
313 != self.role_definition_id.split('/')[-1].lower()):
314 self.fail('State Mismatch Error: The assignment ID exists, but does not match the provided role.')
315
316 except Exception as ex:
317 self.log("Didn't find role assignments id {0}".format(self.id))
318
319 elif self.name and self.scope:
320 try:
321 response = self.authorization_client.role_assignments.get(scope=self.scope, role_assignment_name=self.name)
322 role_assignment = self.roleassignment_to_dict(response)
323 if role_assignment and self.assignee_object_id and role_assignment.get('assignee_object_id') != self.assignee_object_id:
324 self.fail('State Mismatch Error: The assignment name exists, but does not match the provided assignee.')
325
326 if role_assignment and self.role_definition_id and (role_assignment.get('role_definition_id').split('/')[-1].lower()
327 != self.role_definition_id.split('/')[-1].lower()):
328 self.fail('State Mismatch Error: The assignment name exists, but does not match the provided role.')
329
330 except Exception as ex:
331 self.log("Didn't find role assignment by name {0} at scope {1}".format(self.name, self.scope))
332
333 else:
334 try:
335 if self.scope and self.assignee_object_id and self.role_definition_id:
336 response = list(self.authorization_client.role_assignments.list())
337 response = [self.roleassignment_to_dict(role_assignment) for role_assignment in response]
338 response = [role_assignment for role_assignment in response if role_assignment.get('scope').lower() == self.scope.rstrip("/").lower()]
339 response = [role_assignment for role_assignment in response if (role_assignment.get('assignee_object_id').lower()
340 == self.assignee_object_id.lower())]
341 response = [role_assignment for role_assignment in response if (role_assignment.get('role_definition_id').split('/')[-1].lower()
342 == self.role_definition_id.split('/')[-1].lower())]
343 else:
344 self.fail('If id or name are not supplied, then assignee_object_id and role_definition_id are required.')
345 if response:
346 role_assignment = response[0]
347 except Exception as ex:
348 self.log("Didn't find role assignments for subscription {0}".format(self.subscription_id))
349
350 return role_assignment
351
352 def set_results(self, assignment):
353 self.results['id'] = assignment.get('id')
354 self.results['name'] = assignment.get('name')
355 self.results['type'] = assignment.get('type')
356 self.results['assignee_object_id'] = assignment.get('assignee_object_id')
357 self.results['principal_type'] = assignment.get('principal_type')
358 self.results['role_definition_id'] = assignment.get('role_definition_id')
359 self.results['scope'] = assignment.get('scope')
360
361 def roleassignment_to_dict(self, assignment):
362 return dict(
363 assignee_object_id=assignment.principal_id,
364 id=assignment.id,
365 name=assignment.name,
366 principal_id=assignment.principal_id,
367 principal_type=assignment.principal_type,
368 role_definition_id=assignment.role_definition_id,
369 scope=assignment.scope,
370 type=assignment.type
371 )
372
373
374 def main():
375 """Main execution"""
376 AzureRMRoleAssignment()
377
378
379 if __name__ == '__main__':
380 main()