Gunakan SendCommand dengan AWS SDK atau CLI - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan SendCommand dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanSendCommand.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

CLI
AWS CLI

Contoh 1: Untuk menjalankan perintah pada satu atau beberapa instance jarak jauh

send-commandContoh berikut menjalankan echo perintah pada instance target.

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

Output:

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

Untuk informasi selengkapnya, lihat Menjalankan Perintah Menggunakan Systems Manager Run Command di Panduan Pengguna AWS Systems Manager.

Ujian 2: Untuk mendapatkan informasi IP tentang sebuah instance

send-commandContoh berikut mengambil informasi IP tentang sebuah instance.

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

Lihat contoh 1 untuk output sampel.

Untuk informasi selengkapnya, lihat Menjalankan Perintah Menggunakan Systems Manager Run Command di Panduan Pengguna AWS Systems Manager.

Contoh 3: Untuk menjalankan perintah pada instance dengan tag tertentu

send-commandContoh berikut menjalankan perintah pada instance yang memiliki kunci tag "ENV" dan nilai “Dev”.

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

Lihat contoh 1 untuk output sampel.

Untuk informasi selengkapnya, lihat Menjalankan Perintah Menggunakan Systems Manager Run Command di Panduan Pengguna AWS Systems Manager.

Contoh 4: Untuk menjalankan perintah yang mengirimkan SNS notifikasi

send-commandContoh berikut menjalankan perintah yang mengirimkan SNS notifikasi untuk semua peristiwa notifikasi dan jenis Command notifikasi.

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"

Lihat contoh 1 untuk output sampel.

Untuk informasi selengkapnya, lihat Menjalankan Perintah Menggunakan Systems Manager Run Command di Panduan Pengguna AWS Systems Manager.

Contoh 5: Untuk menjalankan perintah yang mengeluarkan ke S3 dan CloudWatch

send-commandContoh berikut menjalankan perintah yang mengeluarkan detail perintah ke bucket S3 dan ke grup CloudWatch log Log.

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"

Lihat contoh 1 untuk output sampel.

Untuk informasi selengkapnya, lihat Menjalankan Perintah Menggunakan Systems Manager Run Command di Panduan Pengguna AWS Systems Manager.

Contoh 6: Untuk menjalankan perintah pada beberapa instance dengan tag yang berbeda

send-commandContoh berikut menjalankan perintah pada instance dengan dua kunci tag dan nilai yang berbeda.

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

Lihat contoh 1 untuk output sampel.

Untuk informasi selengkapnya, lihat Menjalankan Perintah Menggunakan Systems Manager Run Command di Panduan Pengguna AWS Systems Manager.

Contoh 7: Untuk menargetkan beberapa instance dengan kunci tag yang sama

send-commandContoh berikut menjalankan perintah pada instance yang memiliki kunci tag yang sama tetapi dengan nilai yang berbeda.

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

Lihat contoh 1 untuk output sampel.

Untuk informasi selengkapnya, lihat Menjalankan Perintah Menggunakan Systems Manager Run Command di Panduan Pengguna AWS Systems Manager.

Contoh 8: Untuk menjalankan perintah yang menggunakan dokumen bersama

send-commandContoh berikut menjalankan dokumen bersama pada instance target.

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

Lihat contoh 1 untuk output sampel.

Untuk informasi selengkapnya, lihat Menggunakan SSM dokumen bersama di Panduan Pengguna AWS Systems Manager.

  • Untuk API detailnya, lihat SendCommanddi Referensi AWS CLI Perintah.

Java
SDKuntuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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]; }
  • Untuk API detailnya, lihat SendCommanddi AWS SDK for Java 2.x APIReferensi.

PowerShell
Alat untuk PowerShell

Contoh 1: Contoh ini menjalankan perintah echo pada instance target.

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

Output:

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}

Contoh 2: Contoh ini menunjukkan cara menjalankan perintah yang menerima parameter bersarang.

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
  • Untuk API detailnya, lihat SendCommanddi AWS Tools for PowerShell Referensi Cmdlet.

Python
SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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
  • Untuk API detailnya, lihat SendCommand AWSSDKReferensi Python (Boto3). API