Debian Codegraph @

ansible_collections/cisco/intersight/plugins/modules/intersight_target_claim.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_target_claim
16 short_description: Target claim configuraiton for Cisco Intersight
17 description:
18 - Target claim configuraiton for Cisco Intersight
19 - Used to claim or unclaim a Target from Cisco Intersight
20 - For more information see L(Cisco Intersight,https://intersight.com/apidocs).
21 extends_documentation_fragment: intersight
22 options:
23 claim_code:
24 description:
25 - Claim code required for registering a new Target
26 - Required if I(state=present)
27 type: str
28 required: false
29 device_id:
30 description:
31 - Device id (serial number) of target
32 - Targets containing multiple Target ids (e.g. IMM) can be formatted as <target1_id>&<target2_id>
33 type: str
34 required: true
35 state:
36 description:
37 - If C(present), will verify the resource is present and will create if needed.
38 - If C(absent), will verify the resource is absent and will delete if needed.
39 type: str
40 choices: [present, absent]
41 default: present
42 author:
43 - Brandon Beck (@techBeck03)
44 - CiscoUcs (@CiscoUcs)
45 '''
46
47 EXAMPLES = r'''
48 - name: Claim new Target
49 cisco.intersight.intersight_target_claim:
50 device_id: "{{ device_id }}"
51 claim_code: "{{ claim_code }}"
52 state: present
53
54 - name: Delete a Target (unclaim)
55 cisco.intersight.intersight_target_claim:
56 device_id: "{{ device_id }}"
57 state: absent
58 '''
59
60 RETURN = r'''
61 api_response:
62 description: The API response output returned by the specified resource.
63 returned: always
64 type: dict
65 sample:
66 "api_response": {
67 "Account": {
68 "ClassId": "mo.MoRef",
69 "Moid": "8675309",
70 "ObjectType": "iam.Account",
71 "link": "https://www.intersight.com/api/v1/iam/Accounts/8675309"
72 },
73 "AccountMoid": "8675309",
74 "Ancestors": null,
75 "ClassId": "asset.DeviceClaim",
76 "CreateTime": "2021-05-10T17:32:13.522665238Z",
77 "Device": {
78 "ClassId": "mo.MoRef",
79 "Moid": "9035768",
80 "ObjectType": "asset.DeviceRegistration",
81 "link": "https://www.intersight.com/api/v1/asset/DeviceRegistrations/9035768"
82 },
83 "DisplayNames": {
84 "short": [
85 "FDO241604EM&FDO24161700"
86 ]
87 },
88 "DomainGroupMoid": "5b4e48a96a636d6d346cd1c5",
89 "ModTime": "2021-05-10T17:32:13.522665238Z",
90 "Moid": "8675309",
91 "ObjectType": "asset.DeviceClaim",
92 "Owners": [
93 "90357688675309"
94 ],
95 "PermissionResources": null,
96 "SecurityToken": "A95486674376E",
97 "SerialNumber": "FDO86753091&FDO86753092",
98 "SharedScope": "",
99 "Tags": [],
100 "trace_id": "NB3e883980a98adace8f7b9c2409cced1a"
101 }
102 '''
103
104 from ansible_collections.cisco.intersight.plugins.module_utils.intersight import IntersightModule, intersight_argument_spec
105 from ansible.module_utils.basic import AnsibleModule
106
107
108 def main():
109 argument_spec = intersight_argument_spec.copy()
110 argument_spec.update(
111 claim_code=dict(type='str'),
112 device_id=dict(type='str', required=True),
113 state=dict(type='str', choices=['absent', 'present'], default='present'),
114 )
115
116 module = AnsibleModule(
117 argument_spec,
118 supports_check_mode=True,
119 required_if=[
120 ('state', 'present', (['claim_code']), False),
121 ]
122 )
123
124 intersight = IntersightModule(module)
125 intersight.result['api_response'] = {}
126 intersight.result['trace_id'] = ''
127
128 # Check if device already exists in target list
129 target_ids = module.params['device_id'].split('&')
130 target_filter = ''
131 for idx, target_id in enumerate(target_ids):
132 if idx == 0:
133 target_filter += f"contains(TargetId,'{target_id}')"
134 else:
135 target_filter += f" or contains(TargetId,'{target_id}')"
136 intersight.get_resource(
137 resource_path='/asset/Targets',
138 query_params={
139 "$select": "TargetId,RegisteredDevice",
140 "$filter": target_filter,
141 "$expand": "RegisteredDevice($select=DeviceClaim)"
142 },
143 return_list=False,
144 )
145
146 if module.params['state'] == 'present':
147 # Send claim request if device id not already claimed
148 if not intersight.result['api_response']:
149 intersight.configure_resource(
150 moid=None,
151 resource_path='/asset/DeviceClaims',
152 body=dict(
153 SecurityToken=module.params['claim_code'],
154 SerialNumber=module.params['device_id']
155 ),
156 query_params=None,
157 update_method='post'
158 )
159
160 elif module.params['state'] == 'absent':
161 # Check if target exists
162 if intersight.result['api_response'].get('Moid'):
163 intersight.delete_resource(
164 moid=intersight.result['api_response'].get('RegisteredDevice').get('DeviceClaim').get('Moid'),
165 resource_path='/asset/DeviceClaims',
166 )
167
168 module.exit_json(**intersight.result)
169
170
171 if __name__ == '__main__':
172 main()