Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_powerstate.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2019-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r'''
17 ---
18 module: ome_powerstate
19 short_description: Performs the power management operations on OpenManage Enterprise
20 version_added: "2.1.0"
21 description: This module performs the supported power management operations on OpenManage Enterprise.
22 extends_documentation_fragment:
23 - dellemc.openmanage.ome_auth_options
24 options:
25 power_state:
26 description: Desired end power state.
27 type: str
28 required: true
29 choices: ['on', 'off', 'coldboot', 'warmboot', 'shutdown']
30 device_service_tag:
31 description:
32 - Targeted device service tag.
33 - I(device_service_tag) is mutually exclusive with I(device_id).
34 type: str
35 device_id:
36 description:
37 - Targeted device id.
38 - I(device_id) is mutually exclusive with I(device_service_tag).
39 type: int
40 requirements:
41 - "python >= 3.9.6"
42 author: "Felix Stephen (@felixs88)"
43 notes:
44 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
45 - This module supports C(check_mode).
46 '''
47
48 EXAMPLES = r'''
49 ---
50 - name: Power state operation based on device id
51 dellemc.openmanage.ome_powerstate:
52 hostname: "192.168.0.1"
53 username: "username"
54 password: "password"
55 ca_path: "/path/to/ca_cert.pem"
56 device_id: 11111
57 power_state: "off"
58
59 - name: Power state operation based on device service tag
60 dellemc.openmanage.ome_powerstate:
61 hostname: "192.168.0.1"
62 username: "username"
63 password: "password"
64 ca_path: "/path/to/ca_cert.pem"
65 device_service_tag: "KLBR111"
66 power_state: "on"
67
68 - name: Power state operation based on list of device ids
69 dellemc.openmanage.ome_powerstate:
70 hostname: "192.168.0.1"
71 username: "username"
72 password: "password"
73 ca_path: "/path/to/ca_cert.pem"
74 device_id: "{{ item.device_id }}"
75 power_state: "{{ item.state }}"
76 with_items:
77 - { "device_id": 11111, "state": "on" }
78 - { "device_id": 22222, "state": "off" }
79
80 - name: Power state operation based on list of device service tags
81 dellemc.openmanage.ome_powerstate:
82 hostname: "192.168.0.1"
83 username: "username"
84 password: "password"
85 ca_path: "/path/to/ca_cert.pem"
86 device_service_tag: "{{ item.service_tag }}"
87 power_state: "{{ item.state }}"
88 with_items:
89 - { "service_tag": "KLBR111", "state": "on" }
90 - { "service_tag": "KLBR222", "state": "off" }
91 '''
92
93 RETURN = r'''
94 ---
95 msg:
96 type: str
97 description: "Overall power state operation job status."
98 returned: always
99 sample: "Power State operation job submitted successfully."
100 job_status:
101 type: dict
102 description: "Power state operation job and progress details from the OME."
103 returned: success
104 sample: {
105 "Builtin": false,
106 "CreatedBy": "user",
107 "Editable": true,
108 "EndTime": null,
109 "Id": 11111,
110 "JobDescription": "DeviceAction_Task",
111 "JobName": "DeviceAction_Task_PowerState",
112 "JobStatus": {
113 "Id": 1111,
114 "Name": "New"
115 },
116 "JobType": {
117 "Id": 1,
118 "Internal": false,
119 "Name": "DeviceAction_Task"
120 },
121 "LastRun": "2019-04-01 06:39:02.69",
122 "LastRunStatus": {
123 "Id": 1112,
124 "Name": "Running"
125 },
126 "NextRun": null,
127 "Params": [
128 {
129 "JobId": 11111,
130 "Key": "powerState",
131 "Value": "2"
132 },
133 {
134 "JobId": 11111,
135 "Key": "operationName",
136 "Value": "POWER_CONTROL"
137 }
138 ],
139 "Schedule": "",
140 "StartTime": null,
141 "State": "Enabled",
142 "Targets": [
143 {
144 "Data": "",
145 "Id": 11112,
146 "JobId": 11111,
147 "TargetType": {
148 "Id": 1000,
149 "Name": "DEVICE"
150 }
151 }
152 ],
153 "UpdatedBy": null,
154 "Visible": true
155 }
156 '''
157
158 import json
159 from ssl import SSLError
160 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
161 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
162 from ansible.module_utils.urls import ConnectionError, SSLValidationError
163
164 VALID_OPERATION = {"on": 2, "off": 12, "coldboot": 5, "warmboot": 10, "shutdown": 8}
165 POWER_STATE_MAP = {"on": 17, "off": 18, "poweringon": 20, "poweringoff": 21}
166 NOT_APPLICABLE_OPTIONS = ["coldboot", "warmboot", "shutdown"]
167
168
169 def spawn_update_job(rest_obj, payload):
170 """Spawns an update job and tracks it to completion."""
171 job_uri, job_details = "JobService/Jobs", {}
172 job_resp = rest_obj.invoke_request("POST", job_uri, data=payload)
173 if job_resp.status_code == 201:
174 job_details = job_resp.json_data
175 return job_details
176
177
178 def build_power_state_payload(device_id, device_type, valid_option):
179 """Build the payload for requested device."""
180 payload = {
181 "Id": 0,
182 "JobName": "DeviceAction_Task_PowerState",
183 "JobDescription": "DeviceAction_Task",
184 "Schedule": "startnow",
185 "State": "Enabled",
186 "JobType": {"Id": 3, "Name": "DeviceAction_Task"},
187 "Params": [{"Key": "operationName", "Value": "POWER_CONTROL"},
188 {"Key": "powerState", "Value": str(valid_option)}],
189 "Targets": [{"Id": int(device_id), "Data": "",
190 "TargetType": {"Id": device_type, "Name": "DEVICE"}}],
191 }
192 return payload
193
194
195 def get_device_state(module, resp, device_id):
196 """Get the current state and device type from response."""
197 current_state, device_type, invalid_device = None, None, True
198 for device in resp['report_list']:
199 if device['Id'] == int(device_id):
200 current_state = device.get('PowerState', None)
201 device_type = device['Type']
202 invalid_device = False
203 break
204 if invalid_device:
205 module.fail_json(msg="Unable to complete the operation because the entered target"
206 " device id '{0}' is invalid.".format(device_id))
207 if device_type not in (1000, 2000):
208 module.fail_json(msg="Unable to complete the operation because power"
209 " state supports device type 1000 and 2000.")
210 return current_state, device_type
211
212
213 def get_device_resource(module, rest_obj):
214 """Getting the device id filtered from the device inventory."""
215 power_state = module.params['power_state']
216 device_id = module.params['device_id']
217 service_tag = module.params['device_service_tag']
218 resp_data = rest_obj.get_all_report_details("DeviceService/Devices")
219 if resp_data['report_list'] and service_tag is not None:
220 device_resp = dict([(device.get('DeviceServiceTag'), str(device.get('Id'))) for device in resp_data['report_list']])
221 if service_tag in device_resp:
222 device_id = device_resp[service_tag]
223 else:
224 module.fail_json(msg="Unable to complete the operation because the entered target"
225 " device service tag '{0}' is invalid.".format(service_tag))
226 current_state, device_type = get_device_state(module, resp_data, device_id)
227
228 # For check mode changes.
229 valid_option, valid_operation = VALID_OPERATION[power_state], False
230 if power_state in NOT_APPLICABLE_OPTIONS and current_state != POWER_STATE_MAP["on"]:
231 valid_operation = True
232 elif (valid_option == current_state) or \
233 (power_state == "on" and current_state in (POWER_STATE_MAP["on"], POWER_STATE_MAP['poweringon'])) or \
234 (power_state in ("off", "shutdown") and
235 current_state in (POWER_STATE_MAP["off"], POWER_STATE_MAP['poweringoff'])):
236 valid_operation = True
237
238 if module.check_mode and valid_operation:
239 module.exit_json(msg="No changes found to commit.")
240 elif module.check_mode and not valid_operation:
241 module.exit_json(msg="Changes found to commit.", changed=True)
242 payload = build_power_state_payload(device_id, device_type, valid_option)
243 return payload
244
245
246 def main():
247 specs = {
248 "power_state": {"required": True, "type": "str",
249 "choices": ["on", "off", "coldboot", "warmboot", "shutdown"]},
250 "device_service_tag": {"required": False, "type": "str"},
251 "device_id": {"required": False, "type": "int"},
252 }
253
254 module = OmeAnsibleModule(
255 argument_spec=specs,
256 required_one_of=[["device_service_tag", "device_id"]],
257 mutually_exclusive=[["device_service_tag", "device_id"]],
258 supports_check_mode=True
259 )
260 try:
261 if module.params['device_id'] is None and module.params['device_service_tag'] is None:
262 module.fail_json(msg="device_id and device_service_tag attributes should not be None.")
263 job_status = {}
264 with RestOME(module.params, req_session=True) as rest_obj:
265 payload = get_device_resource(module, rest_obj)
266 job_status = spawn_update_job(rest_obj, payload)
267 except HTTPError as err:
268 module.fail_json(msg=str(err), job_status=json.load(err))
269 except (URLError, SSLValidationError, ConnectionError, TypeError, ValueError, SSLError, OSError) as err:
270 module.fail_json(msg=str(err))
271 module.exit_json(msg="Power State operation job submitted successfully.",
272 job_status=job_status, changed=True)
273
274
275 if __name__ == '__main__':
276 main()