Debian Codegraph @

ansible_collections/community/general/plugins/modules/ipmi_power.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: ipmi_power
11 short_description: Power management for machine
12 description:
13 - Use this module for power management.
14 extends_documentation_fragment:
15 - community.general._attributes
16 attributes:
17 check_mode:
18 support: full
19 diff_mode:
20 support: none
21 options:
22 name:
23 description:
24 - Hostname or IP address of the BMC.
25 required: true
26 type: str
27 port:
28 description:
29 - Remote RMCP port.
30 default: 623
31 type: int
32 user:
33 description:
34 - Username to use to connect to the BMC.
35 required: true
36 type: str
37 password:
38 description:
39 - Password to connect to the BMC.
40 required: true
41 type: str
42 key:
43 description:
44 - Encryption key to connect to the BMC in hex format.
45 type: str
46 version_added: 4.1.0
47 state:
48 description:
49 - Whether to ensure that the machine in desired state.
50 - 'The choices for state are:'
51 - V(on) -- Request system turn on.
52 - V(off) -- Request system turn off without waiting for OS to shutdown.
53 - V(shutdown) -- Have system request OS proper shutdown.
54 - V(reset) -- Request system reset without waiting for OS.
55 - V(boot) -- If system is off, then V(on), else V(reset).
56 - Either this option or O(machine) is required.
57 choices: ['on', 'off', shutdown, reset, boot]
58 type: str
59 timeout:
60 description:
61 - Maximum number of seconds before interrupt request.
62 default: 300
63 type: int
64 machine:
65 description:
66 - Provide a list of the remote target address for the bridge IPMI request, and the power status.
67 - Either this option or O(state) is required.
68 type: list
69 elements: dict
70 version_added: 4.3.0
71 suboptions:
72 targetAddress:
73 description:
74 - Remote target address for the bridge IPMI request.
75 type: int
76 required: true
77 state:
78 description:
79 - Whether to ensure that the machine specified by O(machine[].targetAddress) in desired state.
80 - If this option is not set, the power state is set by O(state).
81 - If both this option and O(state) are set, this option takes precedence over O(state).
82 choices: ['on', 'off', shutdown, reset, boot]
83 type: str
84
85 requirements:
86 - pyghmi
87 author: "Bulat Gaifullin (@bgaifullin) <[email protected]>"
88 """
89
90 RETURN = r"""
91 powerstate:
92 description: The current power state of the machine.
93 returned: success and O(machine) is not provided
94 type: str
95 sample: 'on'
96 status:
97 description: The current power state of the machine when the machine option is set.
98 returned: success and O(machine) is provided
99 type: list
100 elements: dict
101 version_added: 4.3.0
102 contains:
103 powerstate:
104 description: The current power state of the machine specified by RV(status[].targetAddress).
105 type: str
106 targetAddress:
107 description: The remote target address.
108 type: int
109 sample:
110 [
111 {
112 "powerstate": "on",
113 "targetAddress": 48
114 },
115 {
116 "powerstate": "on",
117 "targetAddress": 50
118 }
119 ]
120 """
121
122 EXAMPLES = r"""
123 - name: Ensure machine is powered on
124 community.general.ipmi_power:
125 name: test.testdomain.com
126 user: admin
127 password: password
128 state: 'on'
129
130 - name: Ensure machines of which remote target address is 48 and 50 are powered off
131 community.general.ipmi_power:
132 name: test.testdomain.com
133 user: admin
134 password: password
135 state: 'off'
136 machine:
137 - targetAddress: 48
138 - targetAddress: 50
139
140 - name: Ensure machine of which remote target address is 48 is powered on, and 50 is powered off
141 community.general.ipmi_power:
142 name: test.testdomain.com
143 user: admin
144 password: password
145 machine:
146 - targetAddress: 48
147 state: 'on'
148 - targetAddress: 50
149 state: 'off'
150 """
151
152 import binascii
153 import traceback
154
155 PYGHMI_IMP_ERR = None
156 INVALID_TARGET_ADDRESS = 0x100
157 try:
158 from pyghmi.ipmi import command
159 except ImportError:
160 PYGHMI_IMP_ERR = traceback.format_exc()
161 command = None
162
163 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
164
165
166 def main():
167 module = AnsibleModule(
168 argument_spec=dict(
169 name=dict(required=True),
170 port=dict(default=623, type="int"),
171 state=dict(choices=["on", "off", "shutdown", "reset", "boot"]),
172 user=dict(required=True, no_log=True),
173 password=dict(required=True, no_log=True),
174 key=dict(type="str", no_log=True),
175 timeout=dict(default=300, type="int"),
176 machine=dict(
177 type="list",
178 elements="dict",
179 options=dict(
180 targetAddress=dict(required=True, type="int"),
181 state=dict(type="str", choices=["on", "off", "shutdown", "reset", "boot"]),
182 ),
183 ),
184 ),
185 supports_check_mode=True,
186 required_one_of=(["state", "machine"],),
187 )
188
189 if command is None:
190 module.fail_json(msg=missing_required_lib("pyghmi"), exception=PYGHMI_IMP_ERR)
191
192 name = module.params["name"]
193 port = module.params["port"]
194 user = module.params["user"]
195 password = module.params["password"]
196 state = module.params["state"]
197 timeout = module.params["timeout"]
198 machine = module.params["machine"]
199
200 try:
201 if module.params["key"]:
202 key = binascii.unhexlify(module.params["key"])
203 else:
204 key = None
205 except Exception:
206 module.fail_json(msg="Unable to convert 'key' from hex string.")
207
208 # --- run command ---
209 try:
210 ipmi_cmd = command.Command(bmc=name, userid=user, password=password, port=port, kg=key)
211 module.debug(f'ipmi instantiated - name: "{name}"')
212
213 changed = False
214 if machine is None:
215 current = ipmi_cmd.get_power()
216 if current["powerstate"] != state:
217 response = {"powerstate": state} if module.check_mode else ipmi_cmd.set_power(state, wait=timeout)
218 changed = True
219 else:
220 response = current
221
222 if "error" in response:
223 module.fail_json(msg=response["error"])
224
225 module.exit_json(changed=changed, **response)
226 else:
227 response = []
228 for entry in machine:
229 taddr = entry["targetAddress"]
230 if taddr >= INVALID_TARGET_ADDRESS:
231 module.fail_json(msg="targetAddress should be set between 0 to 255.")
232
233 try:
234 # bridge_request is supported on pyghmi 1.5.30 and later
235 current = ipmi_cmd.get_power(bridge_request={"addr": taddr})
236 except TypeError:
237 module.fail_json(msg="targetAddress isn't supported on the installed pyghmi.")
238
239 if entry["state"]:
240 tstate = entry["state"]
241 elif state:
242 tstate = state
243 else:
244 module.fail_json(msg="Either state or suboption of machine state should be set.")
245
246 if current["powerstate"] != tstate:
247 changed = True
248 if not module.check_mode:
249 new = ipmi_cmd.set_power(tstate, wait=timeout, bridge_request={"addr": taddr})
250 if "error" in new:
251 module.fail_json(msg=new["error"])
252
253 response.append({"targetAddress:": taddr, "powerstate": new["powerstate"]})
254
255 if current["powerstate"] == tstate or module.check_mode:
256 response.append({"targetAddress:": taddr, "powerstate": tstate})
257
258 module.exit_json(changed=changed, status=response)
259 except Exception as e:
260 module.fail_json(msg=str(e))
261
262
263 if __name__ == "__main__":
264 main()