Verwendung SendCommand mit einem AWS SDK oder CLI - AWS Systems Manager

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Verwendung SendCommand mit einem AWS SDK oder CLI

Die folgenden Code-Beispiele zeigen, wie SendCommand verwendet wird.

Beispiele für Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Im folgenden Codebeispiel können Sie diese Aktion im Kontext sehen:

CLI
AWS CLI

Beispiel 1: So führen Sie einen Befehl auf einer oder mehreren Remote-Instances aus

Im folgenden Beispiel send-command wird ein echo-Befehl auf einer Ziel-Instance ausgeführt.

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

Ausgabe:

{ "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 } } }

Weitere Informationen finden Sie unter Run-Befehl mithilfe von Systems Manager in der AWS -Systems-Manager-Benutzerhandbuch.

Beispiel 2: Um IP-Informationen über eine Instance abzurufen

Im folgenden send-command-Beispiel werden Informationen über die Instances zurückgegeben.

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

Eine Beispielausgabe finden Sie in Beispiel 1.

Weitere Informationen finden Sie unter Run-Befehl mithilfe von Systems Manager in der AWS -Systems-Manager-Benutzerhandbuch.

Beispiel 3: So führen Sie einen Befehl für Instances mit bestimmten Tags aus

Im folgenden Beispiel send-command wird ein Befehl auf Instances ausgeführt, die den Tag-Schlüssel „ENV“ und den Wert „Dev“ haben.

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

Eine Beispielausgabe finden Sie in Beispiel 1.

Weitere Informationen finden Sie unter Run-Befehl mithilfe von Systems Manager in der AWS -Systems-Manager-Benutzerhandbuch.

Beispiel 4: So führen Sie einen Befehl aus, der SNS-Benachrichtigungen sendet

Im folgenden Beispiel send-command wird ein Befehl ausgeführt, der SNS-Benachrichtigungen für alle Benachrichtigungsereignisse und den Command-Benachrichtigungstyp sendet.

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"

Eine Beispielausgabe finden Sie in Beispiel 1.

Weitere Informationen finden Sie unter Run-Befehl mithilfe von Systems Manager in der AWS -Systems-Manager-Benutzerhandbuch.

Beispiel 5: Um einen Befehl auszuführen, der an S3 ausgegeben wird und CloudWatch

Im folgenden send-command Beispiel wird ein Befehl ausgeführt, der Befehlsdetails an einen S3-Bucket und eine CloudWatch Logs-Protokollgruppe ausgibt.

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"

Eine Beispielausgabe finden Sie in Beispiel 1.

Weitere Informationen finden Sie unter Run-Befehl mithilfe von Systems Manager in der AWS -Systems-Manager-Benutzerhandbuch.

Beispiel 6: So führen Sie Befehle auf mehreren Instances mit unterschiedlichen Tags aus

Im folgenden Beispiel send-command wird ein Befehl für Instances mit zwei verschiedenen Tag-Schlüsseln und -Werten ausgeführt.

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

Eine Beispielausgabe finden Sie in Beispiel 1.

Weitere Informationen finden Sie unter Run-Befehl mithilfe von Systems Manager in der AWS -Systems-Manager-Benutzerhandbuch.

Beispiel 7: So zielen Sie mehrere Instances mit demselben Tag-Schlüssel als Ziel ab

Im folgenden Beispiel send-command wird ein Befehl für Instances ausgeführt, die denselben Tag-Schlüssel, aber unterschiedliche Werte haben.

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

Eine Beispielausgabe finden Sie in Beispiel 1.

Weitere Informationen finden Sie unter Run-Befehl mithilfe von Systems Manager in der AWS -Systems-Manager-Benutzerhandbuch.

Beispiel 8: So führen Sie einen Befehl aus, der ein freigegebenes Dokument verwendet

Im folgenden Beispiel send-command wird ein gemeinsam verwendetes Dokument auf einer Ziel-Instance ausgeführt.

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

Eine Beispielausgabe finden Sie in Beispiel 1.

Weitere Informationen finden Sie unter Verwenden von geteilten SSM-Dokumenten im AWS -Systems-Manager-Benutzerhandbuch.

  • Einzelheiten zur API finden Sie SendCommandunter AWS CLI Befehlsreferenz.

Java
SDK für Java 2.x
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/** * 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]; }
  • Einzelheiten zur API finden Sie SendCommandin der AWS SDK for Java 2.x API-Referenz.

JavaScript
SDK für JavaScript (v3)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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; } } };
  • Einzelheiten zur API finden Sie SendCommandin der AWS SDK for JavaScript API-Referenz.

PowerShell
Tools für PowerShell

Beispiel 1: In diesem Beispiel wird ein Echo-Befehl auf einer Ziel-Instance ausgeführt.

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

Ausgabe:

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}

Beispiel 2: Dieses Beispiel zeigt, wie ein Befehl ausgeführt wird, der verschachtelte Parameter akzeptiert.

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
Python
SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • Einzelheiten zur API finden Sie SendCommandin AWS SDK for Python (Boto3) API Reference.

Eine vollständige Liste der AWS SDK-Entwicklerhandbücher und Codebeispiele finden Sie unter. Verwenden dieses Dienstes mit einem AWS SDK Dieses Thema enthält auch Informationen zu den ersten Schritten und Details zu früheren SDK-Versionen.