AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
搭SendCommand
配 AWS SDK或使用 CLI
下列程式碼範例會示範如何使用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 } } }
若要取得更多資訊,請參閱《Systems Manager 使用指南》中的〈使用 AWS Systems Manager 執行指令〉執
範例 2:取得執行個體的 IP 資訊
下列
send-command
範例會擷取執行個體的 IP 資訊。aws ssm send-command \ --instance-ids
"i-1234567890abcdef0"
\ --document-name"AWS-RunShellScript"
\ --comment"IP config"
\ --parameters"commands=ifconfig"
如需範例輸出,請參閱範例 1。
若要取得更多資訊,請參閱《Systems Manager 使用指南》中的〈使用 AWS Systems Manager 執行指令〉執
範例 3:若要在具有特定標籤的執行個體上執行指令
下列
send-command
範例會在具有標籤索引鍵 "" ENV 和值為「Dev」的執行個體上執行命令。aws ssm send-command \ --targets
"Key=tag:ENV,Values=Dev"
\ --document-name"AWS-RunShellScript"
\ --parameters"commands=ifconfig"
如需範例輸出,請參閱範例 1。
若要取得更多資訊,請參閱《Systems Manager 使用指南》中的〈使用 AWS Systems Manager 執行指令〉執
範例 4:執行傳送SNS通知的命令
下列
send-command
範例會執行指令,該命令會傳送SNS所有通知事件和通Command
知類型的通知。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。
若要取得更多資訊,請參閱《Systems Manager 使用指南》中的〈使用 AWS Systems Manager 執行指令〉執
範例 5:執行輸出至 S3 和的命令 CloudWatch
下列
send-command
範例會執行將命令詳細資訊輸出至 S3 儲存貯體和 CloudWatch 記錄日誌群組的命令。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。
若要取得更多資訊,請參閱《Systems Manager 使用指南》中的〈使用 AWS Systems Manager 執行指令〉執
範例 6:若要在具有不同標籤的多個執行個體上執行指令
下列
send-command
範例會在具有兩個不同標籤鍵和值的執行個體上執行命令。aws ssm send-command \ --document-name
"AWS-RunPowerShellScript"
\ --parameters commands=["echo helloWorld"] \ --targetsKey=tag:Env,Values=Dev
Key=tag:Role,Values=WebServers
如需範例輸出,請參閱範例 1。
若要取得更多資訊,請參閱《Systems Manager 使用指南》中的〈使用 AWS Systems Manager 執行指令〉執
範例 7:使用相同標籤鍵定位多個執行個體
下列
send-command
範例會針對具有相同標籤鍵但值不同的執行個體執行命令。aws ssm send-command \ --document-name
"AWS-RunPowerShellScript"
\ --parameters commands=["echo helloWorld"] \ --targetsKey=tag:Env,Values=Dev,Test
如需範例輸出,請參閱範例 1。
若要取得更多資訊,請參閱《Systems Manager 使用指南》中的〈使用 AWS Systems Manager 執行指令〉執
範例 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對於爪哇 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中的。
-
- 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 指令程SendCommand式參考中的。
-
- Python
-
- SDK對於 Python(肉毒桿菌 3)
-
注意
還有更多關於 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細資訊,請參閱SendCommand中AWS SDK的〈〉以取得 Python (Boto3) API 參考資料。
-