Use RebootInstances with an AWS SDK or CLI - Amazon Elastic Compute Cloud

Use RebootInstances with an AWS SDK or CLI

The following code examples show how to use RebootInstances.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/// <summary> /// Reboot EC2 instances. /// </summary> /// <param name="ec2InstanceId">The instance Id of the instances that will be rebooted.</param> /// <returns>Async task.</returns> public async Task RebootInstances(string ec2InstanceId) { var request = new RebootInstancesRequest { InstanceIds = new List<string> { ec2InstanceId }, }; var response = await _amazonEC2.RebootInstancesAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("Instances successfully rebooted."); } else { Console.WriteLine("Could not reboot one or more instances."); } }

Replace the profile for an instance, reboot, and restart a web server.

/// <summary> /// Replace the profile associated with a running instance. After the profile is replaced, the instance /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is /// used to restart the Python web server. /// </summary> /// <param name="instanceId">The Id of the instance to update.</param> /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param> /// <param name="associationId">The Id of the existing profile association for the instance.</param> /// <returns>Async task.</returns> public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId) { await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync( new ReplaceIamInstanceProfileAssociationRequest() { AssociationId = associationId, IamInstanceProfile = new IamInstanceProfileSpecification() { Name = credsProfileName } }); // Allow time before resetting. Thread.Sleep(25000); var instanceReady = false; var retries = 5; while (retries-- > 0 && !instanceReady) { await _amazonEc2.RebootInstancesAsync( new RebootInstancesRequest(new List<string>() { instanceId })); Thread.Sleep(10000); var instancesPaginator = _amazonSsm.Paginators.DescribeInstanceInformation( new DescribeInstanceInformationRequest()); // Get the entire list using the paginator. await foreach (var instance in instancesPaginator.InstanceInformationList) { instanceReady = instance.InstanceId == instanceId; if (instanceReady) { break; } } } Console.WriteLine($"Sending restart command to instance {instanceId}"); await _amazonSsm.SendCommandAsync( new SendCommandRequest() { InstanceIds = new List<string>() { instanceId }, DocumentName = "AWS-RunShellScript", Parameters = new Dictionary<string, List<string>>() { {"commands", new List<string>() { "cd / && sudo python3 server.py 80" }} } }); Console.WriteLine($"Restarted the web server on instance {instanceId}"); }
C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::RebootInstancesRequest request; request.AddInstanceIds(instanceId); request.SetDryRun(true); auto dry_run_outcome = ec2Client.RebootInstances(request); if (dry_run_outcome.IsSuccess()) { std::cerr << "Failed dry run to reboot on instance. A dry run should trigger an error." << std::endl; return false; } else if (dry_run_outcome.GetError().GetErrorType() != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) { std::cout << "Failed dry run to reboot instance " << instanceId << ": " << dry_run_outcome.GetError().GetMessage() << std::endl; return false; } request.SetDryRun(false); auto outcome = ec2Client.RebootInstances(request); if (!outcome.IsSuccess()) { std::cout << "Failed to reboot instance " << instanceId << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully rebooted instance " << instanceId << std::endl; }
CLI
AWS CLI

To reboot an Amazon EC2 instance

This example reboots the specified instance. If the command succeeds, no output is returned.

Command:

<userinput>aws ec2 reboot-instances --instance-ids <replaceable>i-1234567890abcdef5</replaceable></userinput>

For more information, see Reboot Your Instance in the Amazon Elastic Compute Cloud User Guide.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import { RebootInstancesCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { const command = new RebootInstancesCommand({ InstanceIds: ["INSTANCE_ID"], }); try { await client.send(command); console.log("Instance rebooted successfully."); } catch (err) { console.error(err); } };
  • For API details, see RebootInstances in AWS SDK for JavaScript API Reference.

PowerShell
Tools for PowerShell

Example 1: This example reboots the specified instance.

Restart-EC2Instance -InstanceId i-12345678
  • For API details, see RebootInstances in AWS Tools for PowerShell Cmdlet Reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

class AutoScaler: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix, inst_type, ami_param, autoscaling_client, ec2_client, ssm_client, iam_client, ): """ :param resource_prefix: The prefix for naming AWS resources that are created by this class. :param inst_type: The type of EC2 instance to create, such as t3.micro. :param ami_param: The Systems Manager parameter used to look up the AMI that is created. :param autoscaling_client: A Boto3 EC2 Auto Scaling client. :param ec2_client: A Boto3 EC2 client. :param ssm_client: A Boto3 Systems Manager client. :param iam_client: A Boto3 IAM client. """ self.inst_type = inst_type self.ami_param = ami_param self.autoscaling_client = autoscaling_client self.ec2_client = ec2_client self.ssm_client = ssm_client self.iam_client = iam_client self.launch_template_name = f"{resource_prefix}-template" self.group_name = f"{resource_prefix}-group" self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" self.bad_creds_policy_name = f"{resource_prefix}-bc-pol" self.bad_creds_role_name = f"{resource_prefix}-bc-role" self.bad_creds_profile_name = f"{resource_prefix}-bc-prof" self.key_pair_name = f"{resource_prefix}-key-pair" def replace_instance_profile( self, instance_id, new_instance_profile_name, profile_association_id ): """ Replaces the profile associated with a running instance. After the profile is replaced, the instance is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is used to restart the Python web server. :param instance_id: The ID of the instance to update. :param new_instance_profile_name: The name of the new profile to associate with the specified instance. :param profile_association_id: The ID of the existing profile association for the instance. """ try: self.ec2_client.replace_iam_instance_profile_association( IamInstanceProfile={"Name": new_instance_profile_name}, AssociationId=profile_association_id, ) log.info( "Replaced instance profile for association %s with profile %s.", profile_association_id, new_instance_profile_name, ) time.sleep(5) inst_ready = False tries = 0 while not inst_ready: if tries % 6 == 0: self.ec2_client.reboot_instances(InstanceIds=[instance_id]) log.info( "Rebooting instance %s and waiting for it to to be ready.", instance_id, ) tries += 1 time.sleep(10) response = self.ssm_client.describe_instance_information() for info in response["InstanceInformationList"]: if info["InstanceId"] == instance_id: inst_ready = True self.ssm_client.send_command( InstanceIds=[instance_id], DocumentName="AWS-RunShellScript", Parameters={"commands": ["cd / && sudo python3 server.py 80"]}, ) log.info("Restarted the Python web server on instance %s.", instance_id) except ClientError as err: raise AutoScalerError( f"Couldn't replace instance profile for association {profile_association_id}: {err}" )
  • For API details, see RebootInstances in AWS SDK for Python (Boto3) API Reference.

Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

async fn reboot_instance(client: &Client, id: &str) -> Result<(), Error> { println!("Rebooting instance."); client.reboot_instances().instance_ids(id).send().await?; client .wait_until_instance_stopped() .instance_ids(id) .wait(Duration::from_secs(60)) .await?; let wait_status_ok = client .wait_until_instance_status_ok() .instance_ids(id) .wait(Duration::from_secs(60)) .await; match wait_status_ok { Ok(_) => println!("Rebooted instance {id}, it is started with status OK."), Err(err) => return Err(err.into()), } Ok(()) }
SAP ABAP
SDK for SAP ABAP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist. APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids. "Perform dry run" TRY. " DryRun is set to true. This checks for the required permissions to reboot the instance without actually making the request. " lo_ec2->rebootinstances( it_instanceids = lt_instance_ids iv_dryrun = abap_true ). CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). " If the error code returned is `DryRunOperation`, then you have the required permissions to reboot this instance. " IF lo_exception->av_err_code = 'DryRunOperation'. MESSAGE 'Dry run to reboot instance completed.' TYPE 'I'. " DryRun is set to false to make a reboot request. " lo_ec2->rebootinstances( it_instanceids = lt_instance_ids iv_dryrun = abap_false ). MESSAGE 'Instance rebooted.' TYPE 'I'. " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to reboot this instance. " ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'. MESSAGE 'Dry run to reboot instance failed. User does not have permissions to reboot the instance.' TYPE 'E'. ELSE. DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDIF. ENDTRY.
  • For API details, see RebootInstances in AWS SDK for SAP ABAP API reference.

For a complete list of AWS SDK developer guides and code examples, see Create Amazon EC2 resources using an AWS SDK. This topic also includes information about getting started and details about previous SDK versions.