Debian Codegraph @

ansible_collections/cisco/intersight/plugins/modules/intersight_organization.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 ANSIBLE_METADATA = {'metadata_version': '1.1',
10 'status': ['preview'],
11 'supported_by': 'community'}
12
13 DOCUMENTATION = r'''
14 ---
15 module: intersight_organization
16 short_description: Organization configuration for Cisco Intersight
17 description:
18 - Manages Organization configuration on Cisco Intersight.
19 - Organizations are account-level resources used to organize and manage Intersight resources.
20 - Supports assigning Resource Groups to define resource scope.
21 - Supports sharing resources with other Organizations via sharing rules.
22 - For more information see L(Cisco Intersight,https://intersight.com/apidocs/organization/Organization/model/).
23 extends_documentation_fragment: intersight
24 options:
25 state:
26 description:
27 - If C(present), will verify the resource is present and will create if needed.
28 - If C(absent), will verify the resource is absent and will delete if needed.
29 type: str
30 choices: [present, absent]
31 default: present
32 name:
33 description:
34 - The name assigned to the Organization.
35 type: str
36 required: true
37 description:
38 description:
39 - The user-defined description for the Organization.
40 type: str
41 aliases: [descr]
42 share_resources:
43 description:
44 - Enable this option to share resources with other Organizations.
45 - When C(true), use O(shared_orgs) to specify which Organizations to share with.
46 - Mutually exclusive with O(resource_groups).
47 type: bool
48 default: false
49 resource_groups:
50 description:
51 - List of Resource Group names to assign to the Organization.
52 - Resource Group names are resolved to their Moids automatically.
53 - Mutually exclusive with O(share_resources) and O(shared_orgs).
54 type: list
55 elements: str
56 shared_orgs:
57 description:
58 - List of Organization names to share resources with.
59 - Only valid when O(share_resources) is C(true).
60 - Organization names are resolved to their Moids automatically.
61 type: list
62 elements: str
63 author:
64 - Ron Gershburg (@rgershbu)
65 '''
66
67 EXAMPLES = r'''
68 - name: Create Organization with Resource Groups
69 cisco.intersight.intersight_organization:
70 api_private_key: "{{ api_private_key }}"
71 api_key_id: "{{ api_key_id }}"
72 name: "my-organization"
73 description: "My organization"
74 resource_groups:
75 - "my-resource-group"
76 state: present
77
78 - name: Create Organization with shared resources
79 cisco.intersight.intersight_organization:
80 api_private_key: "{{ api_private_key }}"
81 api_key_id: "{{ api_key_id }}"
82 name: "shared-org"
83 description: "Organization sharing resources"
84 share_resources: true
85 shared_orgs:
86 - "other-org-1"
87 - "other-org-2"
88 state: present
89
90 - name: Create Organization without Resource Groups
91 cisco.intersight.intersight_organization:
92 api_private_key: "{{ api_private_key }}"
93 api_key_id: "{{ api_key_id }}"
94 name: "simple-org"
95 description: "Simple organization"
96 state: present
97
98 - name: Delete Organization
99 cisco.intersight.intersight_organization:
100 api_private_key: "{{ api_private_key }}"
101 api_key_id: "{{ api_key_id }}"
102 name: "my-organization"
103 state: absent
104 '''
105
106 RETURN = r'''
107 api_response:
108 description: The API response output returned by the specified resource.
109 returned: always
110 type: dict
111 sample:
112 "api_response": {
113 "Name": "my-organization",
114 "ObjectType": "organization.Organization",
115 "Description": "My organization"
116 }
117 '''
118
119 from ansible.module_utils.basic import AnsibleModule
120 from ansible_collections.cisco.intersight.plugins.module_utils.intersight import IntersightModule, intersight_argument_spec
121
122
123 def build_api_body(intersight):
124 """Build the API body for Organization configuration."""
125 params = intersight.module.params
126 if params['state'] == 'present':
127 intersight.api_body = {
128 'Name': params['name'],
129 }
130
131 if not params['share_resources']:
132 if params.get('resource_groups'):
133 rg_refs = []
134 for rg_name in params['resource_groups']:
135 moid = intersight.get_moid_by_name('/resource/Groups', rg_name)
136 if moid is None:
137 intersight.module.fail_json(msg=f"Resource Group '{rg_name}' not found")
138 rg_refs.append({'ObjectType': 'resource.Group', 'Moid': moid})
139 intersight.api_body['ResourceGroups'] = rg_refs
140 else:
141 intersight.api_body['ResourceGroups'] = []
142 else:
143 # Shared mode: clear any previously assigned ResourceGroups
144 intersight.api_body['ResourceGroups'] = []
145
146 if params.get('description') is not None:
147 intersight.api_body['Description'] = params['description']
148
149
150 def get_sharing_rules(intersight, org_moid):
151 """Get current sharing rules for an organization."""
152 intersight.get_resource(
153 resource_path='/iam/SharingRules',
154 query_params={
155 '$filter': f"SharedResource.Moid eq '{org_moid}'",
156 },
157 return_list=True,
158 )
159 return intersight.result['api_response'] if isinstance(intersight.result['api_response'], list) else []
160
161
162 def configure_sharing_rules(intersight, org_moid):
163 """Configure sharing rules for an organization."""
164 params = intersight.module.params
165 shared_org_names = params.get('shared_orgs') or []
166
167 # Get current sharing rules
168 current_rules = get_sharing_rules(intersight, org_moid)
169
170 # Build map of current shared org Moids to rule Moids
171 current_shared = {}
172 for rule in current_rules:
173 shared_with_moid = rule.get('SharedWithResource', {}).get('Moid')
174 if shared_with_moid:
175 current_shared[shared_with_moid] = rule['Moid']
176
177 # Resolve desired shared org names to Moids
178 desired_shared = {}
179 for org_name in shared_org_names:
180 moid = intersight.get_moid_by_name('/organization/Organizations', org_name)
181 if moid is None:
182 intersight.module.fail_json(msg=f"Organization '{org_name}' not found")
183 desired_shared[moid] = org_name
184
185 # Compute diff
186 current_moids = set(current_shared.keys())
187 desired_moids = set(desired_shared.keys())
188 to_add = desired_moids - current_moids
189 to_remove = current_moids - desired_moids
190
191 # Delete removed sharing rules
192 if to_remove:
193 delete_data = [{'moid': current_shared[moid]} for moid in to_remove]
194 intersight.configure_bulk_resources(
195 resource_path='/iam/SharingRules',
196 resources_data=delete_data,
197 http_method='delete',
198 )
199
200 # Create new sharing rules
201 if to_add:
202 create_data = [
203 {
204 'body': {
205 'SharedResource': {
206 'ObjectType': 'organization.Organization',
207 'Moid': org_moid,
208 },
209 'SharedWithResource': {
210 'ObjectType': 'organization.Organization',
211 'Moid': shared_moid,
212 },
213 }
214 }
215 for shared_moid in to_add
216 ]
217 intersight.configure_bulk_resources(
218 resource_path='/iam/SharingRules',
219 resources_data=create_data,
220 http_method='post',
221 )
222
223
224 def cleanup_sharing_rules(intersight, org_moid):
225 """Remove all sharing rules for an organization."""
226 current_rules = get_sharing_rules(intersight, org_moid)
227 if current_rules:
228 delete_data = [{'moid': rule['Moid']} for rule in current_rules]
229 intersight.configure_bulk_resources(
230 resource_path='/iam/SharingRules',
231 resources_data=delete_data,
232 http_method='delete',
233 )
234
235
236 def main():
237 argument_spec = intersight_argument_spec.copy()
238 argument_spec.update(
239 state=dict(type='str', choices=['present', 'absent'], default='present'),
240 name=dict(type='str', required=True),
241 description=dict(type='str', aliases=['descr']),
242 share_resources=dict(type='bool', default=False),
243 resource_groups=dict(type='list', elements='str'),
244 shared_orgs=dict(type='list', elements='str'),
245 )
246
247 module = AnsibleModule(
248 argument_spec,
249 supports_check_mode=True,
250 required_if=[
251 ['share_resources', True, ['shared_orgs']],
252 ],
253 )
254
255 if module.params['share_resources'] and module.params.get('resource_groups'):
256 module.fail_json(msg="parameters are mutually exclusive: share_resources=true and resource_groups")
257
258 intersight = IntersightModule(module)
259 intersight.result['api_response'] = {}
260 intersight.result['trace_id'] = ''
261
262 build_api_body(intersight)
263
264 resource_path = '/organization/Organizations'
265
266 # Clean up sharing rules BEFORE modifying the organization.
267 # The Intersight API rejects ResourceGroup changes on orgs that still
268 # have active sharing rules, so removal must happen first.
269 if not module.check_mode:
270 intersight.get_resource(
271 resource_path=resource_path,
272 query_params={'$filter': f"Name eq '{module.params['name']}'"},
273 )
274 existing_moid = intersight.result['api_response'].get('Moid')
275 if existing_moid and module.params['state'] == 'absent' or not module.params['share_resources']:
276 cleanup_sharing_rules(intersight, existing_moid)
277
278 intersight.configure_secondary_resource(
279 resource_path=resource_path,
280 resource_name=module.params['name'],
281 state=module.params['state'],
282 )
283
284 org_response = intersight.result['api_response']
285 org_moid = org_response.get('Moid')
286
287 if module.params['state'] == 'present' and org_moid:
288 if module.params['share_resources']:
289 configure_sharing_rules(intersight, org_moid)
290
291 intersight.result['api_response'] = org_response
292 module.exit_json(**intersight.result)
293
294
295 if __name__ == '__main__':
296 main()