

Doc AWS SDK Examples GitHub リポジトリには、他にも SDK の例があります。 [AWS](https://github.com/awsdocs/aws-doc-sdk-examples)

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS SDK または CLI `SendCommand`で を使用する
<a name="ssm_example_ssm_SendCommand_section"></a>

次のサンプルコードは、`SendCommand` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](ssm_example_ssm_Scenario_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**例 1: 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 を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 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 を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 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 を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 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 を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 5: S3 と CloudWatch に出力するコマンドを実行するには**  
次の `send-command` の例では、コマンドの詳細を S3 バケットと 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"
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 6: タグが異なる複数のインスタンスでコマンドを実行するには**  
次の `send-command` の例では、2 つの異なるタグキーと値を持つインスタンスでコマンドを実行します。  

```
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 を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 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 を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 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 ドキュメントの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-using-shared.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[SendCommand](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/send-command.html)」を参照してください。

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * 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](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/SendCommand)」を参照してください。

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
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](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/SendCommandCommand)」を参照してください。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 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 コマンドレットリファレンス (V4)* の「[SendCommand](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 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 リファレンス (V5) の「[SendCommand](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[SendCommand](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/SendCommand)」を参照してください。

------
#### [ SAP ABAP ]

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ssm->sendcommand(
            it_instanceids = it_instance_ids
            iv_documentname = iv_document_name
            iv_timeoutseconds = 3600 ).
        DATA(lo_command) = lo_result->get_command( ).
        IF lo_command IS BOUND.
          rv_command_id = lo_command->get_commandid( ).
          MESSAGE 'Command sent successfully.' TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_ssminvaliddocument.
        MESSAGE 'Invalid document.' TYPE 'I'.
      CATCH /aws1/cx_ssminvalidinstanceid.
        MESSAGE 'Invalid instance ID.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[SendCommand](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------