RebootInstancesOR와 함께 사용 AWS SDK CLI - AWS SDK코드 예제

AWS 문서 AWS SDK SDK 예제 GitHub 리포지토리에 더 많은 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

RebootInstancesOR와 함께 사용 AWS SDK CLI

다음 코드 예제는 RebootInstances의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 정보가 있습니다 GitHub. 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."); } }

인스턴스의 프로파일을 바꾸고, 재부팅하며, 웹 서버를 다시 시작합니다.

/// <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++
SDKC++의 경우
참고

더 많은 정보가 있습니다. GitHub 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(); }
CLI
AWS CLI

Amazon EC2 인스턴스를 재부팅하려면

이 예제에서는 지정된 인스턴스를 재부팅합니다. 이 명령이 성공하면 출력이 반환되지 않습니다.

명령:

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

자세한 내용은 Amazon Elastic Compute Cloud 사용 설명서에서 인스턴스 재부팅을 참조하세요.

  • 자세한 API 내용은 AWS CLI 명령 RebootInstances참조를 참조하십시오.

JavaScript
SDK JavaScript (v3) 에 대한
참고

더 많은 정보가 있습니다. GitHub AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import { EC2Client, RebootInstancesCommand } from "@aws-sdk/client-ec2"; /** * Requests a reboot of the specified instances. This operation is asynchronous; * it only queues a request to reboot the specified instances. * @param {{ instanceIds: string[] }} options */ export const main = async ({ instanceIds }) => { const client = new EC2Client({}); const command = new RebootInstancesCommand({ InstanceIds: instanceIds, }); try { await client.send(command); console.log("Instance rebooted successfully."); } catch (caught) { if ( caught instanceof Error && caught.name === "InvalidInstanceID.NotFound" ) { console.warn( `${caught.message}. Please provide the InstanceId of a valid instance to reboot.`, ); } else { throw caught; } } };
PowerShell
에 대한 도구 PowerShell

예 1: 이 예제는 지정된 인스턴스를 재부팅합니다.

Restart-EC2Instance -InstanceId i-12345678
  • 자세한 API 내용은 AWS Tools for PowerShell Cmdlet 참조를 참조하십시오 RebootInstances.

Python
SDK파이썬용 (보토3)
참고

더 많은 정보가 있습니다. GitHub 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}" )
  • 자세한 API AWS SDK내용은 Python (Boto3) API 참조를 참조하십시오 RebootInstances.

Rust
SDKRust의 경우
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

pub async fn reboot(&self, ec2: &EC2) -> Result<(), EC2Error> { if self.instance.is_some() { ec2.reboot_instance(self.instance_id()).await?; ec2.wait_for_instance_stopped(self.instance_id(), None) .await?; ec2.wait_for_instance_ready(self.instance_id(), None) .await?; } Ok(()) }
pub async fn reboot_instance(&self, instance_id: &str) -> Result<(), EC2Error> { tracing::info!("Rebooting instance {instance_id}"); self.client .reboot_instances() .instance_ids(instance_id) .send() .await?; Ok(()) }

웨이터를 예로 들자면 웨이터를 사용하다가 멈췄다가 준비 상태가 되는 거죠. API 웨이터를 API 사용하려면 Rust 파일에 'aws_sdk_ec2: :client: :Waiters'를 사용해야 합니다.

/// Wait for an instance to be ready and status ok (default wait 60 seconds) pub async fn wait_for_instance_ready( &self, instance_id: &str, duration: Option<Duration>, ) -> Result<(), EC2Error> { self.client .wait_until_instance_status_ok() .instance_ids(instance_id) .wait(duration.unwrap_or(Duration::from_secs(60))) .await .map_err(|err| match err { WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!( "Exceeded max time ({}s) waiting for instance to start.", exceeded.max_wait().as_secs() )), _ => EC2Error::from(err), })?; Ok(()) } pub async fn wait_for_instance_stopped( &self, instance_id: &str, duration: Option<Duration>, ) -> Result<(), EC2Error> { self.client .wait_until_instance_stopped() .instance_ids(instance_id) .wait(duration.unwrap_or(Duration::from_secs(60))) .await .map_err(|err| match err { WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!( "Exceeded max time ({}s) waiting for instance to stop.", exceeded.max_wait().as_secs(), )), _ => EC2Error::from(err), })?; Ok(()) }
  • 자세한 RebootInstances내용은 AWS SDKRust API 참조를 참조하십시오. API

SAP ABAP
SDK... 에 대한 SAP ABAP
참고

더 많은 정보가 있습니다 GitHub. 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.
  • 자세한 API AWS SDK내용은 RebootInstances에서 SAP ABAP API 참조를 참조하십시오.