与 AWS SDK或SendCommand一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或SendCommand一起使用 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 } } }

有关更多信息,请参阅《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 日志组。

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。

有关更多信息,请参阅《S AWS ystems Manager 用户指南》中的使用共享SSM文档

Java
SDK适用于 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对于 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适用于 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详细信息,请参阅SendCommand中的 AWS SDKPython (Boto3) API 参考。