Utilícelo RebootInstances con un o AWS SDK CLI - Ejemplos de código de AWS SDK

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Utilícelo RebootInstances con un o AWS SDK CLI

En los siguientes ejemplos de código, se muestra cómo utilizar RebootInstances.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

.NET
AWS SDK for .NET
nota

Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <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."); } }

Sustituya el perfil por una instancia y reinicie un servidor web.

/// <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}"); }
  • Para API obtener más información, consulte RebootInstancesla AWS SDK for .NET APIReferencia.

C++
SDKpara C++
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

//! Reboot an Amazon Elastic Compute Cloud (Amazon EC2) instance. /*! \param instanceID: An EC2 instance ID. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::rebootInstance(const Aws::String &instanceId, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::RebootInstancesRequest request; request.AddInstanceIds(instanceId); request.SetDryRun(true); Aws::EC2::Model::RebootInstancesOutcome 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); Aws::EC2::Model::RebootInstancesOutcome 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; } return outcome.IsSuccess(); }
  • Para API obtener más información, consulte RebootInstancesla AWS SDK for C++ APIReferencia.

CLI
AWS CLI

Para reiniciar una EC2 instancia de Amazon

En este ejemplo, se reinicia la instancia especificada. Si el comando se ejecuta correctamente, no se muestra ningún resultado.

Comando:

aws ec2 reboot-instances --instance-ids i-1234567890abcdef5

Para obtener más información, consulte Reiniciar su instancia en la Guía del usuario de Amazon Elastic Compute Cloud.

  • Para API obtener más información, consulte RebootInstancesla Referencia de AWS CLI comandos.

JavaScript
SDKpara JavaScript (v3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

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); } };
  • Para API obtener más información, consulte RebootInstancesla AWS SDK for JavaScript APIReferencia.

PowerShell
Herramientas para PowerShell

Ejemplo 1: en este ejemplo se reinicia la instancia especificada.

Restart-EC2Instance -InstanceId i-12345678
Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

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}" )
  • Para API obtener más información, consulte RebootInstancesla AWS SDKreferencia de Python (Boto3). API

Rust
SDKpara Rust
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

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(()) }
  • Para API obtener más información, consulte RebootInstancesla APIreferencia AWS SDK de Rust.

SAP ABAP
SDKpara SAP ABAP
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

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.
  • Para API obtener más información, consulte RebootInstancesSAPABAPAPIcomo referencia.AWS SDK