AWS SDK 또는 CLI와 함께 SendCommand 사용 - AWS Systems Manager

AWS SDK 또는 CLI와 함께 SendCommand 사용

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

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

CLI
AWS CLI

예제 1: 하나 이상의 원격 인스턴스에서 명령을 실행하는 방법

다음 send-command 예제에서는 대상 인스턴스에서 echo 명령을 실행합니다.

aws ssm send-command \ --document-name "AWS-RunShellScript" \ --parameters 'commands=["echo HelloWorld"]' \ --targets "Key=instanceids,Values=i-1234567890abcdef0" \ --comment "echo HelloWorld"

출력:

{ "Command": { "CommandId": "92853adf-ba41-4cd6-9a88-142d1EXAMPLE", "DocumentName": "AWS-RunShellScript", "DocumentVersion": "", "Comment": "echo HelloWorld", "ExpiresAfter": 1550181014.717, "Parameters": { "commands": [ "echo HelloWorld" ] }, "InstanceIds": [ "i-0f00f008a2dcbefe2" ], "Targets": [], "RequestedDateTime": 1550173814.717, "Status": "Pending", "StatusDetails": "Pending", "OutputS3BucketName": "", "OutputS3KeyPrefix": "", "MaxConcurrency": "50", "MaxErrors": "0", "TargetCount": 1, "CompletedCount": 0, "ErrorCount": 0, "DeliveryTimedOutCount": 0, "ServiceRole": "", "NotificationConfig": { "NotificationArn": "", "NotificationEvents": [], "NotificationType": "" }, "CloudWatchOutputConfig": { "CloudWatchLogGroupName": "", "CloudWatchOutputEnabled": false } } }

자세한 내용은 AWS Systems Manager 사용 설명서의 Systems Manager Run Command를 사용하여 명령 실행을 참조하세요.

예제 2: 인스턴스에 대한 IP 정보를 가져오는 방법

다음 send-command 예제에서는 인스턴스에 대한 IP 정보를 검색합니다.

aws ssm send-command \ --instance-ids "i-1234567890abcdef0" \ --document-name "AWS-RunShellScript" \ --comment "IP config" \ --parameters "commands=ifconfig"

샘플 출력은 예 1을 참조하세요.

자세한 내용은 AWS Systems Manager 사용 설명서의 Systems Manager Run Command를 사용하여 명령 실행을 참조하세요.

예제 3: 특정 태그를 사용하는 인스턴스에서 명령을 실행하는 방법

다음 send-command 예제에서는 태그 키가 'ENV'이고 값이 'Dev'인 인스턴스에서 명령을 실행합니다.

aws ssm send-command \ --targets "Key=tag:ENV,Values=Dev" \ --document-name "AWS-RunShellScript" \ --parameters "commands=ifconfig"

샘플 출력은 예 1을 참조하세요.

자세한 내용은 AWS Systems Manager 사용 설명서의 Systems Manager Run Command를 사용하여 명령 실행을 참조하세요.

예제 4: SNS 알림을 보내는 명령을 실행하는 방법

다음 send-command 예제에서는 모든 알림 이벤트 및 Command 알림 유형에 대해 SNS 알림을 보내는 명령을 실행합니다.

aws ssm send-command \ --instance-ids "i-1234567890abcdef0" \ --document-name "AWS-RunShellScript" \ --comment "IP config" \ --parameters "commands=ifconfig" \ --service-role-arn "arn:aws:iam::123456789012:role/SNS_Role" \ --notification-config "NotificationArn=arn:aws:sns:us-east-1:123456789012:SNSTopicName,NotificationEvents=All,NotificationType=Command"

샘플 출력은 예 1을 참조하세요.

자세한 내용은 AWS Systems Manager 사용 설명서의 Systems Manager Run Command를 사용하여 명령 실행을 참조하세요.

예제 5: S3 및 CloudWatch로 출력하는 명령을 실행하는 방법

다음 send-command 예제에서는 명령 세부 정보를 S3 버킷 및 CloudWatch Logs 로그 그룹에 출력하는 명령을 실행합니다.

aws ssm send-command \ --instance-ids "i-1234567890abcdef0" \ --document-name "AWS-RunShellScript" \ --comment "IP config" \ --parameters "commands=ifconfig" \ --output-s3-bucket-name "s3-bucket-name" \ --output-s3-key-prefix "runcommand" \ --cloud-watch-output-config "CloudWatchOutputEnabled=true,CloudWatchLogGroupName=CWLGroupName"

샘플 출력은 예 1을 참조하세요.

자세한 내용은 AWS Systems Manager 사용 설명서의 Systems Manager Run Command를 사용하여 명령 실행을 참조하세요.

예제 6: 태그가 서로 다른 여러 인스턴스에서 명령을 실행하는 방법

다음 send-command 예제는 서로 다른 두 개의 태그 키와 값을 가진 인스턴스에서 명령을 실행합니다.

aws ssm send-command \ --document-name "AWS-RunPowerShellScript" \ --parameters commands=["echo helloWorld"] \ --targets Key=tag:Env,Values=Dev Key=tag:Role,Values=WebServers

샘플 출력은 예 1을 참조하세요.

자세한 내용은 AWS Systems Manager 사용 설명서의 Systems Manager Run Command를 사용하여 명령 실행을 참조하세요.

예제 7: 태그 키가 같은 여러 인스턴스를 대상으로 지정하는 방법

다음 send-command 예제에서는 태그 키는 같지만 값이 다른 인스턴스에서 명령을 실행합니다.

aws ssm send-command \ --document-name "AWS-RunPowerShellScript" \ --parameters commands=["echo helloWorld"] \ --targets Key=tag:Env,Values=Dev,Test

샘플 출력은 예 1을 참조하세요.

자세한 내용은 AWS Systems Manager 사용 설명서의 Systems Manager Run Command를 사용하여 명령 실행을 참조하세요.

예제 8: 공유 문서를 사용하는 명령을 실행하는 방법

다음 send-command 예제에서는 대상 인스턴스에서 공유 문서를 실행합니다.

aws ssm send-command \ --document-name "arn:aws:ssm:us-east-1:123456789012:document/ExampleDocument" \ --targets "Key=instanceids,Values=i-1234567890abcdef0"

샘플 출력은 예 1을 참조하세요.

자세한 내용은 AWS Systems Manager 사용 설명서의 공유 SSM 문서 사용을 참조하세요.

  • API 세부 정보는 AWS CLI 명령 참조의 SendCommand를 참조하세요.

Java
SDK for Java 2.x
참고

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

/** * Sends a SSM command to a managed node asynchronously. * * @param documentName The name of the document to use. * @param instanceId The ID of the instance to send the command to. * @return The command ID. * <p> * This method initiates asynchronous requests to send a SSM command to a managed node. * It waits until the document is active, sends the command, and checks the command execution status. */ public String sendSSMCommand(String documentName, String instanceId) throws InterruptedException, SsmException { // Before we use Document to send a command - make sure it is active. CompletableFuture<Void> documentActiveFuture = CompletableFuture.runAsync(() -> { boolean isDocumentActive = false; DescribeDocumentRequest request = DescribeDocumentRequest.builder() .name(documentName) .build(); while (!isDocumentActive) { CompletableFuture<DescribeDocumentResponse> response = getAsyncClient().describeDocument(request); String documentStatus = response.join().document().statusAsString(); if (documentStatus.equals("Active")) { System.out.println("The SSM document is active and ready to use."); isDocumentActive = true; } else { System.out.println("The SSM document is not active. Status: " + documentStatus); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }); documentActiveFuture.join(); // Create the SendCommandRequest. SendCommandRequest commandRequest = SendCommandRequest.builder() .documentName(documentName) .instanceIds(instanceId) .build(); // Send the command. CompletableFuture<SendCommandResponse> commandFuture = getAsyncClient().sendCommand(commandRequest); final String[] commandId = {null}; commandFuture.whenComplete((commandResponse, ex) -> { if (commandResponse != null) { commandId[0] = commandResponse.command().commandId(); System.out.println("Command ID: " + commandId[0]); // Wait for the command execution to complete. GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder() .commandId(commandId[0]) .instanceId(instanceId) .build(); try { System.out.println("Wait 5 secs"); TimeUnit.SECONDS.sleep(5); // Retrieve the command execution details. CompletableFuture<GetCommandInvocationResponse> invocationFuture = getAsyncClient().getCommandInvocation(invocationRequest); invocationFuture.whenComplete((commandInvocationResponse, invocationEx) -> { if (commandInvocationResponse != null) { // Check the status of the command execution. CommandInvocationStatus status = commandInvocationResponse.status(); if (status == CommandInvocationStatus.SUCCESS) { System.out.println("Command execution successful"); } else { System.out.println("Command execution failed. Status: " + status); } } else { Throwable invocationCause = (invocationEx instanceof CompletionException) ? invocationEx.getCause() : invocationEx; throw new CompletionException(invocationCause); } }).join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw (SsmException) cause; } else { throw new RuntimeException(cause); } } }).join(); return commandId[0]; }
  • API 세부 정보는 AWS SDK for Java 2.x API 참조의 SendCommand를 참조하세요.

JavaScript
SDK for JavaScript (v3)
참고

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

import { SendCommandCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Send an SSM command to a managed node. * @param {{ documentName: string }} */ export const main = async ({ documentName }) => { const client = new SSMClient({}); try { await client.send( new SendCommandCommand({ DocumentName: documentName, }), ); console.log("Command sent successfully."); return { Success: true }; } catch (caught) { if (caught instanceof Error && caught.name === "ValidationError") { console.warn(`${caught.message}. Did you provide a valid document name?`); } else { throw caught; } } };
  • API 세부 정보는 AWS SDK for JavaScript API 참조의 SendCommand를 참조하세요.

PowerShell
PowerShell용 도구

예제 1: 이 예제에서는 대상 인스턴스에서 echo 명령을 실행합니다.

Send-SSMCommand -DocumentName "AWS-RunPowerShellScript" -Parameter @{commands = "echo helloWorld"} -Target @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}

출력:

CommandId : d8d190fc-32c1-4d65-a0df-ff5ff3965524 Comment : CompletedCount : 0 DocumentName : AWS-RunPowerShellScript ErrorCount : 0 ExpiresAfter : 3/7/2017 10:48:37 PM InstanceIds : {} MaxConcurrency : 50 MaxErrors : 0 NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig OutputS3BucketName : OutputS3KeyPrefix : OutputS3Region : Parameters : {[commands, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]} RequestedDateTime : 3/7/2017 9:48:37 PM ServiceRole : Status : Pending StatusDetails : Pending TargetCount : 0 Targets : {instanceids}

예제 2: 이 예제에서는 중첩된 파라미터를 수락하는 명령을 실행하는 방법을 보여줍니다.

Send-SSMCommand -DocumentName "AWS-RunRemoteScript" -Parameter @{ sourceType="GitHub";sourceInfo='{"owner": "me","repository": "amazon-ssm","path": "Examples/Install-Win32OpenSSH"}'; "commandLine"=".\Install-Win32OpenSSH.ps1"} -InstanceId i-0cb2b964d3e14fd9f
  • API 세부 정보는 AWS Tools for PowerShell Cmdlet 참조의 SendCommand를 참조하세요.

Python
SDK for Python (Boto3)
참고

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

class DocumentWrapper: """Encapsulates AWS Systems Manager Document actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def send_command(self, instance_ids): """ Sends a command to one or more instances. :param instance_ids: The IDs of the instances to send the command to. :return: The ID of the command. """ try: response = self.ssm_client.send_command( InstanceIds=instance_ids, DocumentName=self.name, TimeoutSeconds=3600 ) return response["Command"]["CommandId"] except ClientError as err: logger.error( "Couldn't send command to %s. Here's why: %s: %s", self.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • API 세부 정보는 AWS SDK for Python (Boto3) API 참조SendCommand를 참조하세요.

AWS SDK 개발자 가이드 및 코드 예시의 전체 목록은 AWS SDK와 함께 이 서비스 사용 섹션을 참조하세요. 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.