MCPcopy Create free account
hub / github.com/awsdocs/aws-doc-sdk-examples / stop

Method stop

python/example_code/ec2/instance.py:222–249  ·  view source on GitHub ↗

Stops instances and waits for them to be in a stopped state. :return: The response to the stop request, or None if there are no instances to stop.

(self)

Source from the content-addressed store, hash-verified

220
221 # snippet-start:[python.example_code.ec2.StopInstances]
222 def stop(self) -> Optional[Dict[str, Any]]:
223 """
224 Stops instances and waits for them to be in a stopped state.
225
226 :return: The response to the stop request, or None if there are no instances to stop.
227 """
228 if not self.instances:
229 logger.info("No instances to stop.")
230 return None
231
232 instance_ids = [instance["InstanceId"] for instance in self.instances]
233 try:
234 # Attempt to stop the instances
235 stop_response = self.ec2_client.stop_instances(InstanceIds=instance_ids)
236 waiter = self.ec2_client.get_waiter("instance_stopped")
237 waiter.wait(InstanceIds=instance_ids)
238 except ClientError as err:
239 logger.error(
240 f"Failed to stop instance(s): {','.join(map(str, instance_ids))}"
241 )
242 error_code = err.response["Error"]["Code"]
243 if error_code == "IncorrectInstanceState":
244 logger.error(
245 "Couldn't stop instance(s) because they are in an incorrect state. "
246 "Ensure the instances are in a running state before stopping them."
247 )
248 raise
249 return stop_response
250
251 # snippet-end:[python.example_code.ec2.StopInstances]
252

Callers 6

stopRecordingFunction · 0.45
tearDownMethod · 0.45
mainMethod · 0.45

Calls 2

joinMethod · 0.80
waitMethod · 0.45

Tested by 2

tearDownMethod · 0.36
mainMethod · 0.36