Debian Codegraph @

ansible_collections/cisco/intersight/plugins/modules/intersight_resource_group_info.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_resource_group_info
16 short_description: Gather information about Resource Groups in Cisco Intersight
17 description:
18 - Gather information about Resource Groups in L(Cisco Intersight,https://intersight.com).
19 - Information can be filtered by O(name).
20 - If no filters are passed, all Resource Groups will be returned.
21 - Each Resource Group is enriched with C(domains) and C(sub_targets) fields
22 parsed from the raw API selectors for easier consumption.
23 - Resource Groups are account-level resources and are not scoped to an organization.
24 extends_documentation_fragment: intersight
25 options:
26 name:
27 description:
28 - The name of the Resource Group to gather information from.
29 type: str
30 author:
31 - Ron Gershburg (@rgershbu)
32 '''
33
34 EXAMPLES = r'''
35 - name: Fetch a specific Resource Group by name
36 cisco.intersight.intersight_resource_group_info:
37 api_private_key: "{{ api_private_key }}"
38 api_key_id: "{{ api_key_id }}"
39 name: "ucs-domains-group"
40
41 - name: Fetch all Resource Groups
42 cisco.intersight.intersight_resource_group_info:
43 api_private_key: "{{ api_private_key }}"
44 api_key_id: "{{ api_key_id }}"
45 '''
46
47 RETURN = r'''
48 api_response:
49 description: The API response output returned by the specified resource, enriched with domains and sub_targets.
50 returned: always
51 type: list
52 elements: dict
53 sample:
54 - Name: "ucs-domains-group"
55 ObjectType: "resource.Group"
56 Moid: "507f1f77bcf86cd799439099"
57 domains:
58 - "ucs-domain-1"
59 - "ucs-domain-2"
60 sub_targets:
61 - serial: "FCH26387BD1"
62 type: "Blade"
63 - serial: "WZP26030TAV"
64 type: "RackUnit"
65 '''
66
67 import re
68
69 from ansible.module_utils.basic import AnsibleModule
70 from ansible_collections.cisco.intersight.plugins.module_utils.intersight import IntersightModule, intersight_argument_spec
71
72
73 def parse_moids_from_selector(selector_str):
74 """Extract Moid values from a DeviceRegistrations selector string."""
75 match = re.search(r"Moid in \(([^)]+)\)", selector_str)
76 if match:
77 return [m.strip("' ") for m in match.group(1).split(',')]
78 return []
79
80
81 def parse_serials_from_selector(selector_str):
82 """Extract Serial values from a Blades or RackUnits selector string."""
83 match = re.search(r"Serial in \(([^)]+)\)", selector_str)
84 if match:
85 return [s.strip("' ") for s in match.group(1).split(',')]
86 return []
87
88
89 def resolve_moids_to_target_names(intersight, moids):
90 """Resolve DeviceRegistration Moids to their Target names."""
91 target_names = []
92 for moid in moids:
93 intersight.get_resource(
94 resource_path='/asset/Targets',
95 query_params={
96 '$filter': f"RegisteredDevice.Moid eq '{moid}'",
97 '$select': 'Name',
98 },
99 )
100 name = intersight.result['api_response'].get('Name')
101 target_names.append(name if name else moid)
102 return target_names
103
104
105 def enrich_resource_groups(intersight, groups):
106 """Add domains and sub_targets fields to each resource group."""
107 for group in groups:
108 domains = []
109 sub_targets = []
110
111 for selector_entry in group.get('Selectors', []):
112 selector_str = selector_entry.get('Selector', '')
113
114 if '/asset/DeviceRegistrations' in selector_str:
115 moids = parse_moids_from_selector(selector_str)
116 names = resolve_moids_to_target_names(intersight, moids)
117 domains.extend(names)
118
119 elif '/compute/Blades' in selector_str:
120 serials = parse_serials_from_selector(selector_str)
121 sub_targets.extend({'serial': s, 'type': 'Blade'} for s in serials)
122
123 elif '/compute/RackUnits' in selector_str:
124 serials = parse_serials_from_selector(selector_str)
125 sub_targets.extend({'serial': s, 'type': 'RackUnit'} for s in serials)
126
127 group['domains'] = domains
128 group['sub_targets'] = sub_targets
129
130 return groups
131
132
133 def main():
134 argument_spec = intersight_argument_spec.copy()
135 argument_spec.update(
136 name=dict(type='str'),
137 )
138
139 module = AnsibleModule(
140 argument_spec,
141 supports_check_mode=True,
142 )
143
144 intersight = IntersightModule(module)
145 intersight.result['api_response'] = {}
146 intersight.result['trace_id'] = ''
147
148 resource_path = '/resource/Groups'
149
150 query_params = intersight.set_query_params()
151
152 intersight.get_resource(
153 resource_path=resource_path,
154 query_params=query_params,
155 return_list=True,
156 )
157
158 groups = intersight.result['api_response']
159 if not isinstance(groups, list):
160 groups = [groups] if groups else []
161
162 enriched = enrich_resource_groups(intersight, groups)
163
164 intersight.result['api_response'] = enriched
165 module.exit_json(**intersight.result)
166
167
168 if __name__ == '__main__':
169 main()