D’autres exemples de kits AWS SDK sont disponibles dans le référentiel GitHub AWS Doc SDK Examples
Utilisation de SendCommand avec un kit AWS SDK ou une interface de ligne de commande
Les exemples de code suivants illustrent comment utiliser SendCommand.
Les exemples d’actions sont des extraits de code de programmes de plus grande envergure et doivent être exécutés en contexte. Vous pouvez voir cette action en contexte dans l’exemple de code suivant :
- CLI
-
- AWS CLI
-
Exemple 1 : exécution d’une commande sur une ou plusieurs instances distantes
L’exemple de
send-commandsuivant exécute une commandeechosur une instance cible.aws ssm send-command \ --document-name"AWS-RunShellScript"\ --parameters 'commands=["echo HelloWorld"]' \ --targets"Key=instanceids,Values=i-1234567890abcdef0"\ --comment"echo HelloWorld"Sortie :
{ "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 } } }Pour plus d’informations, consultez Exécution de commandes à l’aide de Run Command de Systems Manager dans le Guide de l’utilisateur AWS Systems Manager.
Exemple 2 : pour obtenir des informations sur l’IP d’une instance
L’exemple de
send-commandsuivant récupère les informations sur l’IP d’une instance.aws ssm send-command \ --instance-ids"i-1234567890abcdef0"\ --document-name"AWS-RunShellScript"\ --comment"IP config"\ --parameters"commands=ifconfig"Voir l’exemple 1 pour un exemple de sortie.
Pour plus d’informations, consultez Exécution de commandes à l’aide de Run Command de Systems Manager dans le Guide de l’utilisateur AWS Systems Manager.
Exemple 3 : pour exécuter une commande sur des instances avec des balises spécifiques
L’exemple de
send-commandsuivant exécute une commande sur les instances qui ont la clé de balise « ENV » et la valeur « Dev ».aws ssm send-command \ --targets"Key=tag:ENV,Values=Dev"\ --document-name"AWS-RunShellScript"\ --parameters"commands=ifconfig"Voir l’exemple 1 pour un exemple de sortie.
Pour plus d’informations, consultez Exécution de commandes à l’aide de Run Command de Systems Manager dans le Guide de l’utilisateur AWS Systems Manager.
Exemple 4 : exécuter une commande qui envoie des notifications SNS
L’exemple de
send-commandsuivant exécute une commande qui envoie des notifications SNS pour tous les événements de notification et le type de notificationCommand.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"Voir l’exemple 1 pour un exemple de sortie.
Pour plus d’informations, consultez Exécution de commandes à l’aide de Run Command de Systems Manager dans le Guide de l’utilisateur AWS Systems Manager.
Exemple 5 : pour exécuter une commande qui renvoie des données vers S3 et CloudWatch
L’exemple de
send-commandsuivant exécute une commande qui renvoie les détails de la commande vers un compartiment S3 et vers un groupe de journaux 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"Voir l’exemple 1 pour un exemple de sortie.
Pour plus d’informations, consultez Exécution de commandes à l’aide de Run Command de Systems Manager dans le Guide de l’utilisateur AWS Systems Manager.
Exemple 6 : pour exécuter des commandes sur plusieurs instances avec des balises différentes
L’exemple de
send-commandsuivant exécute une commande sur des instances avec deux clés et valeurs de balises différentes.aws ssm send-command \ --document-name"AWS-RunPowerShellScript"\ --parameters commands=["echo helloWorld"] \ --targetsKey=tag:Env,Values=DevKey=tag:Role,Values=WebServersVoir l’exemple 1 pour un exemple de sortie.
Pour plus d’informations, consultez Exécution de commandes à l’aide de Run Command de Systems Manager dans le Guide de l’utilisateur AWS Systems Manager.
Exemple 7 : pour cibler plusieurs instances avec la même clé de balise
L’exemple de
send-commandsuivant exécute une commande sur des instances ayant la même clé de balise mais des valeurs différentes.aws ssm send-command \ --document-name"AWS-RunPowerShellScript"\ --parameters commands=["echo helloWorld"] \ --targetsKey=tag:Env,Values=Dev,TestVoir l’exemple 1 pour un exemple de sortie.
Pour plus d’informations, consultez Exécution de commandes à l’aide de Run Command de Systems Manager dans le Guide de l’utilisateur AWS Systems Manager.
Exemple 8 : pour exécuter une commande qui utilise un document partagé
L’exemple de
send-commandsuivant exécute un document partagé sur une instance cible.aws ssm send-command \ --document-name"arn:aws:ssm:us-east-1:123456789012:document/ExampleDocument"\ --targets"Key=instanceids,Values=i-1234567890abcdef0"Voir l’exemple 1 pour un exemple de sortie.
Pour plus d’informations, consultez Utilisation de documents SSM partagés dans le Guide de l’utilisateur AWS Systems Manager.
-
Pour plus d’informations sur l’API, consultez SendCommand
dans la Référence des commandes AWS CLI.
-
- Java
-
- SDK pour Java 2.x
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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]; }-
Pour en savoir plus sur l’API, consultez SendCommand dans la Référence de l’API AWS SDK for Java 2.x.
-
- JavaScript
-
- Kit SDK pour JavaScript (v3)
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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; } } };-
Pour en savoir plus sur l’API, consultez SendCommand dans la Référence de l’API AWS SDK pour JavaScript.
-
- PowerShell
-
- Outils pour PowerShell V4
-
Exemple 1 : cet exemple exécute une commande echo sur une instance cible.
Send-SSMCommand -DocumentName "AWS-RunPowerShellScript" -Parameter @{commands = "echo helloWorld"} -Target @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}Sortie :
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}Exemple 2 : cet exemple montre comment exécuter une commande qui accepte des paramètres imbriqués.
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-
Pour plus de détails sur l’API, consultez SendCommand dans la Référence des cmdlets Outils AWS pour PowerShell (V4).
-
- Outils pour PowerShell V5
-
Exemple 1 : cet exemple exécute une commande echo sur une instance cible.
Send-SSMCommand -DocumentName "AWS-RunPowerShellScript" -Parameter @{commands = "echo helloWorld"} -Target @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}Sortie :
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}Exemple 2 : cet exemple montre comment exécuter une commande qui accepte des paramètres imbriqués.
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-
Pour plus de détails sur l’API, consultez SendCommand dans la Référence des cmdlets Outils AWS pour PowerShell (V5).
-
- Python
-
- Kit SDK pour Python (Boto3)
-
Note
Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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-
Pour plus de détails sur l’API, consultez SendCommand dans la Référence de l’API d’AWS SDK pour Python (Boto3).
-