

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. [AWS](https://github.com/awsdocs/aws-doc-sdk-examples) 

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# AWS SDKs를 사용하는 Systems Manager의 코드 예제
<a name="ssm_code_examples"></a>

다음 코드 예제에서는 AWS 소프트웨어 개발 키트(SDK)와 AWS Systems Manager 함께를 사용하는 방법을 보여줍니다.

*기본 사항*은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.

*작업*은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접 호출하는 방법을 보여주며, 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

**추가 리소스**
+  **[Systems Manager 사용 설명서](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html)** - Systems Manager에 대한 자세한 정보입니다.
+ **[Systems Manager API 참조](https://docs.aws.amazon.com/systems-manager/latest/APIReference/Welcome.html)** - 사용 가능한 모든 Systems Manager 작업에 대한 세부 정보입니다.
+ **[AWS 개발자 센터](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23systems-mgr)** - 범주 또는 전체 텍스트 검색을 기준으로 필터링할 수 있는 코드 예제입니다.
+ **[AWS SDK 예제](https://github.com/awsdocs/aws-doc-sdk-examples)** - 기본 언어로 된 전체 코드가 포함된 GitHub 리포지토리입니다. 코드 설정 및 실행을 위한 지침이 포함되어 있습니다.

**Contents**
+ [기본 사항](ssm_code_examples_basics.md)
  + [Hello Systems Manager](ssm_example_ssm_Hello_section.md)
  + [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md)
  + [작업](ssm_code_examples_actions.md)
    + [`AddTagsToResource`](ssm_example_ssm_AddTagsToResource_section.md)
    + [`CancelCommand`](ssm_example_ssm_CancelCommand_section.md)
    + [`CreateActivation`](ssm_example_ssm_CreateActivation_section.md)
    + [`CreateAssociation`](ssm_example_ssm_CreateAssociation_section.md)
    + [`CreateAssociationBatch`](ssm_example_ssm_CreateAssociationBatch_section.md)
    + [`CreateDocument`](ssm_example_ssm_CreateDocument_section.md)
    + [`CreateMaintenanceWindow`](ssm_example_ssm_CreateMaintenanceWindow_section.md)
    + [`CreateOpsItem`](ssm_example_ssm_CreateOpsItem_section.md)
    + [`CreatePatchBaseline`](ssm_example_ssm_CreatePatchBaseline_section.md)
    + [`DeleteActivation`](ssm_example_ssm_DeleteActivation_section.md)
    + [`DeleteAssociation`](ssm_example_ssm_DeleteAssociation_section.md)
    + [`DeleteDocument`](ssm_example_ssm_DeleteDocument_section.md)
    + [`DeleteMaintenanceWindow`](ssm_example_ssm_DeleteMaintenanceWindow_section.md)
    + [`DeleteOpsItem`](ssm_example_ssm_DeleteOpsItem_section.md)
    + [`DeleteParameter`](ssm_example_ssm_DeleteParameter_section.md)
    + [`DeletePatchBaseline`](ssm_example_ssm_DeletePatchBaseline_section.md)
    + [`DeregisterManagedInstance`](ssm_example_ssm_DeregisterManagedInstance_section.md)
    + [`DeregisterPatchBaselineForPatchGroup`](ssm_example_ssm_DeregisterPatchBaselineForPatchGroup_section.md)
    + [`DeregisterTargetFromMaintenanceWindow`](ssm_example_ssm_DeregisterTargetFromMaintenanceWindow_section.md)
    + [`DeregisterTaskFromMaintenanceWindow`](ssm_example_ssm_DeregisterTaskFromMaintenanceWindow_section.md)
    + [`DescribeActivations`](ssm_example_ssm_DescribeActivations_section.md)
    + [`DescribeAssociation`](ssm_example_ssm_DescribeAssociation_section.md)
    + [`DescribeAssociationExecutionTargets`](ssm_example_ssm_DescribeAssociationExecutionTargets_section.md)
    + [`DescribeAssociationExecutions`](ssm_example_ssm_DescribeAssociationExecutions_section.md)
    + [`DescribeAutomationExecutions`](ssm_example_ssm_DescribeAutomationExecutions_section.md)
    + [`DescribeAutomationStepExecutions`](ssm_example_ssm_DescribeAutomationStepExecutions_section.md)
    + [`DescribeAvailablePatches`](ssm_example_ssm_DescribeAvailablePatches_section.md)
    + [`DescribeDocument`](ssm_example_ssm_DescribeDocument_section.md)
    + [`DescribeDocumentPermission`](ssm_example_ssm_DescribeDocumentPermission_section.md)
    + [`DescribeEffectiveInstanceAssociations`](ssm_example_ssm_DescribeEffectiveInstanceAssociations_section.md)
    + [`DescribeEffectivePatchesForPatchBaseline`](ssm_example_ssm_DescribeEffectivePatchesForPatchBaseline_section.md)
    + [`DescribeInstanceAssociationsStatus`](ssm_example_ssm_DescribeInstanceAssociationsStatus_section.md)
    + [`DescribeInstanceInformation`](ssm_example_ssm_DescribeInstanceInformation_section.md)
    + [`DescribeInstancePatchStates`](ssm_example_ssm_DescribeInstancePatchStates_section.md)
    + [`DescribeInstancePatchStatesForPatchGroup`](ssm_example_ssm_DescribeInstancePatchStatesForPatchGroup_section.md)
    + [`DescribeInstancePatches`](ssm_example_ssm_DescribeInstancePatches_section.md)
    + [`DescribeMaintenanceWindowExecutionTaskInvocations`](ssm_example_ssm_DescribeMaintenanceWindowExecutionTaskInvocations_section.md)
    + [`DescribeMaintenanceWindowExecutionTasks`](ssm_example_ssm_DescribeMaintenanceWindowExecutionTasks_section.md)
    + [`DescribeMaintenanceWindowExecutions`](ssm_example_ssm_DescribeMaintenanceWindowExecutions_section.md)
    + [`DescribeMaintenanceWindowTargets`](ssm_example_ssm_DescribeMaintenanceWindowTargets_section.md)
    + [`DescribeMaintenanceWindowTasks`](ssm_example_ssm_DescribeMaintenanceWindowTasks_section.md)
    + [`DescribeMaintenanceWindows`](ssm_example_ssm_DescribeMaintenanceWindows_section.md)
    + [`DescribeOpsItems`](ssm_example_ssm_DescribeOpsItems_section.md)
    + [`DescribeParameters`](ssm_example_ssm_DescribeParameters_section.md)
    + [`DescribePatchBaselines`](ssm_example_ssm_DescribePatchBaselines_section.md)
    + [`DescribePatchGroupState`](ssm_example_ssm_DescribePatchGroupState_section.md)
    + [`DescribePatchGroups`](ssm_example_ssm_DescribePatchGroups_section.md)
    + [`GetAutomationExecution`](ssm_example_ssm_GetAutomationExecution_section.md)
    + [`GetCommandInvocation`](ssm_example_ssm_GetCommandInvocation_section.md)
    + [`GetConnectionStatus`](ssm_example_ssm_GetConnectionStatus_section.md)
    + [`GetDefaultPatchBaseline`](ssm_example_ssm_GetDefaultPatchBaseline_section.md)
    + [`GetDeployablePatchSnapshotForInstance`](ssm_example_ssm_GetDeployablePatchSnapshotForInstance_section.md)
    + [`GetDocument`](ssm_example_ssm_GetDocument_section.md)
    + [`GetInventory`](ssm_example_ssm_GetInventory_section.md)
    + [`GetInventorySchema`](ssm_example_ssm_GetInventorySchema_section.md)
    + [`GetMaintenanceWindow`](ssm_example_ssm_GetMaintenanceWindow_section.md)
    + [`GetMaintenanceWindowExecution`](ssm_example_ssm_GetMaintenanceWindowExecution_section.md)
    + [`GetMaintenanceWindowExecutionTask`](ssm_example_ssm_GetMaintenanceWindowExecutionTask_section.md)
    + [`GetParameter`](ssm_example_ssm_GetParameter_section.md)
    + [`GetParameterHistory`](ssm_example_ssm_GetParameterHistory_section.md)
    + [`GetParameters`](ssm_example_ssm_GetParameters_section.md)
    + [`GetPatchBaseline`](ssm_example_ssm_GetPatchBaseline_section.md)
    + [`GetPatchBaselineForPatchGroup`](ssm_example_ssm_GetPatchBaselineForPatchGroup_section.md)
    + [`ListAssociationVersions`](ssm_example_ssm_ListAssociationVersions_section.md)
    + [`ListAssociations`](ssm_example_ssm_ListAssociations_section.md)
    + [`ListCommandInvocations`](ssm_example_ssm_ListCommandInvocations_section.md)
    + [`ListCommands`](ssm_example_ssm_ListCommands_section.md)
    + [`ListComplianceItems`](ssm_example_ssm_ListComplianceItems_section.md)
    + [`ListComplianceSummaries`](ssm_example_ssm_ListComplianceSummaries_section.md)
    + [`ListDocumentVersions`](ssm_example_ssm_ListDocumentVersions_section.md)
    + [`ListDocuments`](ssm_example_ssm_ListDocuments_section.md)
    + [`ListInventoryEntries`](ssm_example_ssm_ListInventoryEntries_section.md)
    + [`ListResourceComplianceSummaries`](ssm_example_ssm_ListResourceComplianceSummaries_section.md)
    + [`ListTagsForResource`](ssm_example_ssm_ListTagsForResource_section.md)
    + [`ModifyDocumentPermission`](ssm_example_ssm_ModifyDocumentPermission_section.md)
    + [`PutComplianceItems`](ssm_example_ssm_PutComplianceItems_section.md)
    + [`PutInventory`](ssm_example_ssm_PutInventory_section.md)
    + [`PutParameter`](ssm_example_ssm_PutParameter_section.md)
    + [`RegisterDefaultPatchBaseline`](ssm_example_ssm_RegisterDefaultPatchBaseline_section.md)
    + [`RegisterPatchBaselineForPatchGroup`](ssm_example_ssm_RegisterPatchBaselineForPatchGroup_section.md)
    + [`RegisterTargetWithMaintenanceWindow`](ssm_example_ssm_RegisterTargetWithMaintenanceWindow_section.md)
    + [`RegisterTaskWithMaintenanceWindow`](ssm_example_ssm_RegisterTaskWithMaintenanceWindow_section.md)
    + [`RemoveTagsFromResource`](ssm_example_ssm_RemoveTagsFromResource_section.md)
    + [`SendCommand`](ssm_example_ssm_SendCommand_section.md)
    + [`StartAutomationExecution`](ssm_example_ssm_StartAutomationExecution_section.md)
    + [`StartSession`](ssm_example_ssm_StartSession_section.md)
    + [`StopAutomationExecution`](ssm_example_ssm_StopAutomationExecution_section.md)
    + [`UpdateAssociation`](ssm_example_ssm_UpdateAssociation_section.md)
    + [`UpdateAssociationStatus`](ssm_example_ssm_UpdateAssociationStatus_section.md)
    + [`UpdateDocument`](ssm_example_ssm_UpdateDocument_section.md)
    + [`UpdateDocumentDefaultVersion`](ssm_example_ssm_UpdateDocumentDefaultVersion_section.md)
    + [`UpdateMaintenanceWindow`](ssm_example_ssm_UpdateMaintenanceWindow_section.md)
    + [`UpdateManagedInstanceRole`](ssm_example_ssm_UpdateManagedInstanceRole_section.md)
    + [`UpdateOpsItem`](ssm_example_ssm_UpdateOpsItem_section.md)
    + [`UpdatePatchBaseline`](ssm_example_ssm_UpdatePatchBaseline_section.md)

# AWS SDKs 사용하는 Systems Manager의 기본 예제
<a name="ssm_code_examples_basics"></a>

다음 코드 예제에서는 AWS Systems Manager SDKs에서의 기본 사항을 AWS 사용하는 방법을 보여줍니다.

**Contents**
+ [Hello Systems Manager](ssm_example_ssm_Hello_section.md)
+ [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md)
+ [작업](ssm_code_examples_actions.md)
  + [`AddTagsToResource`](ssm_example_ssm_AddTagsToResource_section.md)
  + [`CancelCommand`](ssm_example_ssm_CancelCommand_section.md)
  + [`CreateActivation`](ssm_example_ssm_CreateActivation_section.md)
  + [`CreateAssociation`](ssm_example_ssm_CreateAssociation_section.md)
  + [`CreateAssociationBatch`](ssm_example_ssm_CreateAssociationBatch_section.md)
  + [`CreateDocument`](ssm_example_ssm_CreateDocument_section.md)
  + [`CreateMaintenanceWindow`](ssm_example_ssm_CreateMaintenanceWindow_section.md)
  + [`CreateOpsItem`](ssm_example_ssm_CreateOpsItem_section.md)
  + [`CreatePatchBaseline`](ssm_example_ssm_CreatePatchBaseline_section.md)
  + [`DeleteActivation`](ssm_example_ssm_DeleteActivation_section.md)
  + [`DeleteAssociation`](ssm_example_ssm_DeleteAssociation_section.md)
  + [`DeleteDocument`](ssm_example_ssm_DeleteDocument_section.md)
  + [`DeleteMaintenanceWindow`](ssm_example_ssm_DeleteMaintenanceWindow_section.md)
  + [`DeleteOpsItem`](ssm_example_ssm_DeleteOpsItem_section.md)
  + [`DeleteParameter`](ssm_example_ssm_DeleteParameter_section.md)
  + [`DeletePatchBaseline`](ssm_example_ssm_DeletePatchBaseline_section.md)
  + [`DeregisterManagedInstance`](ssm_example_ssm_DeregisterManagedInstance_section.md)
  + [`DeregisterPatchBaselineForPatchGroup`](ssm_example_ssm_DeregisterPatchBaselineForPatchGroup_section.md)
  + [`DeregisterTargetFromMaintenanceWindow`](ssm_example_ssm_DeregisterTargetFromMaintenanceWindow_section.md)
  + [`DeregisterTaskFromMaintenanceWindow`](ssm_example_ssm_DeregisterTaskFromMaintenanceWindow_section.md)
  + [`DescribeActivations`](ssm_example_ssm_DescribeActivations_section.md)
  + [`DescribeAssociation`](ssm_example_ssm_DescribeAssociation_section.md)
  + [`DescribeAssociationExecutionTargets`](ssm_example_ssm_DescribeAssociationExecutionTargets_section.md)
  + [`DescribeAssociationExecutions`](ssm_example_ssm_DescribeAssociationExecutions_section.md)
  + [`DescribeAutomationExecutions`](ssm_example_ssm_DescribeAutomationExecutions_section.md)
  + [`DescribeAutomationStepExecutions`](ssm_example_ssm_DescribeAutomationStepExecutions_section.md)
  + [`DescribeAvailablePatches`](ssm_example_ssm_DescribeAvailablePatches_section.md)
  + [`DescribeDocument`](ssm_example_ssm_DescribeDocument_section.md)
  + [`DescribeDocumentPermission`](ssm_example_ssm_DescribeDocumentPermission_section.md)
  + [`DescribeEffectiveInstanceAssociations`](ssm_example_ssm_DescribeEffectiveInstanceAssociations_section.md)
  + [`DescribeEffectivePatchesForPatchBaseline`](ssm_example_ssm_DescribeEffectivePatchesForPatchBaseline_section.md)
  + [`DescribeInstanceAssociationsStatus`](ssm_example_ssm_DescribeInstanceAssociationsStatus_section.md)
  + [`DescribeInstanceInformation`](ssm_example_ssm_DescribeInstanceInformation_section.md)
  + [`DescribeInstancePatchStates`](ssm_example_ssm_DescribeInstancePatchStates_section.md)
  + [`DescribeInstancePatchStatesForPatchGroup`](ssm_example_ssm_DescribeInstancePatchStatesForPatchGroup_section.md)
  + [`DescribeInstancePatches`](ssm_example_ssm_DescribeInstancePatches_section.md)
  + [`DescribeMaintenanceWindowExecutionTaskInvocations`](ssm_example_ssm_DescribeMaintenanceWindowExecutionTaskInvocations_section.md)
  + [`DescribeMaintenanceWindowExecutionTasks`](ssm_example_ssm_DescribeMaintenanceWindowExecutionTasks_section.md)
  + [`DescribeMaintenanceWindowExecutions`](ssm_example_ssm_DescribeMaintenanceWindowExecutions_section.md)
  + [`DescribeMaintenanceWindowTargets`](ssm_example_ssm_DescribeMaintenanceWindowTargets_section.md)
  + [`DescribeMaintenanceWindowTasks`](ssm_example_ssm_DescribeMaintenanceWindowTasks_section.md)
  + [`DescribeMaintenanceWindows`](ssm_example_ssm_DescribeMaintenanceWindows_section.md)
  + [`DescribeOpsItems`](ssm_example_ssm_DescribeOpsItems_section.md)
  + [`DescribeParameters`](ssm_example_ssm_DescribeParameters_section.md)
  + [`DescribePatchBaselines`](ssm_example_ssm_DescribePatchBaselines_section.md)
  + [`DescribePatchGroupState`](ssm_example_ssm_DescribePatchGroupState_section.md)
  + [`DescribePatchGroups`](ssm_example_ssm_DescribePatchGroups_section.md)
  + [`GetAutomationExecution`](ssm_example_ssm_GetAutomationExecution_section.md)
  + [`GetCommandInvocation`](ssm_example_ssm_GetCommandInvocation_section.md)
  + [`GetConnectionStatus`](ssm_example_ssm_GetConnectionStatus_section.md)
  + [`GetDefaultPatchBaseline`](ssm_example_ssm_GetDefaultPatchBaseline_section.md)
  + [`GetDeployablePatchSnapshotForInstance`](ssm_example_ssm_GetDeployablePatchSnapshotForInstance_section.md)
  + [`GetDocument`](ssm_example_ssm_GetDocument_section.md)
  + [`GetInventory`](ssm_example_ssm_GetInventory_section.md)
  + [`GetInventorySchema`](ssm_example_ssm_GetInventorySchema_section.md)
  + [`GetMaintenanceWindow`](ssm_example_ssm_GetMaintenanceWindow_section.md)
  + [`GetMaintenanceWindowExecution`](ssm_example_ssm_GetMaintenanceWindowExecution_section.md)
  + [`GetMaintenanceWindowExecutionTask`](ssm_example_ssm_GetMaintenanceWindowExecutionTask_section.md)
  + [`GetParameter`](ssm_example_ssm_GetParameter_section.md)
  + [`GetParameterHistory`](ssm_example_ssm_GetParameterHistory_section.md)
  + [`GetParameters`](ssm_example_ssm_GetParameters_section.md)
  + [`GetPatchBaseline`](ssm_example_ssm_GetPatchBaseline_section.md)
  + [`GetPatchBaselineForPatchGroup`](ssm_example_ssm_GetPatchBaselineForPatchGroup_section.md)
  + [`ListAssociationVersions`](ssm_example_ssm_ListAssociationVersions_section.md)
  + [`ListAssociations`](ssm_example_ssm_ListAssociations_section.md)
  + [`ListCommandInvocations`](ssm_example_ssm_ListCommandInvocations_section.md)
  + [`ListCommands`](ssm_example_ssm_ListCommands_section.md)
  + [`ListComplianceItems`](ssm_example_ssm_ListComplianceItems_section.md)
  + [`ListComplianceSummaries`](ssm_example_ssm_ListComplianceSummaries_section.md)
  + [`ListDocumentVersions`](ssm_example_ssm_ListDocumentVersions_section.md)
  + [`ListDocuments`](ssm_example_ssm_ListDocuments_section.md)
  + [`ListInventoryEntries`](ssm_example_ssm_ListInventoryEntries_section.md)
  + [`ListResourceComplianceSummaries`](ssm_example_ssm_ListResourceComplianceSummaries_section.md)
  + [`ListTagsForResource`](ssm_example_ssm_ListTagsForResource_section.md)
  + [`ModifyDocumentPermission`](ssm_example_ssm_ModifyDocumentPermission_section.md)
  + [`PutComplianceItems`](ssm_example_ssm_PutComplianceItems_section.md)
  + [`PutInventory`](ssm_example_ssm_PutInventory_section.md)
  + [`PutParameter`](ssm_example_ssm_PutParameter_section.md)
  + [`RegisterDefaultPatchBaseline`](ssm_example_ssm_RegisterDefaultPatchBaseline_section.md)
  + [`RegisterPatchBaselineForPatchGroup`](ssm_example_ssm_RegisterPatchBaselineForPatchGroup_section.md)
  + [`RegisterTargetWithMaintenanceWindow`](ssm_example_ssm_RegisterTargetWithMaintenanceWindow_section.md)
  + [`RegisterTaskWithMaintenanceWindow`](ssm_example_ssm_RegisterTaskWithMaintenanceWindow_section.md)
  + [`RemoveTagsFromResource`](ssm_example_ssm_RemoveTagsFromResource_section.md)
  + [`SendCommand`](ssm_example_ssm_SendCommand_section.md)
  + [`StartAutomationExecution`](ssm_example_ssm_StartAutomationExecution_section.md)
  + [`StartSession`](ssm_example_ssm_StartSession_section.md)
  + [`StopAutomationExecution`](ssm_example_ssm_StopAutomationExecution_section.md)
  + [`UpdateAssociation`](ssm_example_ssm_UpdateAssociation_section.md)
  + [`UpdateAssociationStatus`](ssm_example_ssm_UpdateAssociationStatus_section.md)
  + [`UpdateDocument`](ssm_example_ssm_UpdateDocument_section.md)
  + [`UpdateDocumentDefaultVersion`](ssm_example_ssm_UpdateDocumentDefaultVersion_section.md)
  + [`UpdateMaintenanceWindow`](ssm_example_ssm_UpdateMaintenanceWindow_section.md)
  + [`UpdateManagedInstanceRole`](ssm_example_ssm_UpdateManagedInstanceRole_section.md)
  + [`UpdateOpsItem`](ssm_example_ssm_UpdateOpsItem_section.md)
  + [`UpdatePatchBaseline`](ssm_example_ssm_UpdatePatchBaseline_section.md)

# Hello Systems Manager
<a name="ssm_example_ssm_Hello_section"></a>

다음 코드 예제에서는 Systems Manager를 사용하여 시작하는 방법을 보여줍니다.

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

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.DocumentFilter;
import software.amazon.awssdk.services.ssm.model.ListDocumentsRequest;
import software.amazon.awssdk.services.ssm.model.ListDocumentsResponse;

public class HelloSSM {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <awsAccount>

                Where:
                    awsAccount - Your AWS Account number.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String awsAccount = args[0] ;
        Region region = Region.US_EAST_1;
        SsmClient ssmClient = SsmClient.builder()
            .region(region)
            .build();

        listDocuments(ssmClient, awsAccount);
    }

    /*
    This code automatically fetches the next set of results using the `nextToken` and
    stops once the desired maxResults (20 in this case) have been reached.
    */
    public static void listDocuments(SsmClient ssmClient, String awsAccount) {
        String nextToken = null;
        int totalDocumentsReturned = 0;
        int maxResults = 20;
        do {
            ListDocumentsRequest request = ListDocumentsRequest.builder()
                .documentFilterList(
                    DocumentFilter.builder()
                        .key("Owner")
                        .value(awsAccount)
                        .build()
                    )
                .maxResults(maxResults)
                .nextToken(nextToken)
                .build();

            ListDocumentsResponse response = ssmClient.listDocuments(request);
            response.documentIdentifiers().forEach(identifier -> System.out.println("Document Name: " + identifier.name()));
            nextToken = response.nextToken();
            totalDocumentsReturned += response.documentIdentifiers().size();
        } while (nextToken != null && totalDocumentsReturned < maxResults);
    }
}
```
+  API 세부 정보는 **AWS SDK for Java 2.x API 참조의 [ListDocuments](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/ListDocuments)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { paginateListDocuments, SSMClient } from "@aws-sdk/client-ssm";

// Call ListDocuments and display the result.
export const main = async () => {
  const client = new SSMClient();
  const listDocumentsPaginated = [];
  console.log(
    "Hello, AWS Systems Manager! Let's list some of your documents:\n",
  );
  try {
    // The paginate function is a wrapper around the base command.
    const paginator = paginateListDocuments({ client }, { MaxResults: 5 });
    for await (const page of paginator) {
      listDocumentsPaginated.push(...page.DocumentIdentifiers);
    }
  } catch (caught) {
    console.error(`There was a problem saying hello: ${caught.message}`);
    throw caught;
  }

  for (const { Name, DocumentFormat, CreatedDate } of listDocumentsPaginated) {
    console.log(`${Name} - ${DocumentFormat} - ${CreatedDate}`);
  }
};

// Call function if run directly.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [ListDocuments](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/ListDocumentsCommand)를 참조하세요.

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

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import boto3
from botocore.exceptions import ClientError


def hello_systems_manager(ssm_client):
    """
    Use the AWS SDK for Python (Boto3) to create an AWS Systems Manager
    client and list the first 5 documents in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param ssm_client: A Boto3 AWS Systems Manager Client object. This object wraps
                             the low-level AWS Systems Manager service API.
    """
    print("Hello, AWS Systems Manager! Let's list some of your documents:\n")

    paginator = ssm_client.get_paginator("list_documents")
    page_iterator = paginator.paginate(PaginationConfig={"MaxItems": 5})
    for page in page_iterator:
        for document in page["DocumentIdentifiers"]:
            print(f"  {document['Name']}")


if __name__ == "__main__":
    try:
        hello_systems_manager(boto3.client("ssm"))
    except ClientError as err:
        print("Hello systems manager had an error.")
        print(err.response["Error"]["Code"])
        print(err.response["Error"]["Message"])
```
+  API 세부 정보는 **AWS SDK for Python (Boto3) API 참조의 [ListDocuments](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/ListDocuments)를 참조하세요.

------

# AWS SDK를 사용하여 Systems Manager의 기본 사항 알아보기
<a name="ssm_example_ssm_Scenario_section"></a>

다음 코드 예제는 다음과 같은 작업을 수행하는 방법을 보여줍니다.
+ 유지 관리 기간을 생성합니다.
+ 유지 보수 기간 일정을 수정합니다.
+ 문서를 만듭니다.
+ 지정된 EC2 인스턴스로 명령을 보냅니다.
+ OpsItem을 생성합니다.
+ OpsItem을 업데이트하고 해결합니다.
+ 유지 보수 기간, OpsItem 및 문서를 삭제합니다.

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

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.services.ssm.model.DocumentAlreadyExistsException;
import software.amazon.awssdk.services.ssm.model.SsmException;

import java.util.Map;
import java.util.Scanner;
public class SSMScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final String ROLES_STACK = "SsmStack3`1";

    public static void main(String[] args) {
        String usage = """
            Usage:
              <title> <source> <category> <severity>
      
            Where:
                title - The title of the parameter (default is Disk Space Alert).
                source - The source of the parameter (default is EC2).
                category - The category of the parameter. Valid values are 'Availability', 'Cost', 'Performance', 'Recovery', 'Security' (default is Performance).
                severity - The severity of the parameter. Severity should be a number from 1 to 4 (default is 2).
        """;

        Scanner scanner = new Scanner(System.in);
        SSMActions actions = new SSMActions();
        String documentName;
        String windowName;

        System.out.println("Use AWS CloudFormation to create the EC2 instance that is required for this scenario.");
        CloudFormationHelper.deployCloudFormationStack(ROLES_STACK);
        Map<String, String> stackOutputs = CloudFormationHelper.getStackOutputsAsync(ROLES_STACK).join();
        String instanceId = stackOutputs.get("InstanceId");
        System.out.println("The Instance ID: " + instanceId +" was created.");
        String title = "Disk Space Alert" ;
        String source = "EC2" ;
        String category = "Availability" ;
        String severity = "2" ;

        System.out.println(DASHES);
        System.out.println("""
                Welcome to the AWS Systems Manager SDK Basics scenario.
                This Java program demonstrates how to interact with AWS Systems Manager using the AWS SDK for Java (v2).
                AWS Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution.
                The program's primary functionalities include creating a maintenance window, creating a document, sending a command to a document,
                listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting AWS SSM resources.
                Upon completion of the program, all AWS resources are cleaned up.
                Let's get started...
            
                """);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("1. Create an SSM maintenance window.");
        System.out.println("Please enter the maintenance window name (default is ssm-maintenance-window):");
        String win = scanner.nextLine();
        windowName = win.isEmpty() ? "ssm-maintenance-window" : win;
        String winId = null;
        try {
            winId = actions.createMaintenanceWindow(windowName);
            waitForInputToContinue(scanner);
            System.out.println("The maintenance window ID is: " + winId);
        } catch (DocumentAlreadyExistsException e) {
            System.err.println("The SSM maintenance window already exists. Retrieving existing window ID...");
            String existingWinId = actions.createMaintenanceWindow(windowName);
            System.out.println("Existing window ID: " + existingWinId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("2. Modify the maintenance window by changing the schedule");
        waitForInputToContinue(scanner);
        try {
            actions.updateSSMMaintenanceWindow(winId, windowName);
            waitForInputToContinue(scanner);
            System.out.println("The SSM maintenance window was successfully updated");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("3. Create an SSM document that defines the actions that Systems Manager performs on your managed nodes.");
        System.out.println("Please enter the document name (default is ssmdocument):");
        String doc = scanner.nextLine();
        documentName = doc.isEmpty() ? "ssmdocument" : doc;
        try {
            actions.createSSMDoc(documentName);
            waitForInputToContinue(scanner);
            System.out.println("The SSM document was successfully created");
        } catch (DocumentAlreadyExistsException e) {
            System.err.println("The SSM document already exists. Moving on");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("4. Now we are going to run a command on an EC2 instance");
        waitForInputToContinue(scanner);
        String commandId="";
        try {
            commandId = actions.sendSSMCommand(documentName, instanceId);
            waitForInputToContinue(scanner);
            System.out.println("The command was successfully sent. Command ID: " + commandId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
        } catch (InterruptedException e) {
            System.err.println("Thread was interrupted: " + e.getMessage());
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("5. Lets get the time when the specific command was sent to the specific managed node");
        waitForInputToContinue(scanner);
        try {
            actions.displayCommands(commandId);
            System.out.println("The command invocations were successfully displayed.");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
             6. Now we will create an SSM OpsItem. 
             A SSM OpsItem is a feature provided by Amazon's Systems Manager (SSM) service. 
             It is a type of operational data item that allows you to manage and track various operational issues, 
             events, or tasks within your AWS environment.
             
             You can create OpsItems to track and manage operational issues as they arise. 
             For example, you could create an OpsItem whenever your application detects a critical error 
             or an anomaly in your infrastructure.
            """);

        waitForInputToContinue(scanner);
        String opsItemId;
        try {
            opsItemId = actions.createSSMOpsItem(title, source, category, severity);
            System.out.println(opsItemId + " was created");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Now we will update the SSM OpsItem "+opsItemId);
        waitForInputToContinue(scanner);
        String description = "An update to "+opsItemId ;
        try {
            actions.updateOpsItem(opsItemId, title, description);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }

        System.out.println(DASHES);
        System.out.println("8. Now we will get the status of the SSM OpsItem "+opsItemId);
        waitForInputToContinue(scanner);
        try {
            actions.describeOpsItems(opsItemId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }

        System.out.println(DASHES);
        System.out.println("9. Now we will resolve the SSM OpsItem "+opsItemId);
        waitForInputToContinue(scanner);
        try {
            actions.resolveOpsItem(opsItemId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }

        System.out.println(DASHES);
        System.out.println("10. Would you like to delete the AWS Systems Manager resources? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            System.out.println("You selected to delete the resources.");
            waitForInputToContinue(scanner);
            try {
                actions.deleteMaintenanceWindow(winId);
                actions.deleteDoc(documentName);
            } catch (SsmException e) {
                System.err.println("SSM error: " + e.getMessage());
                return;
            } catch (RuntimeException e) {
                System.err.println("Unexpected error: " + e.getMessage());
                return;
            }
        } else {
            System.out.println("The AWS Systems Manager resources will not be deleted");
        }
        System.out.println(DASHES);
        CloudFormationHelper.destroyCloudFormationStack(ROLES_STACK);
        System.out.println("This concludes the AWS Systems Manager SDK Basics scenario.");
        System.out.println(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println("");
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }
}
```
Systems Manager SDK 메서드에 대한 래퍼 클래스입니다.  

```
public class SSMActions {

    private static SsmAsyncClient ssmAsyncClient;

    private static SsmAsyncClient getAsyncClient() {
        if (ssmAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                    .maxConcurrency(100)
                    .connectionTimeout(Duration.ofSeconds(60))
                    .readTimeout(Duration.ofSeconds(60))
                    .writeTimeout(Duration.ofSeconds(60))
                    .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                    .apiCallTimeout(Duration.ofMinutes(2))
                    .apiCallAttemptTimeout(Duration.ofSeconds(90))
                    .retryPolicy(RetryPolicy.builder()
                            .numRetries(3)
                            .build())
                    .build();

            ssmAsyncClient = SsmAsyncClient.builder()
                    .region(Region.US_WEST_2)
                    .httpClient(httpClient)
                    .overrideConfiguration(overrideConfig)
                    .build();
        }
        return ssmAsyncClient;
    }

    /**
     * Deletes an AWS SSM document asynchronously.
     *
     * @param documentName The name of the document to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM document.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteDoc(String documentName) {
        DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder()
                .name(documentName)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteDocument(documentRequest)
                    .thenAccept(response -> {
                        System.out.println("The SSM document was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Deletes an AWS SSM Maintenance Window asynchronously.
     *
     * @param winId The ID of the Maintenance Window to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM Maintenance Window.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteMaintenanceWindow(String winId) {
        DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder()
                .windowId(winId)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteMaintenanceWindow(windowRequest)
                    .thenAccept(response -> {
                        System.out.println("The maintenance window was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Resolves an AWS SSM OpsItem asynchronously.
     *
     * @param opsID The ID of the OpsItem to resolve.
     * <p>
     * This method initiates an asynchronous request to resolve an SSM OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void resolveOpsItem(String opsID) {
        UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder()
                .opsItemId(opsID)
                .status(OpsItemStatus.RESOLVED)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().updateOpsItem(opsItemRequest)
                    .thenAccept(response -> {
                        System.out.println("OpsItem resolved successfully.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Describes AWS SSM OpsItems asynchronously.
     *
     * @param key The key to filter OpsItems by (e.g., OPS_ITEM_ID).
     *
     * This method initiates an asynchronous request to describe SSM OpsItems.
     * If the request is successful, it prints the title and status of each OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void describeOpsItems(String key) {
        OpsItemFilter filter = OpsItemFilter.builder()
                .key(OpsItemFilterKey.OPS_ITEM_ID)
                .values(key)
                .operator(OpsItemFilterOperator.EQUAL)
                .build();

        DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder()
                .maxResults(10)
                .opsItemFilters(filter)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().describeOpsItems(itemsRequest)
                    .thenAccept(itemsResponse -> {
                        List<OpsItemSummary> items = itemsResponse.opsItemSummaries();
                        for (OpsItemSummary item : items) {
                            System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString());
                        }
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Updates the AWS SSM OpsItem asynchronously.
     *
     * @param opsItemId The ID of the OpsItem to update.
     * @param title The new title of the OpsItem.
     * @param description The new description of the OpsItem.
     * <p>
     * This method initiates an asynchronous request to update an SSM OpsItem.
     * If the request is successful, it completes without returning a value.
     * If an exception occurs, it handles the error appropriately.
     */
    public void updateOpsItem(String opsItemId, String title, String description) {
        Map<String, OpsItemDataValue> operationalData = new HashMap<>();
        operationalData.put("key1", OpsItemDataValue.builder().value("value1").build());
        operationalData.put("key2", OpsItemDataValue.builder().value("value2").build());

        CompletableFuture<Void> future = getOpsItem(opsItemId).thenCompose(opsItem -> {
            UpdateOpsItemRequest request = UpdateOpsItemRequest.builder()
                    .opsItemId(opsItemId)
                    .title(title)
                    .operationalData(operationalData)
                    .status(opsItem.statusAsString())
                    .description(description)
                    .build();

            return getAsyncClient().updateOpsItem(request).thenAccept(response -> {
                System.out.println(opsItemId + " updated successfully.");
            }).exceptionally(ex -> {
                throw new CompletionException(ex);
            });
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }


    private static CompletableFuture<OpsItem> getOpsItem(String opsItemId) {
        GetOpsItemRequest request = GetOpsItemRequest.builder().opsItemId(opsItemId).build();
        return getAsyncClient().getOpsItem(request).thenApply(GetOpsItemResponse::opsItem);
    }

    /**
     * Creates an SSM OpsItem asynchronously.
     *
     * @param title The title of the OpsItem.
     * @param source The source of the OpsItem.
     * @param category The category of the OpsItem.
     * @param severity The severity of the OpsItem.
     * @return The ID of the created OpsItem.
     * <p>
     * This method initiates an asynchronous request to create an SSM OpsItem.
     * If the request is successful, it returns the OpsItem ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createSSMOpsItem(String title, String source, String category, String severity) {
        CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder()
                .description("Created by the SSM Java API")
                .title(title)
                .source(source)
                .category(category)
                .severity(severity)
                .build();

        CompletableFuture<CreateOpsItemResponse> future = getAsyncClient().createOpsItem(opsItemRequest);

        try {
            CreateOpsItemResponse response = future.join();
            return response.opsItemId();
        } catch (CompletionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof SsmException) {
                throw (SsmException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }
    }

    /**
     * Displays the date and time when the specific command was invoked.
     *
     * @param commandId The ID of the command to describe.
     * <p>
     * This method initiates an asynchronous request to list command invocations and prints the date and time of each command invocation.
     * If an exception occurs, it handles the error appropriately.
     */
    public void displayCommands(String commandId) {
        ListCommandInvocationsRequest commandInvocationsRequest = ListCommandInvocationsRequest.builder()
                .commandId(commandId)
                .build();

        CompletableFuture<ListCommandInvocationsResponse> future = getAsyncClient().listCommandInvocations(commandInvocationsRequest);
        future.thenAccept(response -> {
            List<CommandInvocation> commandList = response.commandInvocations();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
            for (CommandInvocation invocation : commandList) {
                System.out.println("The time of the command invocation is " + formatter.format(invocation.requestedDateTime()));
            }
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw (SsmException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }).join();
    }

    /**
     * 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];
    }

    /**
     * Creates an AWS SSM document asynchronously.
     *
     * @param docName The name of the document to create.
     * <p>
     * This method initiates an asynchronous request to create an SSM document.
     * If the request is successful, it prints the document status.
     * If an exception occurs, it handles the error appropriately.
     */
    public void createSSMDoc(String docName) throws SsmException {
        String jsonData = """
        {
        "schemaVersion": "2.2",
        "description": "Run a simple shell command",
        "mainSteps": [
            {
                "action": "aws:runShellScript",
                "name": "runEchoCommand",
                "inputs": {
                  "runCommand": [
                    "echo 'Hello, world!'"
                  ]
                }
              }
            ]
        }
        """;

        CreateDocumentRequest request = CreateDocumentRequest.builder()
                .content(jsonData)
                .name(docName)
                .documentType(DocumentType.COMMAND)
                .build();

        CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request);
        future.thenAccept(response -> {
            System.out.println("The status of the SSM document is " + response.documentDescription().status());
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof DocumentAlreadyExistsException) {
                throw new CompletionException(cause);
            } else if (cause instanceof SsmException) {
                throw new CompletionException(cause);
            } else {
                throw new RuntimeException(cause);
            }
        }).join();
    }

    /**
     * Updates an SSM maintenance window asynchronously.
     *
     * @param id The ID of the maintenance window to update.
     * @param name The new name for the maintenance window.
     * <p>
     * This method initiates an asynchronous request to update an SSM maintenance window.
     * If the request is successful, it prints a success message.
     * If an exception occurs, it handles the error appropriately.
     */
    public void updateSSMMaintenanceWindow(String id, String name) throws SsmException {
        UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder()
                .windowId(id)
                .allowUnassociatedTargets(true)
                .duration(24)
                .enabled(true)
                .name(name)
                .schedule("cron(0 0 ? * MON *)")
                .build();

        CompletableFuture<UpdateMaintenanceWindowResponse> future = getAsyncClient().updateMaintenanceWindow(updateRequest);
        future.whenComplete((response, ex) -> {
            if (response != null) {
                System.out.println("The SSM maintenance window was successfully updated");
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();
    }

    /**
     * Creates an SSM maintenance window asynchronously.
     *
     * @param winName The name of the maintenance window.
     * @return The ID of the created or existing maintenance window.
     * <p>
     * This method initiates an asynchronous request to create an SSM maintenance window.
     * If the request is successful, it prints the maintenance window ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException {
        CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder()
                .name(winName)
                .description("This is my maintenance window")
                .allowUnassociatedTargets(true)
                .duration(2)
                .cutoff(1)
                .schedule("cron(0 10 ? * MON-FRI *)")
                .build();

        CompletableFuture<CreateMaintenanceWindowResponse> future = getAsyncClient().createMaintenanceWindow(request);
        final String[] windowId = {null};
        future.whenComplete((response, ex) -> {
            if (response != null) {
                String maintenanceWindowId = response.windowId();
                System.out.println("The maintenance window id is " + maintenanceWindowId);
                windowId[0] = maintenanceWindowId;
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof DocumentAlreadyExistsException) {
                    throw new CompletionException(cause);
                } else if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();

        if (windowId[0] == null) {
            MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder()
                    .key("name")
                    .values(winName)
                    .build();

            DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder()
                    .filters(filter)
                    .build();

            CompletableFuture<DescribeMaintenanceWindowsResponse> describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest);
            describeFuture.whenComplete((describeResponse, describeEx) -> {
                if (describeResponse != null) {
                    List<MaintenanceWindowIdentity> windows = describeResponse.windowIdentities();
                    if (!windows.isEmpty()) {
                        windowId[0] = windows.get(0).windowId();
                        System.out.println("Window ID: " + windowId[0]);
                    } else {
                        System.out.println("Window not found.");
                        windowId[0] = "";
                    }
                } else {
                    Throwable describeCause = (describeEx instanceof CompletionException) ? describeEx.getCause() : describeEx;
                    throw new RuntimeException("Error describing maintenance windows: " + describeCause.getMessage(), describeCause);
                }
            }).join();
        }

        return windowId[0];
    }
}
```
+ API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 다음 주제를 참조하세요.
  + [CreateDocument](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateDocument)
  + [CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateMaintenanceWindow)
  + [CreateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateOpsItem)
  + [DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DeleteMaintenanceWindow)
  + [ListCommandInvocations](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/ListCommandInvocations)
  + [SendCommand](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/SendCommand)
  + [UpdateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/UpdateOpsItem)

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { fileURLToPath } from "node:url";
import {
  CreateDocumentCommand,
  CreateMaintenanceWindowCommand,
  CreateOpsItemCommand,
  DeleteDocumentCommand,
  DeleteMaintenanceWindowCommand,
  DeleteOpsItemCommand,
  DescribeOpsItemsCommand,
  DocumentAlreadyExists,
  OpsItemStatus,
  waitUntilCommandExecuted,
  CancelCommandCommand,
  paginateListCommandInvocations,
  SendCommandCommand,
  UpdateMaintenanceWindowCommand,
  UpdateOpsItemCommand,
  SSMClient,
} from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * @typedef {{
 *   ssmClient: import('@aws-sdk/client-ssm').SSMClient,
 *   documentName?: string
 *   maintenanceWindow?: string
 *   winId?: int
 *   ec2InstanceId?: string
 *   requestedDateTime?: Date
 *   opsItemId?: string
 *   askToDeleteResources?: boolean
 * }} State
 */

const defaultMaintenanceWindow = "ssm-maintenance-window";
const defaultDocumentName = "ssmdocument";
// The timeout duration is highly dependent on the specific setup and environment necessary. This example handles only the most common error cases, and uses a much shorter duration than most productions systems would use.
const COMMAND_TIMEOUT_DURATION_SECONDS = 30; // 30 seconds

const pressEnter = new ScenarioInput("continue", "Press Enter to continue", {
  type: "confirm",
});

const greet = new ScenarioOutput(
  "greet",
  `Welcome to the AWS Systems Manager SDK Getting Started scenario.
    This program demonstrates how to interact with Systems Manager using the AWS SDK for JavaScript V3.
    Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution.
    The program's primary functions include creating a maintenance window, creating a document, sending a command to a document,
    listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting Systems Manager resources.
    Upon completion of the program, all AWS resources are cleaned up.
    Let's get started...`,
  { header: true },
);

const createMaintenanceWindow = new ScenarioOutput(
  "createMaintenanceWindow",
  "Step 1: Create a Systems Manager maintenance window.",
);

const getMaintenanceWindow = new ScenarioInput(
  "maintenanceWindow",
  "Please enter the maintenance window name:",
  { type: "input", default: defaultMaintenanceWindow },
);

export const sdkCreateMaintenanceWindow = new ScenarioAction(
  "sdkCreateMaintenanceWindow",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new CreateMaintenanceWindowCommand({
          Name: state.maintenanceWindow,
          Schedule: "cron(0 10 ? * MON-FRI *)", //The schedule of the maintenance window in the form of a cron or rate expression.
          Duration: 2, //The duration of the maintenance window in hours.
          Cutoff: 1, //The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution.
          AllowUnassociatedTargets: true, //Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
        }),
      );
      state.winId = response.WindowId;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while creating the maintenance window. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const modifyMaintenanceWindow = new ScenarioOutput(
  "modifyMaintenanceWindow",
  "Modify the maintenance window by changing the schedule.",
);

const sdkModifyMaintenanceWindow = new ScenarioAction(
  "sdkModifyMaintenanceWindow",
  async (/** @type {State} */ state) => {
    try {
      await state.ssmClient.send(
        new UpdateMaintenanceWindowCommand({
          WindowId: state.winId,
          Schedule: "cron(0 0 ? * MON *)",
        }),
      );
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while modifying the maintenance window. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const createSystemsManagerActions = new ScenarioOutput(
  "createSystemsManagerActions",
  "Create a document that defines the actions that Systems Manager performs on your EC2 instance.",
);

const getDocumentName = new ScenarioInput(
  "documentName",
  "Please enter the document: ",
  { type: "input", default: defaultDocumentName },
);

const sdkCreateSSMDoc = new ScenarioAction(
  "sdkCreateSSMDoc",
  async (/** @type {State} */ state) => {
    const contentData = `{
                "schemaVersion": "2.2",
                "description": "Run a simple shell command",
                "mainSteps": [
                    {
                        "action": "aws:runShellScript",
                        "name": "runEchoCommand",
                        "inputs": {
                          "runCommand": [
                            "echo 'Hello, world!'"
                          ]
                        }
                    }
                ]
            }`;
    try {
      await state.ssmClient.send(
        new CreateDocumentCommand({
          Content: contentData,
          Name: state.documentName,
          DocumentType: "Command",
        }),
      );
    } catch (caught) {
      console.log(`Exception type: (${typeof caught})`);
      if (caught instanceof DocumentAlreadyExists) {
        console.log("Document already exists. Continuing...\n");
      } else {
        console.error(caught.message);
        console.log(
          `An error occurred while creating the document. Please fix the error and try again. Error message: ${caught.message}`,
        );
        throw caught;
      }
    }
  },
);

const ec2HelloWorld = new ScenarioOutput(
  "ec2HelloWorld",
  `Now you have the option of running a command on an EC2 instance that echoes 'Hello, world!'. In order to run this command, you must provide the instance ID of a Linux EC2 instance. If you do not already have a running Linux EC2 instance in your account, you can create one using the AWS console. For information about creating an EC2 instance, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html.`,
);

const enterIdOrSkipEC2HelloWorld = new ScenarioInput(
  "enterIdOrSkipEC2HelloWorld",
  "Enter your EC2 InstanceId or press enter to skip this step: ",
  { type: "input", default: "" },
);

const sdkEC2HelloWorld = new ScenarioAction(
  "sdkEC2HelloWorld",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new SendCommandCommand({
          DocumentName: state.documentName,
          InstanceIds: [state.ec2InstanceId],
          TimeoutSeconds: COMMAND_TIMEOUT_DURATION_SECONDS,
        }),
      );
      state.CommandId = response.Command.CommandId;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while sending the command. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
  {
    skipWhen: (/** @type {State} */ state) =>
      state.enterIdOrSkipEC2HelloWorld === "",
  },
);

const sdkGetCommandTime = new ScenarioAction(
  "sdkGetCommandTime",
  async (/** @type {State} */ state) => {
    const listInvocationsPaginated = [];
    console.log(
      "Let's get the time when the specific command was sent to the specific managed node.",
    );

    console.log(
      `First, we'll wait for the command to finish executing. This may take up to ${COMMAND_TIMEOUT_DURATION_SECONDS} seconds.`,
    );
    const commandExecutedResult = waitUntilCommandExecuted(
      { client: state.ssmClient },
      {
        CommandId: state.CommandId,
        InstanceId: state.ec2InstanceId,
      },
    );
    // This is necessary because the TimeoutSeconds of SendCommandCommand is only for the delivery, not execution.
    try {
      await new Promise((_, reject) =>
        setTimeout(
          reject,
          COMMAND_TIMEOUT_DURATION_SECONDS * 1000,
          new Error("Command Timed Out"),
        ),
      );
    } catch (caught) {
      if (caught.message === "Command Timed Out") {
        commandExecutedResult.state = "TIMED_OUT";
      } else {
        throw caught;
      }
    }

    if (commandExecutedResult.state !== "SUCCESS") {
      console.log(
        `The command with id: ${state.CommandId} did not execute in the allotted time. Canceling command.`,
      );
      state.ssmClient.send(
        new CancelCommandCommand({
          CommandId: state.CommandId,
        }),
      );
      state.enterIdOrSkipEC2HelloWorld === "";
      return;
    }

    for await (const page of paginateListCommandInvocations(
      { client: state.ssmClient },
      { CommandId: state.CommandId },
    )) {
      listInvocationsPaginated.push(...page.CommandInvocations);
    }
    /**
     * @type {import('@aws-sdk/client-ssm').CommandInvocation}
     */
    const commandInvocation = listInvocationsPaginated.shift(); // Because the call was made with CommandId, there's only one result, so shift it off.
    state.requestedDateTime = commandInvocation.RequestedDateTime;

    console.log(
      `The command invocation happened at: ${state.requestedDateTime}.`,
    );
  },
  {
    skipWhen: (/** @type {State} */ state) =>
      state.enterIdOrSkipEC2HelloWorld === "",
  },
);

const createSSMOpsItem = new ScenarioOutput(
  "createSSMOpsItem",
  `Now we will create a Systems Manager OpsItem. An OpsItem is a feature provided by the Systems Manager service. It is a type of operational data item that allows you to manage and track various operational issues, events, or tasks within your AWS environment.
You can create OpsItems to track and manage operational issues as they arise. For example, you could create an OpsItem whenever your application detects a critical error or an anomaly in your infrastructure.`,
);

const sdkCreateSSMOpsItem = new ScenarioAction(
  "sdkCreateSSMOpsItem",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new CreateOpsItemCommand({
          Description: "Created by the System Manager Javascript API",
          Title: "Disk Space Alert",
          Source: "EC2",
          Category: "Performance",
          Severity: "2",
        }),
      );
      state.opsItemId = response.OpsItemId;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while creating the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const updateOpsItem = new ScenarioOutput(
  "updateOpsItem",
  (/** @type {State} */ state) =>
    `Now we will update the OpsItem: ${state.opsItemId}`,
);

const sdkUpdateOpsItem = new ScenarioAction(
  "sdkUpdateOpsItem",
  async (/** @type {State} */ state) => {
    try {
      const _response = await state.ssmClient.send(
        new UpdateOpsItemCommand({
          OpsItemId: state.opsItemId,
          Description: `An update to ${state.opsItemId}`,
        }),
      );
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while updating the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const getOpsItemStatus = new ScenarioOutput(
  "getOpsItemStatus",
  (/** @type {State} */ state) =>
    `Now we will get the status of the OpsItem: ${state.opsItemId}`,
);

const sdkOpsItemStatus = new ScenarioAction(
  "sdkGetOpsItemStatus",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new DescribeOpsItemsCommand({
          OpsItemId: state.opsItemId,
        }),
      );
      state.opsItemStatus = response.OpsItemStatus;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while describing the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const resolveOpsItem = new ScenarioOutput(
  "resolveOpsItem",
  (/** @type {State} */ state) =>
    `Now we will resolve the OpsItem: ${state.opsItemId}`,
);

const sdkResolveOpsItem = new ScenarioAction(
  "sdkResolveOpsItem",
  async (/** @type {State} */ state) => {
    try {
      const _response = await state.ssmClient.send(
        new UpdateOpsItemCommand({
          OpsItemId: state.opsItemId,
          Status: OpsItemStatus.RESOLVED,
        }),
      );
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while updating the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const askToDeleteResources = new ScenarioInput(
  "askToDeleteResources",
  "Would you like to delete the Systems Manager resources created during this example run?",
  { type: "confirm" },
);

const confirmDeleteChoice = new ScenarioOutput(
  "confirmDeleteChoice",
  (/** @type {State} */ state) => {
    if (state.askToDeleteResources) {
      return "You chose to delete the resources.";
    }
    return "The Systems Manager resources will not be deleted. Please delete them manually to avoid charges.";
  },
);

export const sdkDeleteResources = new ScenarioAction(
  "sdkDeleteResources",
  async (/** @type {State} */ state) => {
    try {
      await state.ssmClient.send(
        new DeleteOpsItemCommand({
          OpsItemId: state.opsItemId,
        }),
      );
      console.log(`The ops item: ${state.opsItemId} was successfully deleted.`);
    } catch (caught) {
      console.log(
        `There was a problem deleting the ops item: ${state.opsItemId}. Please delete it manually. Error: ${caught.message}`,
      );
    }

    try {
      await state.ssmClient.send(
        new DeleteMaintenanceWindowCommand({
          Name: state.maintenanceWindow,
          WindowId: state.winId,
        }),
      );
      console.log(
        `The maintenance window: ${state.maintenanceWindow} was successfully deleted.`,
      );
    } catch (caught) {
      console.log(
        `There was a problem deleting the maintenance window: ${state.opsItemId}. Please delete it manually. Error: ${caught.message}`,
      );
    }

    try {
      await state.ssmClient.send(
        new DeleteDocumentCommand({
          Name: state.documentName,
        }),
      );
      console.log(
        `The document: ${state.documentName} was successfully deleted.`,
      );
    } catch (caught) {
      console.log(
        `There was a problem deleting the document: ${state.documentName}. Please delete it manually. Error: ${caught.message}`,
      );
    }
  },
  { skipWhen: (/** @type {{}} */ state) => !state.askToDeleteResources },
);

const goodbye = new ScenarioOutput(
  "goodbye",
  "This concludes the Systems Manager Basics scenario for the AWS Javascript SDK v3. Thank you!",
);

const myScenario = new Scenario(
  "SSM Basics",
  [
    greet,
    pressEnter,
    createMaintenanceWindow,
    getMaintenanceWindow,
    sdkCreateMaintenanceWindow,
    modifyMaintenanceWindow,
    pressEnter,
    sdkModifyMaintenanceWindow,
    createSystemsManagerActions,
    getDocumentName,
    sdkCreateSSMDoc,
    ec2HelloWorld,
    enterIdOrSkipEC2HelloWorld,
    sdkEC2HelloWorld,
    sdkGetCommandTime,
    pressEnter,
    createSSMOpsItem,
    pressEnter,
    sdkCreateSSMOpsItem,
    updateOpsItem,
    pressEnter,
    sdkUpdateOpsItem,
    getOpsItemStatus,
    pressEnter,
    sdkOpsItemStatus,
    resolveOpsItem,
    pressEnter,
    sdkResolveOpsItem,
    askToDeleteResources,
    confirmDeleteChoice,
    sdkDeleteResources,
    goodbye,
  ],
  { ssmClient: new SSMClient({}) },
);

/** @type {{ stepHandlerOptions: StepHandlerOptions }} */
export const main = async (stepHandlerOptions) => {
  await myScenario.run(stepHandlerOptions);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      yes: {
        type: "boolean",
        short: "y",
      },
    },
  });
  main({ confirmAll: values.yes });
}
```
+ API 세부 정보는 *AWS SDK for JavaScript API 참조*의 다음 주제를 참조하세요.
  + [CreateDocument](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateDocumentCommand)
  + [CreateMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateMaintenanceWindowCommand)
  + [CreateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateOpsItemCommand)
  + [DeleteMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DeleteMaintenanceWindowCommand)
  + [ListCommandInvocations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/ListCommandInvocationsCommand)
  + [SendCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/SendCommandCommand)
  + [UpdateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/UpdateOpsItemCommand)

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

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
명령 프롬프트에서 대화형 시나리오를 실행합니다.  

```
class SystemsManagerScenario:
    """Runs an interactive scenario that shows how to get started using Amazon Systems Manager."""

    def __init__(self, document_wrapper, maintenance_window_wrapper, ops_item_wrapper):
        """
        :param document_wrapper: An object that wraps Systems Manager document functions.
        :param maintenance_window_wrapper: An object that wraps Systems Manager maintenance window functions.
        :param ops_item_wrapper: An object that wraps Systems Manager OpsItem functions.
        """
        self.document_wrapper = document_wrapper
        self.maintenance_window_wrapper = maintenance_window_wrapper
        self.ops_item_wrapper = ops_item_wrapper

    def run(self):
        """Demonstrates how to use the AWS SDK for Python (Boto3) to get started with Systems Manager."""
        try:
            print("-" * 88)
            print(
                """
Welcome to the AWS Systems Manager SDK Getting Started scenario.
This program demonstrates how to interact with Systems Manager using the AWS SDK for Python (Boto3).
Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management 
solution. The program's primary functions include creating a maintenance window, creating a document, sending a 
command to a document, listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting 
Systems Manager resources. Upon completion of the program, all AWS resources are cleaned up.
Let's get started..."""
            )
            q.ask("Please hit Enter")

            print("-" * 88)
            print("Create a Systems Manager maintenance window.")
            maintenance_window_name = q.ask(
                "Please enter the maintenance window name (default is ssm-maintenance-window):",
            )
            if not maintenance_window_name:
                maintenance_window_name = "ssm-maintenance-window"

            self.maintenance_window_wrapper.create(
                name=maintenance_window_name,
                schedule="cron(0 10 ? * MON-FRI *)",
                duration=2,
                cutoff=1,
                allow_unassociated_targets=True,
            )

            print("-" * 88)
            print("Modify the maintenance window by changing the schedule")
            q.ask("Please hit Enter")

            self.maintenance_window_wrapper.update(
                name=maintenance_window_name,
                schedule="cron(0 0 ? * MON *)",
                duration=24,
                cutoff=1,
                allow_unassociated_targets=True,
                enabled=True,
            )

            print("-" * 88)
            print(
                "Create a document that defines the actions that Systems Manager performs on your EC2 instance."
            )
            document_name = q.ask(
                "Please enter the document name (default is ssmdocument):"
            )

            if not document_name:
                document_name = "ssmdocument"

            self.document_wrapper.create(
                name=document_name,
                content="""
{
    "schemaVersion": "2.2",
    "description": "Run a simple shell command",
    "mainSteps": [
        {
            "action": "aws:runShellScript",
            "name": "runEchoCommand",
            "inputs": {
              "runCommand": [
                "echo 'Hello, world!'"
              ]
            }
        }
    ]
}
            """,
            )

            self.document_wrapper.wait_until_active()

            print(
                """
Now you have the option of running a command on an EC2 instance that echoes 'Hello, world!'.
In order to run this command, you must provide the instance ID of a Linux EC2 instance. If you do
not already have a running Linux EC2 instance in your account, you can create one using the AWS console.
For information about creating an EC2 instance, see 
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html.
            """
            )

            if q.ask(
                "Would you like to run a command on an EC2 instance? (y/n)",
                q.is_yesno,
            ):
                instance_id = q.ask(
                    "Please enter the instance ID of the EC2 instance:", q.non_empty
                )
                command_id = self.document_wrapper.send_command(
                    instance_ids=[instance_id]
                )

                self.document_wrapper.wait_command_executed(
                    command_id=command_id, instance_id=instance_id
                )

                print("-" * 88)
                print(
                    "Lets get the time when the specific command was sent to the specific managed node"
                )
                q.ask("Please hit Enter")

                self.document_wrapper.list_command_invocations(instance_id=instance_id)

            print("-" * 88)
            print("-" * 88)
            print(
                """
Now we will create a  Systems Manager OpsItem.
An OpsItem is a feature provided by the Systems Manager service.
It is a type of operational data item that allows you to manage and track various operational issues,
events, or tasks within your AWS environment.

You can create OpsItems to track and manage operational issues as they arise.
For example, you could create an OpsItem whenever your application detects a critical error
or an anomaly in your infrastructure.
            """
            )
            q.ask("Please hit Enter")

            self.ops_item_wrapper.create(
                title="Disk Space Alert",
                description="Created by the Systems Manager Python (Boto3) API",
                source="EC2",
                category="Performance",
                severity="2",
            )

            print("-" * 88)
            print("-" * 88)
            print(f"Now we will update  the OpsItem {self.ops_item_wrapper.id}")
            q.ask("Please hit Enter")

            self.ops_item_wrapper.update(
                title="Disk Space Alert",
                description=f"An update to {self.ops_item_wrapper.id}",
            )

            print(
                f"Now we will get the status of the OpsItem {self.ops_item_wrapper.id}"
            )
            q.ask("Please hit Enter")

            # It may take a second for the ops item to be available
            counter = 0
            while not self.ops_item_wrapper.describe() and counter < 5:
                counter += 1
                time.sleep(1)

            print(f"Now we will resolve the OpsItem {self.ops_item_wrapper.id}")
            q.ask("Please hit Enter")

            self.ops_item_wrapper.update(status="Resolved")

            print("-" * 88)
            print("-" * 88)
            if q.ask(
                "Would you like to delete the Systems Manager resources? (y/n)",
                q.is_yesno,
            ):
                print("You selected to delete the resources.")
                self.cleanup()
            else:
                print("The Systems Manager resources will not be deleted")

            print("-" * 88)
            print("This concludes the Systems Manager SDK Getting Started scenario.")
            print("-" * 88)

        except Exception:
            self.cleanup()
            raise

    def cleanup(self):
        self.maintenance_window_wrapper.delete()
        self.ops_item_wrapper.delete()
        self.document_wrapper.delete()


if __name__ == "__main__":
    try:
        scenario = SystemsManagerScenario(
            DocumentWrapper.from_client(),
            MaintenanceWindowWrapper.from_client(),
            OpsItemWrapper.from_client(),
        )
        scenario.run()
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
문서 및 명령 작업을 래핑하는 클래스를 정의합니다.  

```
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 create(self, content, name):
        """
        Creates a document.

        :param content: The content of the document.
        :param name: The name of the document.
        """
        try:
            self.ssm_client.create_document(
                Name=name, Content=content, DocumentType="Command"
            )
            self.name = name
        except self.ssm_client.exceptions.DocumentAlreadyExists:
            print(f"Document {name} already exists.")
            self.name = name
        except ClientError as err:
            logger.error(
                "Couldn't create %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete(self):
        """
        Deletes an AWS Systems Manager document.
        """
        if self.name is None:
            return

        try:
            self.ssm_client.delete_document(Name=self.name)
            print(f"Deleted document {self.name}.")
            self.name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    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


    def describe(self):
        """
        Describes the document.

        :return: Document status.
        """
        try:
            response = self.ssm_client.describe_document(Name=self.name)
            return response["Document"]["Status"]
        except ClientError as err:
            logger.error(
                "Couldn't get %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def wait_until_active(self, max_attempts=20, delay=5):
        """
        Waits until the document is active.

        :param max_attempts: The maximum number of attempts for checking the status.
        :param delay: The delay in seconds between each check.
        """
        attempt = 0
        status = ""
        while attempt <= max_attempts:
            status = self.describe()
            if status == "Active":
                break
            attempt += 1
            time.sleep(delay)

        if status != "Active":
            logger.error("Document is not active.")
        else:
            logger.info("Document is active.")

    def wait_command_executed(self, command_id, instance_id):
        """
        Waits until the command is executed on the instance.

        :param command_id: The ID of the command.
        :param instance_id: The ID of the instance.
        """

        waiter = self.ssm_client.get_waiter("command_executed")
        waiter.wait(CommandId=command_id, InstanceId=instance_id)

    def list_command_invocations(self, instance_id):
        """
        Lists the commands for an instance.

        :param instance_id: The ID of the instance.
        :return: The list of commands.
        """
        try:
            paginator = self.ssm_client.get_paginator("list_command_invocations")
            command_invocations = []
            for page in paginator.paginate(InstanceId=instance_id):
                command_invocations.extend(page["CommandInvocations"])
            num_of_commands = len(command_invocations)
            print(
                f"{num_of_commands} command invocation(s) found for instance {instance_id}."
            )

            if num_of_commands > 10:
                print("Displaying the first 10 commands:")
                num_of_commands = 10
            date_format = "%A, %d %B %Y %I:%M%p"
            for command in command_invocations[:num_of_commands]:
                print(
                    f"   The time of command invocation is {command['RequestedDateTime'].strftime(date_format)}"
                )
        except ClientError as err:
            logger.error(
                "Couldn't list commands for %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
OpsItem 작업을 래핑하는 클래스를 정의합니다.  

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, title, source, category, severity, description):
        """
        Create an OpsItem

        :param title: The OpsItem title.
        :param source: The OpsItem source.
        :param category: The OpsItem category.
        :param severity: The OpsItem severity.
        :param description: The OpsItem description.

        """
        try:
            response = self.ssm_client.create_ops_item(
                Title=title,
                Source=source,
                Category=category,
                Severity=severity,
                Description=description,
            )
            self.id = response["OpsItemId"]
        except self.ssm_client.exceptions.OpsItemLimitExceededException as err:
            logger.error(
                "Couldn't create ops item because you have exceeded your open OpsItem limit. "
                "Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create ops item %s. Here's why: %s: %s",
                title,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

    def delete(self):
        """
        Delete the OpsItem.
        """
        if self.id is None:
            return
        try:
            self.ssm_client.delete_ops_item(OpsItemId=self.id)
            print(f"Deleted ops item with id {self.id}")
            self.id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def describe(self):
        """
        Describe an OpsItem.
        """
        try:
            paginator = self.ssm_client.get_paginator("describe_ops_items")
            ops_items = []
            for page in paginator.paginate(
                OpsItemFilters=[
                    {"Key": "OpsItemId", "Values": [self.id], "Operator": "Equal"}
                ]
            ):
                ops_items.extend(page["OpsItemSummaries"])

            for item in ops_items:
                print(
                    f"The item title is {item['Title']} and the status is {item['Status']}"
                )
            return len(ops_items) > 0
        except ClientError as err:
            logger.error(
                "Couldn't describe ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def update(self, title=None, description=None, status=None):
        """
        Update an OpsItem.

        :param title: The new OpsItem title.
        :param description: The new OpsItem description.
        :param status: The new OpsItem status.
        :return:
        """
        args = dict(OpsItemId=self.id)
        if title is not None:
            args["Title"] = title
        if description is not None:
            args["Description"] = description
        if status is not None:
            args["Status"] = status
        try:
            self.ssm_client.update_ops_item(**args)
        except ClientError as err:
            logger.error(
                "Couldn't update ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
유지 관리 기간 작업을 래핑하는 클래스를 정의합니다.  

```
class MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, name, schedule, duration, cutoff, allow_unassociated_targets):
        """
        Create an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            response = self.ssm_client.create_maintenance_window(
                Name=name,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.window_id = response["WindowId"]
            self.name = name
            logger.info("Created maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to create maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create maintenance window %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete(self):
        """
        Delete the associated AWS Systems Manager maintenance window.
        """
        if self.window_id is None:
            return

        try:
            self.ssm_client.delete_maintenance_window(WindowId=self.window_id)
            logger.info("Deleted maintenance window %s.", self.window_id)
            print(f"Deleted maintenance window {self.name}")
            self.window_id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete maintenance window %s. Here's why: %s: %s",
                self.window_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def update(
        self, name, enabled, schedule, duration, cutoff, allow_unassociated_targets
    ):
        """
        Update an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param enabled: Whether the maintenance window is enabled to run on managed nodes.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            self.ssm_client.update_maintenance_window(
                WindowId=self.window_id,
                Name=name,
                Enabled=enabled,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.name = name
            logger.info("Updated maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to update maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't update maintenance window %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+ API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 다음 주제를 참조하세요.
  + [CreateDocument](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateDocument)
  + [CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateMaintenanceWindow)
  + [CreateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateOpsItem)
  + [DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteMaintenanceWindow)
  + [ListCommandInvocations](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/ListCommandInvocations)
  + [SendCommand](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/SendCommand)
  + [UpdateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/UpdateOpsItem)

------

# AWS SDKs를 사용하는 Systems Manager에 대한 작업
<a name="ssm_code_examples_actions"></a>

다음 코드 예제에서는 AWS SDKs를 사용하여 개별 Systems Manager 작업을 수행하는 방법을 보여줍니다. 각 예시에는 GitHub에 대한 링크가 포함되어 있습니다. 여기에서 코드 설정 및 실행에 대한 지침을 찾을 수 있습니다.

 다음 예제에는 가장 일반적으로 사용되는 작업만 포함되어 있습니다. 전체 목록은 [AWS Systems Manager API 참조](https://docs.aws.amazon.com/systems-manager/latest/APIReference/Welcome.html)를 참조하세요.

**Topics**
+ [`AddTagsToResource`](ssm_example_ssm_AddTagsToResource_section.md)
+ [`CancelCommand`](ssm_example_ssm_CancelCommand_section.md)
+ [`CreateActivation`](ssm_example_ssm_CreateActivation_section.md)
+ [`CreateAssociation`](ssm_example_ssm_CreateAssociation_section.md)
+ [`CreateAssociationBatch`](ssm_example_ssm_CreateAssociationBatch_section.md)
+ [`CreateDocument`](ssm_example_ssm_CreateDocument_section.md)
+ [`CreateMaintenanceWindow`](ssm_example_ssm_CreateMaintenanceWindow_section.md)
+ [`CreateOpsItem`](ssm_example_ssm_CreateOpsItem_section.md)
+ [`CreatePatchBaseline`](ssm_example_ssm_CreatePatchBaseline_section.md)
+ [`DeleteActivation`](ssm_example_ssm_DeleteActivation_section.md)
+ [`DeleteAssociation`](ssm_example_ssm_DeleteAssociation_section.md)
+ [`DeleteDocument`](ssm_example_ssm_DeleteDocument_section.md)
+ [`DeleteMaintenanceWindow`](ssm_example_ssm_DeleteMaintenanceWindow_section.md)
+ [`DeleteOpsItem`](ssm_example_ssm_DeleteOpsItem_section.md)
+ [`DeleteParameter`](ssm_example_ssm_DeleteParameter_section.md)
+ [`DeletePatchBaseline`](ssm_example_ssm_DeletePatchBaseline_section.md)
+ [`DeregisterManagedInstance`](ssm_example_ssm_DeregisterManagedInstance_section.md)
+ [`DeregisterPatchBaselineForPatchGroup`](ssm_example_ssm_DeregisterPatchBaselineForPatchGroup_section.md)
+ [`DeregisterTargetFromMaintenanceWindow`](ssm_example_ssm_DeregisterTargetFromMaintenanceWindow_section.md)
+ [`DeregisterTaskFromMaintenanceWindow`](ssm_example_ssm_DeregisterTaskFromMaintenanceWindow_section.md)
+ [`DescribeActivations`](ssm_example_ssm_DescribeActivations_section.md)
+ [`DescribeAssociation`](ssm_example_ssm_DescribeAssociation_section.md)
+ [`DescribeAssociationExecutionTargets`](ssm_example_ssm_DescribeAssociationExecutionTargets_section.md)
+ [`DescribeAssociationExecutions`](ssm_example_ssm_DescribeAssociationExecutions_section.md)
+ [`DescribeAutomationExecutions`](ssm_example_ssm_DescribeAutomationExecutions_section.md)
+ [`DescribeAutomationStepExecutions`](ssm_example_ssm_DescribeAutomationStepExecutions_section.md)
+ [`DescribeAvailablePatches`](ssm_example_ssm_DescribeAvailablePatches_section.md)
+ [`DescribeDocument`](ssm_example_ssm_DescribeDocument_section.md)
+ [`DescribeDocumentPermission`](ssm_example_ssm_DescribeDocumentPermission_section.md)
+ [`DescribeEffectiveInstanceAssociations`](ssm_example_ssm_DescribeEffectiveInstanceAssociations_section.md)
+ [`DescribeEffectivePatchesForPatchBaseline`](ssm_example_ssm_DescribeEffectivePatchesForPatchBaseline_section.md)
+ [`DescribeInstanceAssociationsStatus`](ssm_example_ssm_DescribeInstanceAssociationsStatus_section.md)
+ [`DescribeInstanceInformation`](ssm_example_ssm_DescribeInstanceInformation_section.md)
+ [`DescribeInstancePatchStates`](ssm_example_ssm_DescribeInstancePatchStates_section.md)
+ [`DescribeInstancePatchStatesForPatchGroup`](ssm_example_ssm_DescribeInstancePatchStatesForPatchGroup_section.md)
+ [`DescribeInstancePatches`](ssm_example_ssm_DescribeInstancePatches_section.md)
+ [`DescribeMaintenanceWindowExecutionTaskInvocations`](ssm_example_ssm_DescribeMaintenanceWindowExecutionTaskInvocations_section.md)
+ [`DescribeMaintenanceWindowExecutionTasks`](ssm_example_ssm_DescribeMaintenanceWindowExecutionTasks_section.md)
+ [`DescribeMaintenanceWindowExecutions`](ssm_example_ssm_DescribeMaintenanceWindowExecutions_section.md)
+ [`DescribeMaintenanceWindowTargets`](ssm_example_ssm_DescribeMaintenanceWindowTargets_section.md)
+ [`DescribeMaintenanceWindowTasks`](ssm_example_ssm_DescribeMaintenanceWindowTasks_section.md)
+ [`DescribeMaintenanceWindows`](ssm_example_ssm_DescribeMaintenanceWindows_section.md)
+ [`DescribeOpsItems`](ssm_example_ssm_DescribeOpsItems_section.md)
+ [`DescribeParameters`](ssm_example_ssm_DescribeParameters_section.md)
+ [`DescribePatchBaselines`](ssm_example_ssm_DescribePatchBaselines_section.md)
+ [`DescribePatchGroupState`](ssm_example_ssm_DescribePatchGroupState_section.md)
+ [`DescribePatchGroups`](ssm_example_ssm_DescribePatchGroups_section.md)
+ [`GetAutomationExecution`](ssm_example_ssm_GetAutomationExecution_section.md)
+ [`GetCommandInvocation`](ssm_example_ssm_GetCommandInvocation_section.md)
+ [`GetConnectionStatus`](ssm_example_ssm_GetConnectionStatus_section.md)
+ [`GetDefaultPatchBaseline`](ssm_example_ssm_GetDefaultPatchBaseline_section.md)
+ [`GetDeployablePatchSnapshotForInstance`](ssm_example_ssm_GetDeployablePatchSnapshotForInstance_section.md)
+ [`GetDocument`](ssm_example_ssm_GetDocument_section.md)
+ [`GetInventory`](ssm_example_ssm_GetInventory_section.md)
+ [`GetInventorySchema`](ssm_example_ssm_GetInventorySchema_section.md)
+ [`GetMaintenanceWindow`](ssm_example_ssm_GetMaintenanceWindow_section.md)
+ [`GetMaintenanceWindowExecution`](ssm_example_ssm_GetMaintenanceWindowExecution_section.md)
+ [`GetMaintenanceWindowExecutionTask`](ssm_example_ssm_GetMaintenanceWindowExecutionTask_section.md)
+ [`GetParameter`](ssm_example_ssm_GetParameter_section.md)
+ [`GetParameterHistory`](ssm_example_ssm_GetParameterHistory_section.md)
+ [`GetParameters`](ssm_example_ssm_GetParameters_section.md)
+ [`GetPatchBaseline`](ssm_example_ssm_GetPatchBaseline_section.md)
+ [`GetPatchBaselineForPatchGroup`](ssm_example_ssm_GetPatchBaselineForPatchGroup_section.md)
+ [`ListAssociationVersions`](ssm_example_ssm_ListAssociationVersions_section.md)
+ [`ListAssociations`](ssm_example_ssm_ListAssociations_section.md)
+ [`ListCommandInvocations`](ssm_example_ssm_ListCommandInvocations_section.md)
+ [`ListCommands`](ssm_example_ssm_ListCommands_section.md)
+ [`ListComplianceItems`](ssm_example_ssm_ListComplianceItems_section.md)
+ [`ListComplianceSummaries`](ssm_example_ssm_ListComplianceSummaries_section.md)
+ [`ListDocumentVersions`](ssm_example_ssm_ListDocumentVersions_section.md)
+ [`ListDocuments`](ssm_example_ssm_ListDocuments_section.md)
+ [`ListInventoryEntries`](ssm_example_ssm_ListInventoryEntries_section.md)
+ [`ListResourceComplianceSummaries`](ssm_example_ssm_ListResourceComplianceSummaries_section.md)
+ [`ListTagsForResource`](ssm_example_ssm_ListTagsForResource_section.md)
+ [`ModifyDocumentPermission`](ssm_example_ssm_ModifyDocumentPermission_section.md)
+ [`PutComplianceItems`](ssm_example_ssm_PutComplianceItems_section.md)
+ [`PutInventory`](ssm_example_ssm_PutInventory_section.md)
+ [`PutParameter`](ssm_example_ssm_PutParameter_section.md)
+ [`RegisterDefaultPatchBaseline`](ssm_example_ssm_RegisterDefaultPatchBaseline_section.md)
+ [`RegisterPatchBaselineForPatchGroup`](ssm_example_ssm_RegisterPatchBaselineForPatchGroup_section.md)
+ [`RegisterTargetWithMaintenanceWindow`](ssm_example_ssm_RegisterTargetWithMaintenanceWindow_section.md)
+ [`RegisterTaskWithMaintenanceWindow`](ssm_example_ssm_RegisterTaskWithMaintenanceWindow_section.md)
+ [`RemoveTagsFromResource`](ssm_example_ssm_RemoveTagsFromResource_section.md)
+ [`SendCommand`](ssm_example_ssm_SendCommand_section.md)
+ [`StartAutomationExecution`](ssm_example_ssm_StartAutomationExecution_section.md)
+ [`StartSession`](ssm_example_ssm_StartSession_section.md)
+ [`StopAutomationExecution`](ssm_example_ssm_StopAutomationExecution_section.md)
+ [`UpdateAssociation`](ssm_example_ssm_UpdateAssociation_section.md)
+ [`UpdateAssociationStatus`](ssm_example_ssm_UpdateAssociationStatus_section.md)
+ [`UpdateDocument`](ssm_example_ssm_UpdateDocument_section.md)
+ [`UpdateDocumentDefaultVersion`](ssm_example_ssm_UpdateDocumentDefaultVersion_section.md)
+ [`UpdateMaintenanceWindow`](ssm_example_ssm_UpdateMaintenanceWindow_section.md)
+ [`UpdateManagedInstanceRole`](ssm_example_ssm_UpdateManagedInstanceRole_section.md)
+ [`UpdateOpsItem`](ssm_example_ssm_UpdateOpsItem_section.md)
+ [`UpdatePatchBaseline`](ssm_example_ssm_UpdatePatchBaseline_section.md)

# CLI로 `AddTagsToResource` 사용
<a name="ssm_example_ssm_AddTagsToResource_section"></a>

다음 코드 예시는 `AddTagsToResource`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 유지 관리 기간에 태그를 추가하는 방법**  
다음 `add-tags-to-resource` 예제에서는 지정된 유지 관리 기간에 태그를 추가합니다.  

```
aws ssm add-tags-to-resource \
    --resource-type "MaintenanceWindow" \
    --resource-id "mw-03eb9db428EXAMPLE" \
    --tags "Key=Stack,Value=Production"
```
이 명령은 출력을 생성하지 않습니다.  
**예제 2: 파라미터에 태그를 추가하는 방법**  
다음 `add-tags-to-resource` 예제에서는 지정된 파라미터에 두 개의 태그를 추가합니다.  

```
aws ssm add-tags-to-resource \
    --resource-type "Parameter" \
    --resource-id "My-Parameter" \
    --tags '[{"Key":"Region","Value":"East"},{"Key":"Environment", "Value":"Production"}]'
```
이 명령은 출력을 생성하지 않습니다.  
**예제 3: SSM 문서에 태그를 추가하는 방법**  
다음 `add-tags-to-resource` 예제에서는 지정된 문서에 태그를 추가합니다.  

```
aws ssm add-tags-to-resource \
    --resource-type "Document" \
    --resource-id "My-Document" \
    --tags "Key=Quarter,Value=Q322"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 리소스 태그 지정](https://docs.aws.amazon.com/systems-manager/latest/userguide/tagging-resources.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [AddTagsToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/add-tags-to-resource.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간을 새 태그로 업데이트합니다. 명령이 성공해도 출력은 없습니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$option1 = @{Key="Stack";Value=@("Production")}
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $option1
```
**예제 2: PowerShell 버전 2에서 각 태그를 생성하려면 New-Object를 사용해야 합니다. 명령이 성공해도 출력은 없습니다.**  

```
$tag1 = New-Object Amazon.SimpleSystemsManagement.Model.Tag
$tag1.Key = "Stack"
$tag1.Value = "Production"
		
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $tag1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [AddTagsToResource](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간을 새 태그로 업데이트합니다. 명령이 성공해도 출력은 없습니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$option1 = @{Key="Stack";Value=@("Production")}
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $option1
```
**예제 2: PowerShell 버전 2에서 각 태그를 생성하려면 New-Object를 사용해야 합니다. 명령이 성공해도 출력은 없습니다.**  

```
$tag1 = New-Object Amazon.SimpleSystemsManagement.Model.Tag
$tag1.Key = "Stack"
$tag1.Value = "Production"
		
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $tag1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AddTagsToResource](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `CancelCommand` 사용
<a name="ssm_example_ssm_CancelCommand_section"></a>

다음 코드 예시는 `CancelCommand`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 모든 인스턴스에 대한 명령을 취소하는 방법**  
다음 `cancel-command` 예제에서는 모든 인스턴스에 대해 이미 실행 중인 지정된 명령을 취소하려고 시도합니다.  

```
aws ssm cancel-command \
    --command-id "662add3d-5831-4a10-b64a-f2ff3EXAMPLE"
```
이 명령은 출력을 생성하지 않습니다.  
**예제 2: 특정 인스턴스의 명령을 취소하는 방법**  
다음 `cancel-command` 예제에서는 지정된 인스턴스에 대한 명령만 취소하려고 시도합니다.  

```
aws ssm cancel-command \
    --command-id "662add3d-5831-4a10-b64a-f2ff3EXAMPLE"
    --instance-ids "i-02573cafcfEXAMPLE"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 파라미터 태그 지정](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-tag.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CancelCommand](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/cancel-command.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 명령 취소를 시도합니다. 작업이 성공해도 출력은 없습니다.**  

```
Stop-SSMCommand -CommandId "9ded293e-e792-4440-8e3e-7b8ec5feaa38"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CancelCommand](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 명령 취소를 시도합니다. 작업이 성공해도 출력은 없습니다.**  

```
Stop-SSMCommand -CommandId "9ded293e-e792-4440-8e3e-7b8ec5feaa38"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CancelCommand](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `CreateActivation` 사용
<a name="ssm_example_ssm_CreateActivation_section"></a>

다음 코드 예시는 `CreateActivation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**관리형 인스턴스 활성화를 생성하는 방법**  
다음 `create-activation` 예제에서는 관리형 인스턴스 활성화를 생성합니다.  

```
aws ssm create-activation \
    --default-instance-name "HybridWebServers" \
    --iam-role "HybridWebServersRole" \
    --registration-limit 5
```
출력:  

```
{
    "ActivationId": "5743558d-563b-4457-8682-d16c3EXAMPLE",
    "ActivationCode": "dRmgnYaFv567vEXAMPLE"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [4단계: 하이브리드 환경을 위한 관리형 인스턴스 활성화 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-managed-instance-activation.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateActivation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-activation.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 관리형 인스턴스를 생성합니다.**  

```
New-SSMActivation -DefaultInstanceName "MyWebServers" -IamRole "SSMAutomationRole" -RegistrationLimit 10
```
**출력:**  

```
ActivationCode       ActivationId
--------------       ------------
KWChhOxBTiwDcKE9BlKC 08e51e79-1e36-446c-8e63-9458569c1363
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateActivation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 관리형 인스턴스를 생성합니다.**  

```
New-SSMActivation -DefaultInstanceName "MyWebServers" -IamRole "SSMAutomationRole" -RegistrationLimit 10
```
**출력:**  

```
ActivationCode       ActivationId
--------------       ------------
KWChhOxBTiwDcKE9BlKC 08e51e79-1e36-446c-8e63-9458569c1363
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateActivation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `CreateAssociation` 사용
<a name="ssm_example_ssm_CreateAssociation_section"></a>

다음 코드 예시는 `CreateAssociation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 인스턴스 ID를 사용하여 문서를 연결하는 방법**  
이 예제에서는 인스턴스 ID를 사용하여 구성 문서를 인스턴스와 연결합니다.  

```
aws ssm create-association \
    --instance-id "i-0cb2b964d3e14fd9f" \
    --name "AWS-UpdateSSMAgent"
```
출력:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487875500.33,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-0cb2b964d3e14fd9f",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487875500.33,
        "Date": 1487875500.33,
        "Targets": [
            {
                "Values": [
                    "i-0cb2b964d3e14fd9f"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
자세한 내용은 **AWS Systems Manager API 참조의 [CreateAssociation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html)을 참조하세요.  
**예제 2: 대상을 사용하여 문서를 연결하는 방법**  
이 예제에서는 대상을 사용하여 구성 문서를 인스턴스와 연결합니다.  

```
aws ssm create-association \
    --name "AWS-UpdateSSMAgent" \
    --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f"
```
출력:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487875500.33,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-0cb2b964d3e14fd9f",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487875500.33,
        "Date": 1487875500.33,
        "Targets": [
            {
                "Values": [
                    "i-0cb2b964d3e14fd9f"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
자세한 내용은 **AWS Systems Manager API 참조의 [CreateAssociation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html)을 참조하세요.  
**예제 3: 한 번만 실행되는 연결을 생성하는 방법**  
이 예제에서는 지정된 날짜 및 시간에 한 번만 실행되는 새 연결을 생성합니다. 과거 또는 현재 날짜(처리 시점을 기준으로 해당 날짜가 과거임)에 생성된 연결은 즉시 실행됩니다.  

```
aws ssm create-association \
    --name "AWS-UpdateSSMAgent" \
    --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \
    --schedule-expression "at(2020-05-14T15:55:00)"  \
    --apply-only-at-cron-interval
```
출력:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487875500.33,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-0cb2b964d3e14fd9f",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487875500.33,
        "Date": 1487875500.33,
        "Targets": [
            {
                "Values": [
                    "i-0cb2b964d3e14fd9f"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
자세한 내용은 **AWS Systems Manager API 참조의 [CreateAssociation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html) 또는 **AWS Systems Manager 사용 설명서의 [참조: Systems Manager의 Cron 및 Rate 표현식](https://docs.aws.amazon.com/systems-manager/latest/userguide/reference-cron-and-rate-expressions.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-association.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스 ID를 사용하여 구성 문서를 인스턴스와 연결합니다.**  

```
New-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Associated
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : Associated with AWS-UpdateSSMAgent
Status.AdditionalInfo :
```
**예제 2: 이 예제에서는 대상을 사용하여 구성 문서를 인스턴스와 연결합니다.**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
New-SSMAssociation -Name "AWS-UpdateSSMAgent" -Target $target
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**예제 3: 이 예제는 대상과 파라미터를 사용하여 구성 문서를 인스턴스와 연결합니다.**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
$params = @{
  "action"="configure"
  "mode"="ec2"
  "optionalConfigurationSource"="ssm"
  "optionalConfigurationLocation"=""
  "optionalRestart"="yes"
}
New-SSMAssociation -Name "Configure-CloudWatch" -AssociationName "CWConfiguration" -Target $target -Parameter $params
```
**출력:**  

```
Name                  : Configure-CloudWatch
InstanceId            :
Date                  : 5/17/2018 3:17:44 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**예제 4: 이 예제에서는 `AWS-GatherSoftwareInventory`를 사용하여 리전에 있는 모든 인스턴스와의 연결을 생성합니다. 또한 파라미터에서 수집할 사용자 지정 파일 및 레지스트리 위치도 제공합니다.**  

```
$params = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$params["windowsRegistry"] ='[{"Path":"HKEY_LOCAL_MACHINE\SOFTWARE\Amazon\MachineImage","Recursive":false,"ValueNames":["AMIName"]}]'
$params["files"] = '[{"Path":"C:\Program Files","Pattern":["*.exe"],"Recursive":true}, {"Path":"C:\ProgramData","Pattern":["*.log"],"Recursive":true}]' 
New-SSMAssociation -AssociationName new-in-mum -Name AWS-GatherSoftwareInventory -Target @{Key="instanceids";Values="*"} -Parameter $params -region ap-south-1 -ScheduleExpression "rate(720 minutes)"
```
**출력:**  

```
Name                  : AWS-GatherSoftwareInventory
InstanceId            :
Date                  : 6/9/2019 8:57:56 AM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateAssociation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스 ID를 사용하여 구성 문서를 인스턴스와 연결합니다.**  

```
New-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Associated
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : Associated with AWS-UpdateSSMAgent
Status.AdditionalInfo :
```
**예제 2: 이 예제에서는 대상을 사용하여 구성 문서를 인스턴스와 연결합니다.**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
New-SSMAssociation -Name "AWS-UpdateSSMAgent" -Target $target
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**예제 3: 이 예제는 대상과 파라미터를 사용하여 구성 문서를 인스턴스와 연결합니다.**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
$params = @{
  "action"="configure"
  "mode"="ec2"
  "optionalConfigurationSource"="ssm"
  "optionalConfigurationLocation"=""
  "optionalRestart"="yes"
}
New-SSMAssociation -Name "Configure-CloudWatch" -AssociationName "CWConfiguration" -Target $target -Parameter $params
```
**출력:**  

```
Name                  : Configure-CloudWatch
InstanceId            :
Date                  : 5/17/2018 3:17:44 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**예제 4: 이 예제에서는 `AWS-GatherSoftwareInventory`를 사용하여 리전에 있는 모든 인스턴스와의 연결을 생성합니다. 또한 파라미터에서 수집할 사용자 지정 파일 및 레지스트리 위치도 제공합니다.**  

```
$params = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$params["windowsRegistry"] ='[{"Path":"HKEY_LOCAL_MACHINE\SOFTWARE\Amazon\MachineImage","Recursive":false,"ValueNames":["AMIName"]}]'
$params["files"] = '[{"Path":"C:\Program Files","Pattern":["*.exe"],"Recursive":true}, {"Path":"C:\ProgramData","Pattern":["*.log"],"Recursive":true}]' 
New-SSMAssociation -AssociationName new-in-mum -Name AWS-GatherSoftwareInventory -Target @{Key="instanceids";Values="*"} -Parameter $params -region ap-south-1 -ScheduleExpression "rate(720 minutes)"
```
**출력:**  

```
Name                  : AWS-GatherSoftwareInventory
InstanceId            :
Date                  : 6/9/2019 8:57:56 AM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `CreateAssociationBatch` 사용
<a name="ssm_example_ssm_CreateAssociationBatch_section"></a>

다음 코드 예시는 `CreateAssociationBatch`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**다중 연결을 생성하는 방법**  
이 예제에서는 구성 문서를 여러 인스턴스와 연결합니다. 출력은 해당하는 경우 성공한 작업과 실패한 작업의 목록을 반환합니다.  
명령:  

```
aws ssm create-association-batch --entries "Name=AWS-UpdateSSMAgent,InstanceId=i-1234567890abcdef0" "Name=AWS-UpdateSSMAgent,InstanceId=i-9876543210abcdef0"
```
출력:  

```
{
  "Successful": [
      {
          "Name": "AWS-UpdateSSMAgent",
          "InstanceId": "i-1234567890abcdef0",
          "AssociationVersion": "1",
          "Date": 1550504725.007,
          "LastUpdateAssociationDate": 1550504725.007,
          "Status": {
              "Date": 1550504725.007,
              "Name": "Associated",
              "Message": "Associated with AWS-UpdateSSMAgent"
          },
          "Overview": {
              "Status": "Pending",
              "DetailedStatus": "Creating"
          },
          "DocumentVersion": "$DEFAULT",
          "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
          "Targets": [
              {
                  "Key": "InstanceIds",
                  "Values": [
                      "i-1234567890abcdef0"
                  ]
              }
          ]
      },
      {
          "Name": "AWS-UpdateSSMAgent",
          "InstanceId": "i-9876543210abcdef0",
          "AssociationVersion": "1",
          "Date": 1550504725.057,
          "LastUpdateAssociationDate": 1550504725.057,
          "Status": {
              "Date": 1550504725.057,
              "Name": "Associated",
              "Message": "Associated with AWS-UpdateSSMAgent"
          },
          "Overview": {
              "Status": "Pending",
              "DetailedStatus": "Creating"
          },
          "DocumentVersion": "$DEFAULT",
          "AssociationId": "9c9f7f20-5154-4fed-a83e-0123456789ab",
          "Targets": [
              {
                  "Key": "InstanceIds",
                  "Values": [
                      "i-9876543210abcdef0"
                  ]
              }
          ]
      }
  ],
  "Failed": []
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateAssociationBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-association-batch.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 구성 문서를 여러 인스턴스와 연결합니다. 출력은 해당하는 경우 성공한 작업과 실패한 작업의 목록을 반환합니다.**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
New-SSMAssociationFromBatch -Entry $option1,$option2
```
**출력:**  

```
Failed  Successful
------  ----------
{}      {Amazon.SimpleSystemsManagement.Model.FailedCreateAssociation, Amazon.SimpleSystemsManagement.Model.FailedCreateAsso...
```
**예제 2: 이 예제에서는 성공한 작업의 전체 세부 정보를 보여줍니다.**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
(New-SSMAssociationFromBatch -Entry $option1,$option2).Successful
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateAssociationBatch](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 구성 문서를 여러 인스턴스와 연결합니다. 출력은 해당하는 경우 성공한 작업과 실패한 작업의 목록을 반환합니다.**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
New-SSMAssociationFromBatch -Entry $option1,$option2
```
**출력:**  

```
Failed  Successful
------  ----------
{}      {Amazon.SimpleSystemsManagement.Model.FailedCreateAssociation, Amazon.SimpleSystemsManagement.Model.FailedCreateAsso...
```
**예제 2: 이 예제에서는 성공한 작업의 전체 세부 정보를 보여줍니다.**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
(New-SSMAssociationFromBatch -Entry $option1,$option2).Successful
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateAssociationBatch](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `CreateDocument` 함께 사용
<a name="ssm_example_ssm_CreateDocument_section"></a>

다음 코드 예시는 `CreateDocument`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md) 

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

**AWS CLI**  
**문서를 생성하는 방법**  
다음 `create-document` 예제에서는 Systems Manager 문서를 생성합니다.  

```
aws ssm create-document \
    --content file://exampleDocument.yml \
    --name "Example" \
    --document-type "Automation" \
    --document-format YAML
```
출력:  

```
{
    "DocumentDescription": {
        "Hash": "fc2410281f40779e694a8b95975d0f9f316da8a153daa94e3d9921102EXAMPLE",
        "HashType": "Sha256",
        "Name": "Example",
        "Owner": "29884EXAMPLE",
        "CreatedDate": 1583256349.452,
        "Status": "Creating",
        "DocumentVersion": "1",
        "Description": "Document Example",
        "Parameters": [
            {
                "Name": "AutomationAssumeRole",
                "Type": "String",
                "Description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.",
                "DefaultValue": ""
            },
            {
                "Name": "InstanceId",
                "Type": "String",
                "Description": "(Required) The ID of the Amazon EC2 instance.",
                "DefaultValue": ""
            }
        ],
        "PlatformTypes": [
            "Windows",
            "Linux"
        ],
        "DocumentType": "Automation",
        "SchemaVersion": "0.3",
        "LatestVersion": "1",
        "DefaultVersion": "1",
        "DocumentFormat": "YAML",
        "Tags": []
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 문서 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-document.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Creates an AWS SSM document asynchronously.
     *
     * @param docName The name of the document to create.
     * <p>
     * This method initiates an asynchronous request to create an SSM document.
     * If the request is successful, it prints the document status.
     * If an exception occurs, it handles the error appropriately.
     */
    public void createSSMDoc(String docName) throws SsmException {
        String jsonData = """
        {
        "schemaVersion": "2.2",
        "description": "Run a simple shell command",
        "mainSteps": [
            {
                "action": "aws:runShellScript",
                "name": "runEchoCommand",
                "inputs": {
                  "runCommand": [
                    "echo 'Hello, world!'"
                  ]
                }
              }
            ]
        }
        """;

        CreateDocumentRequest request = CreateDocumentRequest.builder()
                .content(jsonData)
                .name(docName)
                .documentType(DocumentType.COMMAND)
                .build();

        CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request);
        future.thenAccept(response -> {
            System.out.println("The status of the SSM document is " + response.documentDescription().status());
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof DocumentAlreadyExistsException) {
                throw new CompletionException(cause);
            } else if (cause instanceof SsmException) {
                throw new CompletionException(cause);
            } else {
                throw new RuntimeException(cause);
            }
        }).join();
    }
```
+  API 세부 정보는 **AWS SDK for Java 2.x API 참조의 [CreateDocument](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateDocument)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { CreateDocumentCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Create an SSM document.
 * @param {{ content: string, name: string, documentType?: DocumentType }}
 */
export const main = async ({ content, name, documentType }) => {
  const client = new SSMClient({});
  try {
    const { documentDescription } = await client.send(
      new CreateDocumentCommand({
        Content: content, // The content for the new SSM document. The content must not exceed 64KB.
        Name: name,
        DocumentType: documentType, // Document format type can be JSON, YAML, or TEXT. The default format is JSON.
      }),
    );
    console.log("Document created successfully.");
    return { DocumentDescription: documentDescription };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "DocumentAlreadyExists") {
      console.warn(`${caught.message}. Did you provide a new document name?`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [CreateDocument](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateDocumentCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 계정에서 문서를 생성합니다. 문서는 JSON 형식이어야 합니다. 구성 문서 작성에 대한 자세한 내용은 SSM API 참조의 구성 문서를 참조하세요.**  

```
New-SSMDocument -Content (Get-Content -Raw "c:\temp\RunShellScript.json") -Name "RunShellScript" -DocumentType "Command"
```
**출력:**  

```
CreatedDate     : 3/1/2017 1:21:33 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Creating
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateDocument](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 계정에서 문서를 생성합니다. 문서는 JSON 형식이어야 합니다. 구성 문서 작성에 대한 자세한 내용은 SSM API 참조의 구성 문서를 참조하세요.**  

```
New-SSMDocument -Content (Get-Content -Raw "c:\temp\RunShellScript.json") -Name "RunShellScript" -DocumentType "Command"
```
**출력:**  

```
CreatedDate     : 3/1/2017 1:21:33 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Creating
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateDocument](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 create(self, content, name):
        """
        Creates a document.

        :param content: The content of the document.
        :param name: The name of the document.
        """
        try:
            self.ssm_client.create_document(
                Name=name, Content=content, DocumentType="Command"
            )
            self.name = name
        except self.ssm_client.exceptions.DocumentAlreadyExists:
            print(f"Document {name} already exists.")
            self.name = name
        except ClientError as err:
            logger.error(
                "Couldn't create %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateDocument](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateDocument)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ssm->createdocument(
            iv_name = iv_name
            iv_content = iv_content
            iv_documenttype = 'Command' ).
        MESSAGE 'Document created.' TYPE 'I'.
      CATCH /aws1/cx_ssmdocalreadyexists.
        MESSAGE 'Document already exists.' TYPE 'I'.
      CATCH /aws1/cx_ssminvaliddoccontent.
        MESSAGE 'Invalid document content.' TYPE 'I'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateDocument](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# AWS SDK 또는 CLI와 `CreateMaintenanceWindow` 함께 사용
<a name="ssm_example_ssm_CreateMaintenanceWindow_section"></a>

다음 코드 예시는 `CreateMaintenanceWindow`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md) 

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

**AWS CLI**  
**예제 1: 유지 관리 기간을 생성하는 방법**  
다음 `create-maintenance-window` 예제에서는 필요한 경우 5분마다 최대 2시간 동안 유지 관리 기간 실행 종료 1시간 이내에 새 작업 시작을 방지하는 새 유지 관리 기간을 생성하고, 연결되지 않은 대상(유지 관리 기간에 등록되지 않은 인스턴스)을 허용하며, 생성자가 자습서에서 사용하려는 사용자 지정 태그 사용을 통해 이를 나타냅니다.  

```
aws ssm create-maintenance-window \
    --name "My-Tutorial-Maintenance-Window" \
    --schedule "rate(5 minutes)" \
    --duration 2 --cutoff 1 \
    --allow-unassociated-targets \
    --tags "Key=Purpose,Value=Tutorial"
```
출력:  

```
{
    "WindowId": "mw-0c50858d01EXAMPLE"
}
```
**예제 2: 한 번만 실행되는 유지 관리 기간을 생성하는 방법**  
다음 `create-maintenance-window` 예제에서는 지정된 날짜 및 시간에 한 번만 실행되는 새 유지 관리 기간을 생성합니다.  

```
aws ssm create-maintenance-window \
    --name My-One-Time-Maintenance-Window \
    --schedule "at(2020-05-14T15:55:00)" \
    --duration 5 \
    --cutoff 2 \
    --allow-unassociated-targets \
    --tags "Key=Environment,Value=Production"
```
출력:  

```
{
    "WindowId": "mw-01234567890abcdef"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [유지 관리 기간](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-maintenance.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-maintenance-window.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Creates an SSM maintenance window asynchronously.
     *
     * @param winName The name of the maintenance window.
     * @return The ID of the created or existing maintenance window.
     * <p>
     * This method initiates an asynchronous request to create an SSM maintenance window.
     * If the request is successful, it prints the maintenance window ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException {
        CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder()
                .name(winName)
                .description("This is my maintenance window")
                .allowUnassociatedTargets(true)
                .duration(2)
                .cutoff(1)
                .schedule("cron(0 10 ? * MON-FRI *)")
                .build();

        CompletableFuture<CreateMaintenanceWindowResponse> future = getAsyncClient().createMaintenanceWindow(request);
        final String[] windowId = {null};
        future.whenComplete((response, ex) -> {
            if (response != null) {
                String maintenanceWindowId = response.windowId();
                System.out.println("The maintenance window id is " + maintenanceWindowId);
                windowId[0] = maintenanceWindowId;
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof DocumentAlreadyExistsException) {
                    throw new CompletionException(cause);
                } else if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();

        if (windowId[0] == null) {
            MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder()
                    .key("name")
                    .values(winName)
                    .build();

            DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder()
                    .filters(filter)
                    .build();

            CompletableFuture<DescribeMaintenanceWindowsResponse> describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest);
            describeFuture.whenComplete((describeResponse, describeEx) -> {
                if (describeResponse != null) {
                    List<MaintenanceWindowIdentity> windows = describeResponse.windowIdentities();
                    if (!windows.isEmpty()) {
                        windowId[0] = windows.get(0).windowId();
                        System.out.println("Window ID: " + windowId[0]);
                    } else {
                        System.out.println("Window not found.");
                        windowId[0] = "";
                    }
                } else {
                    Throwable describeCause = (describeEx instanceof CompletionException) ? describeEx.getCause() : describeEx;
                    throw new RuntimeException("Error describing maintenance windows: " + describeCause.getMessage(), describeCause);
                }
            }).join();
        }

        return windowId[0];
    }
```
+  API 세부 정보는 **AWS SDK for Java 2.x API 참조의 [CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateMaintenanceWindow)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { CreateMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Create an SSM maintenance window.
 * @param {{ name: string, allowUnassociatedTargets: boolean, duration: number, cutoff: number, schedule: string, description?: string }}
 */
export const main = async ({
  name,
  allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
  duration, // The duration of the maintenance window in hours.
  cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution.
  schedule, // The schedule of the maintenance window in the form of a cron or rate expression.
  description = undefined,
}) => {
  const client = new SSMClient({});

  try {
    const { windowId } = await client.send(
      new CreateMaintenanceWindowCommand({
        Name: name,
        Description: description,
        AllowUnassociatedTargets: allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
        Duration: duration, // The duration of the maintenance window in hours.
        Cutoff: cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution.
        Schedule: schedule, // The schedule of the maintenance window in the form of a cron or rate expression.
      }),
    );
    console.log(`Maintenance window created with Id: ${windowId}`);
    return { WindowId: windowId };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide these values?`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [CreateMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateMaintenanceWindowCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 이름의 새 유지 관리 기간을 생성합니다. 이 유지 관리 기간은 매주 화요일 오후 4시에 4시간 동안 실행되며, 마감 시간은 1시간이고, 연결되지 않은 대상을 허용합니다.**  

```
New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 -AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)"
```
**출력:**  

```
mw-03eb53e1ea7383998
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 이름의 새 유지 관리 기간을 생성합니다. 이 유지 관리 기간은 매주 화요일 오후 4시에 4시간 동안 실행되며, 마감 시간은 1시간이고, 연결되지 않은 대상을 허용합니다.**  

```
New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 -AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)"
```
**출력:**  

```
mw-03eb53e1ea7383998
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateMaintenanceWindow](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 MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, name, schedule, duration, cutoff, allow_unassociated_targets):
        """
        Create an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            response = self.ssm_client.create_maintenance_window(
                Name=name,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.window_id = response["WindowId"]
            self.name = name
            logger.info("Created maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to create maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create maintenance window %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateMaintenanceWindow)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ssm->createmaintenancewindow(
            iv_name = iv_name
            iv_schedule = iv_schedule
            iv_duration = iv_duration
            iv_cutoff = iv_cutoff
            iv_allowunassociatedtargets = iv_allow_unassociated_targets ).
        MESSAGE 'Maintenance window created.' TYPE 'I'.
      CATCH /aws1/cx_ssmresrclimitexcdex.
        MESSAGE 'Resource limit exceeded.' TYPE 'I'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateMaintenanceWindow](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# AWS SDK 또는 CLI와 `CreateOpsItem` 함께 사용
<a name="ssm_example_ssm_CreateOpsItem_section"></a>

다음 코드 예시는 `CreateOpsItem`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md) 

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

**AWS CLI**  
**OpsItems를 생성하는 방법**  
다음 `create-ops-item` 예시에서는 OperationalData의 /aws/resources 키를 사용하여 Amazon DynamoDB 관련 리소스가 있는 OpsItem을 생성합니다.  

```
aws ssm create-ops-item \
    --title "EC2 instance disk full" \
    --description "Log clean up may have failed which caused the disk to be full" \
    --priority 2 \
    --source ec2 \
    --operational-data '{"/aws/resources":{"Value":"[{\"arn\": \"arn:aws:dynamodb:us-west-2:12345678:table/OpsItems\"}]","Type":"SearchableString"}}' \
    --notifications Arn="arn:aws:sns:us-west-2:12345678:TestUser"
```
출력:  

```
{
    "OpsItemId": "oi-1a2b3c4d5e6f"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Creating OpsItems](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateOpsItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-ops-item.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Creates an SSM OpsItem asynchronously.
     *
     * @param title The title of the OpsItem.
     * @param source The source of the OpsItem.
     * @param category The category of the OpsItem.
     * @param severity The severity of the OpsItem.
     * @return The ID of the created OpsItem.
     * <p>
     * This method initiates an asynchronous request to create an SSM OpsItem.
     * If the request is successful, it returns the OpsItem ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createSSMOpsItem(String title, String source, String category, String severity) {
        CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder()
                .description("Created by the SSM Java API")
                .title(title)
                .source(source)
                .category(category)
                .severity(severity)
                .build();

        CompletableFuture<CreateOpsItemResponse> future = getAsyncClient().createOpsItem(opsItemRequest);

        try {
            CreateOpsItemResponse response = future.join();
            return response.opsItemId();
        } catch (CompletionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof SsmException) {
                throw (SsmException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }
    }
```
+  API에 대한 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [CreateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateOpsItem)을 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { CreateOpsItemCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Create an SSM OpsItem.
 * @param {{ title: string, source: string, category?: string, severity?: string }}
 */
export const main = async ({
  title,
  source,
  category = undefined,
  severity = undefined,
}) => {
  const client = new SSMClient({});
  try {
    const { opsItemArn, opsItemId } = await client.send(
      new CreateOpsItemCommand({
        Title: title,
        Source: source, // The origin of the OpsItem, such as Amazon EC2 or Systems Manager.
        Category: category,
        Severity: severity,
      }),
    );
    console.log(`Ops item created with id: ${opsItemId}`);
    return { OpsItemArn: opsItemArn, OpsItemId: opsItemId };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide these values?`);
    } else {
      throw caught;
    }
  }
};
```
+  API에 대한 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateOpsItemCommand)을 참조하세요.

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

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, title, source, category, severity, description):
        """
        Create an OpsItem

        :param title: The OpsItem title.
        :param source: The OpsItem source.
        :param category: The OpsItem category.
        :param severity: The OpsItem severity.
        :param description: The OpsItem description.

        """
        try:
            response = self.ssm_client.create_ops_item(
                Title=title,
                Source=source,
                Category=category,
                Severity=severity,
                Description=description,
            )
            self.id = response["OpsItemId"]
        except self.ssm_client.exceptions.OpsItemLimitExceededException as err:
            logger.error(
                "Couldn't create ops item because you have exceeded your open OpsItem limit. "
                "Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create ops item %s. Here's why: %s: %s",
                title,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python(Boto3) API 참조*의 [CreateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateOpsItem)을 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_ssm->createopsitem(
            iv_title = iv_title
            iv_source = iv_source
            iv_category = iv_category
            iv_severity = iv_severity
            iv_description = iv_description ).
        MESSAGE 'OpsItem created.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsitemlimitexcdex.
        MESSAGE 'You have exceeded your open OpsItem limit.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsitemalrdyexex.
        MESSAGE 'OpsItem already exists.' TYPE 'I'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateOpsItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------

# CLI로 `CreatePatchBaseline` 사용
<a name="ssm_example_ssm_CreatePatchBaseline_section"></a>

다음 코드 예시는 `CreatePatchBaseline`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 자동 승인을 사용하여 패치 기준을 생성하는 방법**  
다음 `create-patch-baseline` 예제에서는 Microsoft에서 릴리스하고 7일 후에 프로덕션 환경에 대한 패치를 승인하는 Windows Server용 패치 기준을 생성합니다.  

```
aws ssm create-patch-baseline \
    --name "Windows-Production-Baseline-AutoApproval" \
    --operating-system "WINDOWS" \
    --approval-rules "PatchRules=[{PatchFilterGroup={PatchFilters=[{Key=MSRC_SEVERITY,Values=[Critical,Important,Moderate]},{Key=CLASSIFICATION,Values=[SecurityUpdates,Updates,UpdateRollups,CriticalUpdates]}]},ApproveAfterDays=7}]" \
    --description "Baseline containing all updates approved for Windows Server production systems"
```
출력:  

```
{
    "BaselineId": "pb-045f10b4f3EXAMPLE"
}
```
**예제 2: 승인 마감일이 포함된 패치 기준을 생성하는 방법**  
다음 `create-patch-baseline` 예제에서는 2020년 7월 7일을 포함하여 해당 날짜 이전에 릴리스된 프로덕션 환경에 대한 패치를 승인하는 Windows Server용 패치 기준을 생성합니다.  

```
aws ssm create-patch-baseline \
    --name "Windows-Production-Baseline-AutoApproval" \
    --operating-system "WINDOWS" \
    --approval-rules "PatchRules=[{PatchFilterGroup={PatchFilters=[{Key=MSRC_SEVERITY,Values=[Critical,Important,Moderate]},{Key=CLASSIFICATION,Values=[SecurityUpdates,Updates,UpdateRollups,CriticalUpdates]}]},ApproveUntilDate=2020-07-07}]" \
    --description "Baseline containing all updates approved for Windows Server production systems"
```
출력:  

```
{
    "BaselineId": "pb-045f10b4f3EXAMPLE"
}
```
**예제 3: JSON 파일에 저장된 승인 규칙을 사용하여 패치 기준을 생성하는 방법**  
다음 `create-patch-baseline` 예제에서는 Amazon Linux 2017.09용 패치 기준을 생성합니다. 여기에서는 릴리스하고 7일 후에 프로덕션 환경에 대한 패치를 승인하고 패치 기준에 대한 승인 규칙을 지정하며 패치에 대한 사용자 지정 리포지토리를 지정합니다.  

```
aws ssm create-patch-baseline \
    --cli-input-json file://my-amazon-linux-approval-rules-and-repo.json
```
`my-amazon-linux-approval-rules-and-repo.json`의 콘텐츠:  

```
{
    "Name": "Amazon-Linux-2017.09-Production-Baseline",
    "Description": "My approval rules patch baseline for Amazon Linux 2017.09 instances",
    "OperatingSystem": "AMAZON_LINUX",
    "Tags": [
        {
            "Key": "Environment",
            "Value": "Production"
        }
    ],
    "ApprovalRules": {
        "PatchRules": [
            {
                "ApproveAfterDays": 7,
                "EnableNonSecurity": true,
                "PatchFilterGroup": {
                    "PatchFilters": [
                        {
                            "Key": "SEVERITY",
                            "Values": [
                                "Important",
                                "Critical"
                            ]
                        },
                        {
                            "Key": "CLASSIFICATION",
                            "Values": [
                                "Security",
                                "Bugfix"
                            ]
                        },
                        {
                            "Key": "PRODUCT",
                            "Values": [
                                "AmazonLinux2017.09"
                            ]
                        }
                    ]
                }
            }
        ]
    },
    "Sources": [
        {
            "Name": "My-AL2017.09",
            "Products": [
                "AmazonLinux2017.09"
            ],
            "Configuration": "[amzn-main] \nname=amzn-main-Base\nmirrorlist=http://repo./$awsregion./$awsdomain//$releasever/main/mirror.list //nmirrorlist_expire=300//nmetadata_expire=300 \npriority=10 \nfailovermethod=priority \nfastestmirror_enabled=0 \ngpgcheck=1 \ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga \nenabled=1 \nretries=3 \ntimeout=5\nreport_instanceid=yes"
        }
    ]
}
```
**예제 4: 승인된 패치와 거부된 패치를 지정하는 패치 기준을 생성하는 방법**  
다음 `create-patch-baseline` 예제에서는 기본 승인 규칙의 예외로 승인 및 거부할 패치를 명시적으로 지정합니다.  

```
aws ssm create-patch-baseline \
    --name "Amazon-Linux-2017.09-Alpha-Baseline" \
    --description "My custom approve/reject patch baseline for Amazon Linux 2017.09 instances" \
    --operating-system "AMAZON_LINUX" \
    --approved-patches "CVE-2018-1234567,example-pkg-EE-2018*.amzn1.noarch" \
    --approved-patches-compliance-level "HIGH" \
    --approved-patches-enable-non-security \
    --tags "Key=Environment,Value=Alpha"
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [사용자 지정 패치 기준 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baseline-console.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreatePatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-patch-baseline.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 Microsoft에서 릴리스하고 7일 후에 프로덕션 환경에서 Windows Server 2019를 실행하는 관리형 인스턴스에 대한 패치를 승인하는 패치 기준을 생성합니다.**  

```
$rule = New-Object Amazon.SimpleSystemsManagement.Model.PatchRule
$rule.ApproveAfterDays = 7

$ruleFilters = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilterGroup

$patchFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$patchFilter.Key="PRODUCT"
$patchFilter.Values="WindowsServer2019"

$severityFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$severityFilter.Key="MSRC_SEVERITY"
$severityFilter.Values.Add("Critical")
$severityFilter.Values.Add("Important")
$severityFilter.Values.Add("Moderate")

$classificationFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$classificationFilter.Key = "CLASSIFICATION"
$classificationFilter.Values.Add( "SecurityUpdates" )
$classificationFilter.Values.Add( "Updates" )
$classificationFilter.Values.Add( "UpdateRollups" )
$classificationFilter.Values.Add( "CriticalUpdates" )

$ruleFilters.PatchFilters.Add($severityFilter)
$ruleFilters.PatchFilters.Add($classificationFilter)
$ruleFilters.PatchFilters.Add($patchFilter)
$rule.PatchFilterGroup = $ruleFilters

New-SSMPatchBaseline -Name "Production-Baseline-Windows2019" -Description "Baseline containing all updates approved for production systems" -ApprovalRules_PatchRule $rule
```
**출력:**  

```
pb-0z4z6221c4296b23z
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [CreatePatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 Microsoft에서 릴리스하고 7일 후에 프로덕션 환경에서 Windows Server 2019를 실행하는 관리형 인스턴스에 대한 패치를 승인하는 패치 기준을 생성합니다.**  

```
$rule = New-Object Amazon.SimpleSystemsManagement.Model.PatchRule
$rule.ApproveAfterDays = 7

$ruleFilters = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilterGroup

$patchFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$patchFilter.Key="PRODUCT"
$patchFilter.Values="WindowsServer2019"

$severityFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$severityFilter.Key="MSRC_SEVERITY"
$severityFilter.Values.Add("Critical")
$severityFilter.Values.Add("Important")
$severityFilter.Values.Add("Moderate")

$classificationFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$classificationFilter.Key = "CLASSIFICATION"
$classificationFilter.Values.Add( "SecurityUpdates" )
$classificationFilter.Values.Add( "Updates" )
$classificationFilter.Values.Add( "UpdateRollups" )
$classificationFilter.Values.Add( "CriticalUpdates" )

$ruleFilters.PatchFilters.Add($severityFilter)
$ruleFilters.PatchFilters.Add($classificationFilter)
$ruleFilters.PatchFilters.Add($patchFilter)
$rule.PatchFilterGroup = $ruleFilters

New-SSMPatchBaseline -Name "Production-Baseline-Windows2019" -Description "Baseline containing all updates approved for production systems" -ApprovalRules_PatchRule $rule
```
**출력:**  

```
pb-0z4z6221c4296b23z
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DeleteActivation` 사용
<a name="ssm_example_ssm_DeleteActivation_section"></a>

다음 코드 예시는 `DeleteActivation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**관리형 인스턴스 활성화를 삭제하는 방법**  
다음 `delete-activation` 예제에서는 관리형 인스턴스 활성화를 삭제합니다.  

```
aws ssm delete-activation \
    --activation-id "aa673477-d926-42c1-8757-1358cEXAMPLE"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 [AWS Systems Manager 사용 설명서의 하이브리드 환경을 위한 Systems Manager 설정을 참조하세요](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances.html). *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteActivation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-activation.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 활성화를 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMActivation -ActivationId "08e51e79-1e36-446c-8e63-9458569c1363"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteActivation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 활성화를 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMActivation -ActivationId "08e51e79-1e36-446c-8e63-9458569c1363"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteActivation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DeleteAssociation` 사용
<a name="ssm_example_ssm_DeleteAssociation_section"></a>

다음 코드 예시는 `DeleteAssociation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 연결 ID를 사용하여 연결을 삭제하는 방법**  
다음 `delete-association` 예제에서는 지정된 연결 ID의 연결을 삭제합니다. 명령이 성공해도 출력은 없습니다.  

```
aws ssm delete-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [새 연결 버전 편집 및 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)을 참조하세요.  
**예제 2: 연결을 삭제하는 방법**  
다음 `delete-association` 예제에서는 인스턴스와 문서 간 연결을 삭제합니다. 명령이 성공해도 출력은 없습니다.  

```
aws ssm delete-association \
    --instance-id "i-1234567890abcdef0" \
    --name "AWS-UpdateSSMAgent"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Systems Manager에서 연결 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-association.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스와 문서 간의 연결을 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteAssociation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스와 문서 간의 연결을 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteAssociation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# AWS SDK 또는 CLI와 `DeleteDocument` 함께 사용
<a name="ssm_example_ssm_DeleteDocument_section"></a>

다음 코드 예시는 `DeleteDocument`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서를 삭제하는 방법**  
다음 `delete-document` 예제에서는 Systems Manager 문서를 삭제합니다.  

```
aws ssm delete-document \
    --name "Example"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 문서 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-document.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Deletes an AWS SSM document asynchronously.
     *
     * @param documentName The name of the document to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM document.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteDoc(String documentName) {
        DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder()
                .name(documentName)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteDocument(documentRequest)
                    .thenAccept(response -> {
                        System.out.println("The SSM document was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API 세부 정보는 **AWS SDK for Java 2.x API 참조의 [DeleteDocument](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DeleteDocument)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DeleteDocumentCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Delete an SSM document.
 * @param {{ documentName: string }}
 */
export const main = async ({ documentName }) => {
  const client = new SSMClient({});
  try {
    await client.send(new DeleteDocumentCommand({ Name: documentName }));
    console.log(`Document '${documentName}' deleted.`);
    return { Deleted: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide this value?`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [DeleteDocument](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DeleteDocumentCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 문서를 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMDocument -Name "RunShellScript"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteDocument](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 문서를 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMDocument -Name "RunShellScript"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteDocument](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 delete(self):
        """
        Deletes an AWS Systems Manager document.
        """
        if self.name is None:
            return

        try:
            self.ssm_client.delete_document(Name=self.name)
            print(f"Deleted document {self.name}.")
            self.name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python(Boto3) API 참조*의 [DeleteDocument](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteDocument)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ssm->deletedocument( iv_name = iv_name ).
        MESSAGE 'Document deleted.' TYPE 'I'.
      CATCH /aws1/cx_ssminvaliddocument.
        MESSAGE 'Invalid document.' TYPE 'I'.
      CATCH /aws1/cx_ssmassocdinstances.
        MESSAGE 'Document has associated instances.' TYPE 'I'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteDocument](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# AWS SDK 또는 CLI와 `DeleteMaintenanceWindow` 함께 사용
<a name="ssm_example_ssm_DeleteMaintenanceWindow_section"></a>

다음 코드 예시는 `DeleteMaintenanceWindow`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md) 

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

**AWS CLI**  
**유지 관리 기간을 삭제하는 방법**  
이 `delete-maintenance-window` 예제에서는 지정된 유지 관리 기간을 제거합니다.  

```
aws ssm delete-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9"
```
출력:  

```
{
    "WindowId":"mw-1a2b3c4d5e6f7g8h9"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [유지 관리 기간 삭제(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-delete-mw.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-maintenance-window.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Deletes an AWS SSM Maintenance Window asynchronously.
     *
     * @param winId The ID of the Maintenance Window to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM Maintenance Window.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteMaintenanceWindow(String winId) {
        DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder()
                .windowId(winId)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteMaintenanceWindow(windowRequest)
                    .thenAccept(response -> {
                        System.out.println("The maintenance window was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API 세부 정보는 **AWS SDK for Java 2.x API 참조의 [DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DeleteMaintenanceWindow)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { DeleteMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Delete an SSM maintenance window.
 * @param {{ windowId: string }}
 */
export const main = async ({ windowId }) => {
  const client = new SSMClient({});
  try {
    await client.send(
      new DeleteMaintenanceWindowCommand({ WindowId: windowId }),
    );
    console.log(`Maintenance window '${windowId}' deleted.`);
    return { Deleted: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide this value?`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [DeleteMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DeleteMaintenanceWindowCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간을 제거합니다.**  

```
Remove-SSMMaintenanceWindow -WindowId "mw-06d59c1a07c022145"
```
**출력:**  

```
mw-06d59c1a07c022145
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간을 제거합니다.**  

```
Remove-SSMMaintenanceWindow -WindowId "mw-06d59c1a07c022145"
```
**출력:**  

```
mw-06d59c1a07c022145
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteMaintenanceWindow](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 MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def delete(self):
        """
        Delete the associated AWS Systems Manager maintenance window.
        """
        if self.window_id is None:
            return

        try:
            self.ssm_client.delete_maintenance_window(WindowId=self.window_id)
            logger.info("Deleted maintenance window %s.", self.window_id)
            print(f"Deleted maintenance window {self.name}")
            self.window_id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete maintenance window %s. Here's why: %s: %s",
                self.window_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteMaintenanceWindow)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ssm->deletemaintenancewindow( iv_windowid = iv_window_id ).
        MESSAGE 'Maintenance window deleted.' TYPE 'I'.
      CATCH /aws1/cx_ssminternalservererr.
        MESSAGE 'Internal server error occurred.' TYPE 'I'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteMaintenanceWindow](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# AWS SDK와 `DeleteOpsItem` 함께 사용
<a name="ssm_example_ssm_DeleteOpsItem_section"></a>

다음 코드 예시는 `DeleteOpsItem`의 사용 방법을 보여 줍니다.

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

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def delete(self):
        """
        Delete the OpsItem.
        """
        if self.id is None:
            return
        try:
            self.ssm_client.delete_ops_item(OpsItemId=self.id)
            print(f"Deleted ops item with id {self.id}")
            self.id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteOpsItem)을 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ssm->deleteopsitem( iv_opsitemid = iv_ops_item_id ).
        MESSAGE 'OpsItem deleted.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsiteminvparamex.
        MESSAGE 'Invalid OpsItem parameter.' TYPE 'I'.
    ENDTRY.
```
+  API 세부 정보는 [AWS SDK for SAP ABAP API 참조](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)의 *DeleteOpsItem*을 참조하세요.

------

# CLI로 `DeleteParameter` 사용
<a name="ssm_example_ssm_DeleteParameter_section"></a>

다음 코드 예시는 `DeleteParameter`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**파라미터를 삭제하는 방법**  
다음 `delete-parameter` 예제에서는 지정된 단일 파라미터를 삭제합니다.  

```
aws ssm delete-parameter \
    --name "MyParameter"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Parameter Store 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteParameter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-parameter.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 파라미터를 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMParameter -Name "helloWorld"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeleteParameter](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 파라미터를 삭제합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMParameter -Name "helloWorld"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteParameter](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DeletePatchBaseline` 사용
<a name="ssm_example_ssm_DeletePatchBaseline_section"></a>

다음 코드 예시는 `DeletePatchBaseline`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 기준을 삭제하는 방법**  
다음 `delete-patch-baseline` 예제에서는 지정된 패치 기준을 삭제합니다.  

```
aws ssm delete-patch-baseline \
    --baseline-id "pb-045f10b4f382baeda"
```
출력:  

```
{
    "BaselineId": "pb-045f10b4f382baeda"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [패치 기준 업데이트 또는 삭제(콘솔)](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-baseline-update-or-delete.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeletePatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-patch-baseline.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 기준을 삭제합니다.**  

```
Remove-SSMPatchBaseline -BaselineId "pb-045f10b4f382baeda"
```
**출력:**  

```
pb-045f10b4f382baeda
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeletePatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 기준을 삭제합니다.**  

```
Remove-SSMPatchBaseline -BaselineId "pb-045f10b4f382baeda"
```
**출력:**  

```
pb-045f10b4f382baeda
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeletePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DeregisterManagedInstance` 사용
<a name="ssm_example_ssm_DeregisterManagedInstance_section"></a>

다음 코드 예시는 `DeregisterManagedInstance`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**관리형 인스턴스를 등록 취소하는 방법**  
다음 `deregister-managed-instance` 예제에서는 지정된 관리형 인스턴스를 등록 취소합니다.  

```
aws ssm deregister-managed-instance \
    --instance-id 'mi-08ab247cdfEXAMPLE'
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [하이브리드 및 멀티클라우드 환경에서 관리형 인스턴스 등록 취소](https://docs.aws.amazon.com/systems-manager/latest/userguide/fleet-manager-deregister-hybrid-nodes.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeregisterManagedInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-managed-instance.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 관리형 인스턴스를 등록 취소합니다. 명령이 성공해도 출력은 없습니다.**  

```
Unregister-SSMManagedInstance -InstanceId "mi-08ab247cdf1046573"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeregisterManagedInstance](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 관리형 인스턴스를 등록 취소합니다. 명령이 성공해도 출력은 없습니다.**  

```
Unregister-SSMManagedInstance -InstanceId "mi-08ab247cdf1046573"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeregisterManagedInstance](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DeregisterPatchBaselineForPatchGroup` 사용
<a name="ssm_example_ssm_DeregisterPatchBaselineForPatchGroup_section"></a>

다음 코드 예시는 `DeregisterPatchBaselineForPatchGroup`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 기준에서 패치 그룹을 등록 취소하는 방법**  
다음 `deregister-patch-baseline-for-patch-group` 예제에서는 지정된 패치 기준에서 지정된 패치 그룹을 등록 취소합니다.  

```
aws ssm deregister-patch-baseline-for-patch-group \
    --patch-group "Production" \
    --baseline-id "pb-0ca44a362fEXAMPLE"
```
출력:  

```
{
  "PatchGroup":"Production",
  "BaselineId":"pb-0ca44a362fEXAMPLE"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [패치 기준에 패치 그룹 추가](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeregisterPatchBaselineForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-patch-baseline-for-patch-group.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 기준에서 패치 그룹을 등록 취소합니다.**  

```
Unregister-SSMPatchBaselineForPatchGroup -BaselineId "pb-045f10b4f382baeda" -PatchGroup "Production"
```
**출력:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeregisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 기준에서 패치 그룹을 등록 취소합니다.**  

```
Unregister-SSMPatchBaselineForPatchGroup -BaselineId "pb-045f10b4f382baeda" -PatchGroup "Production"
```
**출력:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeregisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DeregisterTargetFromMaintenanceWindow` 사용
<a name="ssm_example_ssm_DeregisterTargetFromMaintenanceWindow_section"></a>

다음 코드 예시는 `DeregisterTargetFromMaintenanceWindow`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**유지 관리 기간에서 대상을 제거하는 방법**  
다음 `deregister-target-from-maintenance-window` 예제에서는 지정된 유지 관리 기간에서 지정된 대상을 제거합니다.  

```
aws ssm deregister-target-from-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --window-target-id "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
```
출력:  

```
{
    "WindowId":"mw-ab12cd34ef56gh78",
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [유지 관리 기간 업데이트(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-update.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeregisterTargetFromMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-target-from-maintenance-window.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간에서 대상을 제거합니다.**  

```
Unregister-SSMTargetFromMaintenanceWindow -WindowTargetId "6ab5c208-9fc4-4697-84b7-b02a6cc25f7d" -WindowId "mw-06cf17cbefcb4bf4f"
```
**출력:**  

```
WindowId             WindowTargetId
--------             --------------
mw-06cf17cbefcb4bf4f 6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간에서 대상을 제거합니다.**  

```
Unregister-SSMTargetFromMaintenanceWindow -WindowTargetId "6ab5c208-9fc4-4697-84b7-b02a6cc25f7d" -WindowId "mw-06cf17cbefcb4bf4f"
```
**출력:**  

```
WindowId             WindowTargetId
--------             --------------
mw-06cf17cbefcb4bf4f 6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DeregisterTaskFromMaintenanceWindow` 사용
<a name="ssm_example_ssm_DeregisterTaskFromMaintenanceWindow_section"></a>

다음 코드 예시는 `DeregisterTaskFromMaintenanceWindow`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**유지 관리 기간에서 작업을 제거하는 방법**  
다음 `deregister-task-from-maintenance-window` 예제에서는 지정된 유지 관리 기간에서 지정된 작업을 제거합니다.  

```
aws ssm deregister-task-from-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --window-task-id "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6c"
```
출력:  

```
{
    "WindowTaskId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6c",
    "WindowId":"mw-ab12cd34ef56gh78"
}
```
자세한 내용은 [Systems Manager 사용 설명서의 Systems Manager Maintenance Windows Tutorials(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-tutorials.html)를 참조하세요. *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeregisterTaskFromMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-task-from-maintenance-window.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간에서 작업을 제거합니다.**  

```
Unregister-SSMTaskFromMaintenanceWindow -WindowTaskId "f34a2c47-ddfd-4c85-a88d-72366b69af1b" -WindowId "mw-03a342e62c96d31b0"
```
**출력:**  

```
WindowId             WindowTaskId
--------             ------------
mw-03a342e62c96d31b0 f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DeregisterTaskFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간에서 작업을 제거합니다.**  

```
Unregister-SSMTaskFromMaintenanceWindow -WindowTaskId "f34a2c47-ddfd-4c85-a88d-72366b69af1b" -WindowId "mw-03a342e62c96d31b0"
```
**출력:**  

```
WindowId             WindowTaskId
--------             ------------
mw-03a342e62c96d31b0 f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeregisterTaskFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeActivations` 사용
<a name="ssm_example_ssm_DescribeActivations_section"></a>

다음 코드 예시는 `DescribeActivations`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**활성화를 설명하는 방법**  
다음 `describe-activations` 예시에서는 AWS 계정의 활성화에 대한 세부 정보를 나열합니다.  

```
aws ssm describe-activations
```
출력:  

```
{
    "ActivationList": [
        {
            "ActivationId": "5743558d-563b-4457-8682-d16c3EXAMPLE",
            "Description": "Example1",
            "IamRole": "HybridWebServersRole,
            "RegistrationLimit": 5,
            "RegistrationsCount": 5,
            "ExpirationDate": 1584316800.0,
            "Expired": false,
            "CreatedDate": 1581954699.792
        },
        {
            "ActivationId": "3ee0322b-f62d-40eb-b672-13ebfEXAMPLE",
            "Description": "Example2",
            "IamRole": "HybridDatabaseServersRole",
            "RegistrationLimit": 5,
            "RegistrationsCount": 5,
            "ExpirationDate": 1580515200.0,
            "Expired": true,
            "CreatedDate": 1578064132.002
        },
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [4단계: 하이브리드 환경을 위한 관리형 인스턴스 활성화 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-managed-instance-activation.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeActivations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-activations.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 계정 활성화에 대한 세부 정보를 제공합니다.**  

```
Get-SSMActivation
```
**출력:**  

```
ActivationId        : 08e51e79-1e36-446c-8e63-9458569c1363
CreatedDate         : 3/1/2017 12:01:51 AM
DefaultInstanceName : MyWebServers
Description         :
ExpirationDate      : 3/2/2017 12:01:51 AM
Expired             : False
IamRole             : AutomationRole
RegistrationLimit   : 10
RegistrationsCount  : 0
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeActivations](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 계정 활성화에 대한 세부 정보를 제공합니다.**  

```
Get-SSMActivation
```
**출력:**  

```
ActivationId        : 08e51e79-1e36-446c-8e63-9458569c1363
CreatedDate         : 3/1/2017 12:01:51 AM
DefaultInstanceName : MyWebServers
Description         :
ExpirationDate      : 3/2/2017 12:01:51 AM
Expired             : False
IamRole             : AutomationRole
RegistrationLimit   : 10
RegistrationsCount  : 0
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeActivations](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeAssociation` 사용
<a name="ssm_example_ssm_DescribeAssociation_section"></a>

다음 코드 예시는 `DescribeAssociation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 연결 세부 정보를 가져오는 방법**  
다음 `describe-association` 예제에서는 지정된 연결 ID의 연결을 설명합니다.  

```
aws ssm describe-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
출력:  

```
{
    "AssociationDescription": {
        "Name": "AWS-GatherSoftwareInventory",
        "AssociationVersion": "1",
        "Date": 1534864780.995,
        "LastUpdateAssociationDate": 1543235759.81,
        "Overview": {
            "Status": "Success",
            "AssociationStatusAggregatedCount": {
                "Success": 2
            }
        },
        "DocumentVersion": "$DEFAULT",
        "Parameters": {
            "applications": [
                "Enabled"
            ],
            "awsComponents": [
                "Enabled"
            ],
            "customInventory": [
                "Enabled"
            ],
            "files": [
                ""
            ],
            "instanceDetailedInformation": [
                "Enabled"
            ],
            "networkConfig": [
                "Enabled"
            ],
            "services": [
                "Enabled"
            ],
            "windowsRegistry": [
                ""
            ],
            "windowsRoles": [
                "Enabled"
            ],
            "windowsUpdates": [
                "Enabled"
            ]
        },
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "InstanceIds",
                "Values": [
                    "*"
                ]
            }
        ],
        "ScheduleExpression": "rate(24 hours)",
        "LastExecutionDate": 1550501886.0,
        "LastSuccessfulExecutionDate": 1550501886.0,
        "AssociationName": "Inventory-Association"
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [새 연결 버전 편집 및 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)을 참조하세요.  
**예제 2: 특정 인스턴스 및 문서에 대한 연결 세부 정보를 가져오는 방법**  
다음 `describe-association` 예제에서는 인스턴스와 문서 간 연결을 설명합니다.  

```
aws ssm describe-association \
    --instance-id "i-1234567890abcdef0" \
    --name "AWS-UpdateSSMAgent"
```
출력:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487876122.564,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-1234567890abcdef0",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Associated",
            "AssociationStatusAggregatedCount": {
                "Pending": 1
            }
        },
        "AssociationId": "d8617c07-2079-4c18-9847-1234567890ab",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487876122.564,
        "Date": 1487876122.564,
        "Targets": [
            {
                "Values": [
                    "i-1234567890abcdef0"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [새 연결 버전 편집 및 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-association.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스와 문서 간 연결을 설명합니다.**  

```
Get-SSMAssociation -InstanceId "i-0000293ffd8c57862" -Name "AWS-UpdateSSMAgent"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temp_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAssociation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스와 문서 간 연결을 설명합니다.**  

```
Get-SSMAssociation -InstanceId "i-0000293ffd8c57862" -Name "AWS-UpdateSSMAgent"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temp_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAssociation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DescribeAssociationExecutionTargets` 사용
<a name="ssm_example_ssm_DescribeAssociationExecutionTargets_section"></a>

다음 코드 예시는 `DescribeAssociationExecutionTargets`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**연결 실행의 세부 정보를 가져오는 방법**  
다음 `describe-association-execution-targets` 예제에서는 지정된 연결 실행을 설명합니다.  

```
aws ssm describe-association-execution-targets \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --execution-id "7abb6378-a4a5-4f10-8312-0123456789ab"
```
출력:  

```
{
    "AssociationExecutionTargets": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
            "ResourceId": "i-1234567890abcdef0",
            "ResourceType": "ManagedInstance",
            "Status": "Success",
            "DetailedStatus": "Success",
            "LastExecutionDate": 1550505538.497,
            "OutputSource": {
                "OutputSourceId": "97fff367-fc5a-4299-aed8-0123456789ab",
                "OutputSourceType": "RunCommand"
            }
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [연결 기록 보기](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-history.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeAssociationExecutionTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-association-execution-targets.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 연결 실행 대상의 일부인 리소스 ID와 해당 실행 상태를 표시합니다.**  

```
Get-SSMAssociationExecutionTarget -AssociationId 123a45a0-c678-9012-3456-78901234db5e -ExecutionId 123a45a0-c678-9012-3456-78901234db5e | Select-Object ResourceId, Status
```
**출력:**  

```
ResourceId           Status
----------           ------
i-0b1b2a3456f7a890b  Success
i-01c12a45d6fc7a89f  Success
i-0a1caf234f56d7dc8  Success
i-012a3fd45af6dbcfe  Failed
i-0ddc1df23c4a5fb67  Success
```
**예제 2: 이 명령은 어제 이후 명령 문서가 연결된 명령 자동화의 특정 실행을 확인합니다. 연결 실행이 실패했는지 추가로 확인하고, 실패한 경우 인스턴스 ID와 함께 실행에 대한 명령 간접 호출 세부 정보를 표시합니다.**  

```
$AssociationExecution= Get-SSMAssociationExecutionTarget -AssociationId 1c234567-890f-1aca-a234-5a678d901cb0 -ExecutionId 12345ca12-3456-2345-2b45-23456789012 | 
    Where-Object {$_.LastExecutionDate -gt (Get-Date -Hour 00 -Minute 00).AddDays(-1)} 

foreach ($execution in $AssociationExecution) {
    if($execution.Status -ne 'Success'){
        Write-Output "There was an issue executing the association $($execution.AssociationId) on $($execution.ResourceId)"
        Get-SSMCommandInvocation -CommandId $execution.OutputSource.OutputSourceId -Detail:$true | Select-Object -ExpandProperty CommandPlugins
    }
}
```
**출력:**  

```
There was an issue executing the association 1c234567-890f-1aca-a234-5a678d901cb0 on i-0a1caf234f56d7dc8


Name                   : aws:runPowerShellScript
Output                 : 
                         ----------ERROR-------
                         failed to run commands: exit status 1
OutputS3BucketName     : 
OutputS3KeyPrefix      : 
OutputS3Region         : eu-west-1
ResponseCode           : 1
ResponseFinishDateTime : 5/29/2019 11:04:49 AM
ResponseStartDateTime  : 5/29/2019 11:04:49 AM
StandardErrorUrl       : 
StandardOutputUrl      : 
Status                 : Failed
StatusDetails          : Failed
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAssociationExecutionTargets](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 연결 실행 대상의 일부인 리소스 ID와 해당 실행 상태를 표시합니다.**  

```
Get-SSMAssociationExecutionTarget -AssociationId 123a45a0-c678-9012-3456-78901234db5e -ExecutionId 123a45a0-c678-9012-3456-78901234db5e | Select-Object ResourceId, Status
```
**출력:**  

```
ResourceId           Status
----------           ------
i-0b1b2a3456f7a890b  Success
i-01c12a45d6fc7a89f  Success
i-0a1caf234f56d7dc8  Success
i-012a3fd45af6dbcfe  Failed
i-0ddc1df23c4a5fb67  Success
```
**예제 2: 이 명령은 어제 이후 명령 문서가 연결된 명령 자동화의 특정 실행을 확인합니다. 연결 실행이 실패했는지 추가로 확인하고, 실패한 경우 인스턴스 ID와 함께 실행에 대한 명령 간접 호출 세부 정보를 표시합니다.**  

```
$AssociationExecution= Get-SSMAssociationExecutionTarget -AssociationId 1c234567-890f-1aca-a234-5a678d901cb0 -ExecutionId 12345ca12-3456-2345-2b45-23456789012 | 
    Where-Object {$_.LastExecutionDate -gt (Get-Date -Hour 00 -Minute 00).AddDays(-1)} 

foreach ($execution in $AssociationExecution) {
    if($execution.Status -ne 'Success'){
        Write-Output "There was an issue executing the association $($execution.AssociationId) on $($execution.ResourceId)"
        Get-SSMCommandInvocation -CommandId $execution.OutputSource.OutputSourceId -Detail:$true | Select-Object -ExpandProperty CommandPlugins
    }
}
```
**출력:**  

```
There was an issue executing the association 1c234567-890f-1aca-a234-5a678d901cb0 on i-0a1caf234f56d7dc8


Name                   : aws:runPowerShellScript
Output                 : 
                         ----------ERROR-------
                         failed to run commands: exit status 1
OutputS3BucketName     : 
OutputS3KeyPrefix      : 
OutputS3Region         : eu-west-1
ResponseCode           : 1
ResponseFinishDateTime : 5/29/2019 11:04:49 AM
ResponseStartDateTime  : 5/29/2019 11:04:49 AM
StandardErrorUrl       : 
StandardOutputUrl      : 
Status                 : Failed
StatusDetails          : Failed
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAssociationExecutionTargets](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeAssociationExecutions` 사용
<a name="ssm_example_ssm_DescribeAssociationExecutions_section"></a>

다음 코드 예시는 `DescribeAssociationExecutions`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 연결에 대한 모든 실행 세부 정보를 가져오는 방법**  
다음 `describe-association-executions` 예제에서는 지정된 연결의 모든 실행을 설명합니다.  

```
aws ssm describe-association-executions \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
출력:  

```
{
    "AssociationExecutions": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "474925ef-1249-45a2-b93d-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505827.119,
            "ResourceCountByStatus": "{Success=1}"
        },
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505536.843,
            "ResourceCountByStatus": "{Success=1}"
        },
        ...
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [연결 기록 보기](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-history.html)를 참조하세요.  
**예제 2: 특정 날짜 및 시간 이후 연결에 대한 모든 실행의 세부 정보를 보는 방법**  
다음 `describe-association-executions` 예제에서는 지정된 날짜 및 시간 이후 연결의 모든 실행을 설명합니다.  

```
aws ssm describe-association-executions \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --filters "Key=CreatedTime,Value=2019-02-18T16:00:00Z,Type=GREATER_THAN"
```
출력:  

```
{
    "AssociationExecutions": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "474925ef-1249-45a2-b93d-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505827.119,
            "ResourceCountByStatus": "{Success=1}"
        },
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505536.843,
            "ResourceCountByStatus": "{Success=1}"
        },
        ...
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [연결 기록 보기](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-history.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeAssociationExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-association-executions.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 제공된 연결 ID에 대한 실행을 반환합니다.**  

```
Get-SSMAssociationExecution -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**출력:**  

```
AssociationId         : 123a45a0-c678-9012-3456-78901234db5e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 123a45a0-c678-9012-3456-78901234db5e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=4}
Status                : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAssociationExecutions](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 제공된 연결 ID에 대한 실행을 반환합니다.**  

```
Get-SSMAssociationExecution -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**출력:**  

```
AssociationId         : 123a45a0-c678-9012-3456-78901234db5e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 123a45a0-c678-9012-3456-78901234db5e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=4}
Status                : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAssociationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeAutomationExecutions` 사용
<a name="ssm_example_ssm_DescribeAutomationExecutions_section"></a>

다음 코드 예시는 `DescribeAutomationExecutions`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**자동화 실행을 설명하는 방법**  
다음 `describe-automation-executions` 예제에서는 자동화 실행에 대한 세부 정보를 표시합니다.  

```
aws ssm describe-automation-executions \
    --filters Key=ExecutionId,Values=73c8eef8-f4ee-4a05-820c-e354fEXAMPLE
```
출력:  

```
{
    "AutomationExecutionMetadataList": [
        {
            "AutomationExecutionId": "73c8eef8-f4ee-4a05-820c-e354fEXAMPLE",
            "DocumentName": "AWS-StartEC2Instance",
            "DocumentVersion": "1",
            "AutomationExecutionStatus": "Success",
            "ExecutionStartTime": 1583737233.748,
            "ExecutionEndTime": 1583737234.719,
            "ExecutedBy": "arn:aws:sts::29884EXAMPLE:assumed-role/mw_service_role/OrchestrationService",
            "LogFile": "",
            "Outputs": {},
            "Mode": "Auto",
            "Targets": [],
            "ResolvedTargets": {
                "ParameterValues": [],
                "Truncated": false
            },
            "AutomationType": "Local"
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [단순 자동화 워크플로 실행](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeAutomationExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-automation-executions.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 계정과 연결된 모든 활성 및 종료된 자동화 실행을 설명합니다.**  

```
Get-SSMAutomationExecutionList
```
**출력:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutedBy                : admin
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
LogFile                   :
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
```
**예제 2: 이 예제에서는 자동화 실행 상태가 '성공'이 아닌 실행의 ExecutionID, 문서, 실행 시작 및 종료 타임스탬프를 표시합니다.**  

```
Get-SSMAutomationExecutionList | Where-Object AutomationExecutionStatus -ne "Success" | Select-Object AutomationExecutionId, DocumentName, AutomationExecutionStatus, ExecutionStartTime, ExecutionEndTime | Format-Table -AutoSize
```
**출력:**  

```
AutomationExecutionId                DocumentName                            AutomationExecutionStatus ExecutionStartTime   ExecutionEndTime
---------------------                ------------                            ------------------------- ------------------   ----------------
e1d2bad3-4567-8901-ae23-456c7c8901be AWS-UpdateWindowsAmi                    Cancelled                 4/16/2019 5:37:04 AM 4/16/2019 5:47:29 AM
61234567-a7f8-90e1-2b34-567b8bf9012c Fixed-UpdateAmi                         Cancelled                 4/16/2019 5:33:04 AM 4/16/2019 5:40:15 AM
91234d56-7e89-0ac1-2aee-34ea5d6a7c89 AWS-UpdateWindowsAmi                    Failed                    4/16/2019 5:22:46 AM 4/16/2019 5:27:29 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAutomationExecutions](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 계정과 연결된 모든 활성 및 종료된 자동화 실행을 설명합니다.**  

```
Get-SSMAutomationExecutionList
```
**출력:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutedBy                : admin
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
LogFile                   :
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
```
**예제 2: 이 예제에서는 자동화 실행 상태가 '성공'이 아닌 실행의 ExecutionID, 문서, 실행 시작 및 종료 타임스탬프를 표시합니다.**  

```
Get-SSMAutomationExecutionList | Where-Object AutomationExecutionStatus -ne "Success" | Select-Object AutomationExecutionId, DocumentName, AutomationExecutionStatus, ExecutionStartTime, ExecutionEndTime | Format-Table -AutoSize
```
**출력:**  

```
AutomationExecutionId                DocumentName                            AutomationExecutionStatus ExecutionStartTime   ExecutionEndTime
---------------------                ------------                            ------------------------- ------------------   ----------------
e1d2bad3-4567-8901-ae23-456c7c8901be AWS-UpdateWindowsAmi                    Cancelled                 4/16/2019 5:37:04 AM 4/16/2019 5:47:29 AM
61234567-a7f8-90e1-2b34-567b8bf9012c Fixed-UpdateAmi                         Cancelled                 4/16/2019 5:33:04 AM 4/16/2019 5:40:15 AM
91234d56-7e89-0ac1-2aee-34ea5d6a7c89 AWS-UpdateWindowsAmi                    Failed                    4/16/2019 5:22:46 AM 4/16/2019 5:27:29 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAutomationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeAutomationStepExecutions` 사용
<a name="ssm_example_ssm_DescribeAutomationStepExecutions_section"></a>

다음 코드 예시는 `DescribeAutomationStepExecutions`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 자동화 실행의 모든 단계를 설명하는 방법**  
다음 `describe-automation-step-executions` 예제에서는 자동화 실행 단계에 대한 세부 정보를 표시합니다.  

```
aws ssm describe-automation-step-executions \
    --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE
```
출력:  

```
{
    "StepExecutions": [
        {
            "StepName": "startInstances",
            "Action": "aws:changeInstanceState",
            "ExecutionStartTime": 1583737234.134,
            "ExecutionEndTime": 1583737234.672,
            "StepStatus": "Success",
            "Inputs": {
                "DesiredState": "\"running\"",
                "InstanceIds": "[\"i-0cb99161f6EXAMPLE\"]"
            },
            "Outputs": {
                "InstanceStates": [
                    "running"
                ]
            },
            "StepExecutionId": "95e70479-cf20-4d80-8018-7e4e2EXAMPLE",
            "OverriddenParameters": {}
        }
    ]
}
```
**예제 2: 자동화 실행의 특정 단계를 설명하는 방법**  
다음 `describe-automation-step-executions` 예제에서는 자동화 실행의 특정 단계에 대한 세부 정보를 표시합니다.  

```
aws ssm describe-automation-step-executions \
    --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE \
    --filters Key=StepExecutionId,Values=95e70479-cf20-4d80-8018-7e4e2EXAMPLE
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [자동화 워크플로 단계별 실행(명령줄)](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing-manually.html#automation-working-executing-manually-commandline)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeAutomationStepExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-automation-step-executions.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 자동화 워크플로에서 모든 활성 및 종료된 단계 실행에 대한 정보를 표시합니다.**  

```
Get-SSMAutomationStepExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object StepName, Action, StepStatus
```
**출력:**  

```
StepName                  Action                  StepStatus
--------                  ------                  ----------
LaunchInstance            aws:runInstances        Success
OSCompatibilityCheck      aws:runCommand          Success
RunPreUpdateScript        aws:runCommand          Success
UpdateEC2Config           aws:runCommand          Cancelled
UpdateSSMAgent            aws:runCommand          Pending
UpdateAWSPVDriver         aws:runCommand          Pending
UpdateAWSEnaNetworkDriver aws:runCommand          Pending
UpdateAWSNVMe             aws:runCommand          Pending
InstallWindowsUpdates     aws:runCommand          Pending
RunPostUpdateScript       aws:runCommand          Pending
RunSysprepGeneralize      aws:runCommand          Pending
StopInstance              aws:changeInstanceState Pending
CreateImage               aws:createImage         Pending
TerminateInstance         aws:changeInstanceState Pending
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAutomationStepExecutions](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 자동화 워크플로에서 모든 활성 및 종료된 단계 실행에 대한 정보를 표시합니다.**  

```
Get-SSMAutomationStepExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object StepName, Action, StepStatus
```
**출력:**  

```
StepName                  Action                  StepStatus
--------                  ------                  ----------
LaunchInstance            aws:runInstances        Success
OSCompatibilityCheck      aws:runCommand          Success
RunPreUpdateScript        aws:runCommand          Success
UpdateEC2Config           aws:runCommand          Cancelled
UpdateSSMAgent            aws:runCommand          Pending
UpdateAWSPVDriver         aws:runCommand          Pending
UpdateAWSEnaNetworkDriver aws:runCommand          Pending
UpdateAWSNVMe             aws:runCommand          Pending
InstallWindowsUpdates     aws:runCommand          Pending
RunPostUpdateScript       aws:runCommand          Pending
RunSysprepGeneralize      aws:runCommand          Pending
StopInstance              aws:changeInstanceState Pending
CreateImage               aws:createImage         Pending
TerminateInstance         aws:changeInstanceState Pending
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAutomationStepExecutions](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeAvailablePatches` 사용
<a name="ssm_example_ssm_DescribeAvailablePatches_section"></a>

다음 코드 예시는 `DescribeAvailablePatches`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**사용 가능한 패치를 가져오는 방법**  
다음 `describe-available-patches` 예제에서는 MSRC 심각도가 위험인 Windows Server 2019에서 사용 가능한 모든 패치에 대한 세부 정보를 검색합니다.  

```
aws ssm describe-available-patches \
    --filters "Key=PRODUCT,Values=WindowsServer2019" "Key=MSRC_SEVERITY,Values=Critical"
```
출력:  

```
{
    "Patches": [
        {
            "Id": "fe6bd8c2-3752-4c8b-ab3e-1a7ed08767ba",
            "ReleaseDate": 1544047205.0,
            "Title": "2018-11 Update for Windows Server 2019 for x64-based Systems (KB4470788)",
            "Description": "Install this update to resolve issues in Windows. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article for more information. After you install this item, you may have to restart your computer.",
            "ContentUrl": "https://support.microsoft.com/en-us/kb/4470788",
            "Vendor": "Microsoft",
            "ProductFamily": "Windows",
            "Product": "WindowsServer2019",
            "Classification": "SecurityUpdates",
            "MsrcSeverity": "Critical",
            "KbNumber": "KB4470788",
            "MsrcNumber": "",
            "Language": "All"
        },
        {
            "Id": "c96115e1-5587-4115-b851-22baa46a3f11",
            "ReleaseDate": 1549994410.0,
            "Title": "2019-02 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4487038)",
            "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.",
            "ContentUrl": "https://support.microsoft.com/en-us/kb/4487038",
            "Vendor": "Microsoft",
            "ProductFamily": "Windows",
            "Product": "WindowsServer2019",
            "Classification": "SecurityUpdates",
            "MsrcSeverity": "Critical",
            "KbNumber": "KB4487038",
            "MsrcNumber": "",
            "Language": "All"
        },
        ...
    ]
}
```
**특정 패치의 세부 정보를 가져오는 방법**  
다음 `describe-available-patches` 예제에서는 지정된 패치에 대한 세부 정보를 검색합니다.  

```
aws ssm describe-available-patches \
    --filters "Key=PATCH_ID,Values=KB4480979"
```
출력:  

```
{
    "Patches": [
        {
            "Id": "680861e3-fb75-432e-818e-d72e5f2be719",
            "ReleaseDate": 1546970408.0,
            "Title": "2019-01 Security Update for Adobe Flash Player for Windows Server 2016 for x64-based Systems (KB4480979)",
            "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.",
            "ContentUrl": "https://support.microsoft.com/en-us/kb/4480979",
            "Vendor": "Microsoft",
            "ProductFamily": "Windows",
            "Product": "WindowsServer2016",
            "Classification": "SecurityUpdates",
            "MsrcSeverity": "Critical",
            "KbNumber": "KB4480979",
            "MsrcNumber": "",
            "Language": "All"
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Patch Manager 작업 작동 방법](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-how-it-works.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeAvailablePatches](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-available-patches.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 MSRC 심각도가 위험인 Windows Server 2012에서 사용 가능한 모든 패치를 가져옵니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="PRODUCT";Values=@("WindowsServer2012")}
$filter2 = @{Key="MSRC_SEVERITY";Values=@("Critical")}

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**출력:**  

```
Classification : SecurityUpdates
ContentUrl     : https://support.microsoft.com/en-us/kb/2727528
Description    : A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain control
                 over it. You can help protect your system by installing this update from Microsoft. After you install this update, you may have to
                 restart your system.
Id             : 1eb507be-2040-4eeb-803d-abc55700b715
KbNumber       : KB2727528
Language       : All
MsrcNumber     : MS12-072
MsrcSeverity   : Critical
Product        : WindowsServer2012
ProductFamily  : Windows
ReleaseDate    : 11/13/2012 6:00:00 PM
Title          : Security Update for Windows Server 2012 (KB2727528)
Vendor         : Microsoft
...
```
**예제 2: PowerShell 버전 2에서 각 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "PRODUCT"
$filter1.Values = "WindowsServer2012"
$filter2 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter2.Key = "MSRC_SEVERITY"
$filter2.Values = "Critical"

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**예제 3: 이 예제에서는 지난 20일 동안 릴리스되고 WindowsServer2019와 일치하는 제품에 적용할 수 있는 모든 업데이트를 가져옵니다.**  

```
Get-SSMAvailablePatch | Where-Object ReleaseDate -ge (Get-Date).AddDays(-20) | Where-Object Product -eq "WindowsServer2019" | Select-Object ReleaseDate, Product, Title
```
**출력:**  

```
ReleaseDate         Product           Title
-----------         -------           -----
4/9/2019 5:00:12 PM WindowsServer2019 2019-04 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4493478)
4/9/2019 5:00:06 PM WindowsServer2019 2019-04 Cumulative Update for Windows Server 2019 for x64-based Systems (KB4493509)
4/2/2019 5:00:06 PM WindowsServer2019 2019-03 Servicing Stack Update for Windows Server 2019 for x64-based Systems (KB4493510)
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeAvailablePatches](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 MSRC 심각도가 위험인 Windows Server 2012에서 사용 가능한 모든 패치를 가져옵니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="PRODUCT";Values=@("WindowsServer2012")}
$filter2 = @{Key="MSRC_SEVERITY";Values=@("Critical")}

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**출력:**  

```
Classification : SecurityUpdates
ContentUrl     : https://support.microsoft.com/en-us/kb/2727528
Description    : A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain control
                 over it. You can help protect your system by installing this update from Microsoft. After you install this update, you may have to
                 restart your system.
Id             : 1eb507be-2040-4eeb-803d-abc55700b715
KbNumber       : KB2727528
Language       : All
MsrcNumber     : MS12-072
MsrcSeverity   : Critical
Product        : WindowsServer2012
ProductFamily  : Windows
ReleaseDate    : 11/13/2012 6:00:00 PM
Title          : Security Update for Windows Server 2012 (KB2727528)
Vendor         : Microsoft
...
```
**예제 2: PowerShell 버전 2에서 각 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "PRODUCT"
$filter1.Values = "WindowsServer2012"
$filter2 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter2.Key = "MSRC_SEVERITY"
$filter2.Values = "Critical"

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**예제 3: 이 예제에서는 지난 20일 동안 릴리스되고 WindowsServer2019와 일치하는 제품에 적용할 수 있는 모든 업데이트를 가져옵니다.**  

```
Get-SSMAvailablePatch | Where-Object ReleaseDate -ge (Get-Date).AddDays(-20) | Where-Object Product -eq "WindowsServer2019" | Select-Object ReleaseDate, Product, Title
```
**출력:**  

```
ReleaseDate         Product           Title
-----------         -------           -----
4/9/2019 5:00:12 PM WindowsServer2019 2019-04 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4493478)
4/9/2019 5:00:06 PM WindowsServer2019 2019-04 Cumulative Update for Windows Server 2019 for x64-based Systems (KB4493509)
4/2/2019 5:00:06 PM WindowsServer2019 2019-03 Servicing Stack Update for Windows Server 2019 for x64-based Systems (KB4493510)
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeAvailablePatches](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `DescribeDocument` 함께 사용
<a name="ssm_example_ssm_DescribeDocument_section"></a>

다음 코드 예시는 `DescribeDocument`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서 세부 정보를 표시하는 방법**  
다음 `describe-document` 예제에서는 AWS 계정의 Systems Manager 문서에 대한 세부 정보를 표시합니다.  

```
aws ssm describe-document \
    --name "Example"
```
출력:  

```
{
    "Document": {
        "Hash": "fc2410281f40779e694a8b95975d0f9f316da8a153daa94e3d9921102EXAMPLE",
        "HashType": "Sha256",
        "Name": "Example",
        "Owner": "29884EXAMPLE",
        "CreatedDate": 1583257938.266,
        "Status": "Active",
        "DocumentVersion": "1",
        "Description": "Document Example",
        "Parameters": [
            {
                "Name": "AutomationAssumeRole",
                "Type": "String",
                "Description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.",
                "DefaultValue": ""
            },
            {
                "Name": "InstanceId",
                "Type": "String",
                "Description": "(Required) The ID of the Amazon EC2 instance.",
                "DefaultValue": ""
            }
        ],
        "PlatformTypes": [
            "Windows",
            "Linux"
        ],
        "DocumentType": "Automation",
        "SchemaVersion": "0.3",
        "LatestVersion": "1",
        "DefaultVersion": "1",
        "DocumentFormat": "YAML",
        "Tags": []
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 문서 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-document.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 문서에 대한 정보를 반환합니다.**  

```
Get-SSMDocumentDescription -Name "RunShellScript"
```
**출력:**  

```
CreatedDate     : 2/24/2017 5:25:13 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 123456789012
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeDocument](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 문서에 대한 정보를 반환합니다.**  

```
Get-SSMDocumentDescription -Name "RunShellScript"
```
**출력:**  

```
CreatedDate     : 2/24/2017 5:25:13 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 123456789012
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeDocument](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        DATA(lo_result) = lo_ssm->describedocument( iv_name = iv_name ).
        DATA(lo_document) = lo_result->get_document( ).
        IF lo_document IS BOUND.
          rv_status = lo_document->get_status( ).
          MESSAGE |Document status: { rv_status }| TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_ssminvaliddocument.
        MESSAGE 'Invalid document.' TYPE 'I'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeDocument](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `DescribeDocumentPermission` 사용
<a name="ssm_example_ssm_DescribeDocumentPermission_section"></a>

다음 코드 예시는 `DescribeDocumentPermission`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서 권한을 설명하는 방법**  
다음 `describe-document-permission` 예제에서는 공개적으로 공유되는 Systems Manager 문서에 대한 권한 세부 정보를 표시합니다.  

```
aws ssm describe-document-permission \
    --name "Example" \
    --permission-type "Share"
```
출력:  

```
{
    "AccountIds": [
        "all"
    ],
    "AccountSharingInfoList": [
        {
            "AccountId": "all",
            "SharedDocumentVersion": "$DEFAULT"
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 문서 공유](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-how-to-share.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeDocumentPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-document-permission.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 문서의 모든 버전을 나열합니다.**  

```
Get-SSMDocumentVersionList -Name "RunShellScript"
```
**출력:**  

```
CreatedDate          DocumentVersion IsDefaultVersion Name
-----------          --------------- ---------------- ----
2/24/2017 5:25:13 AM 1               True             RunShellScript
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeDocumentPermission](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 문서의 모든 버전을 나열합니다.**  

```
Get-SSMDocumentVersionList -Name "RunShellScript"
```
**출력:**  

```
CreatedDate          DocumentVersion IsDefaultVersion Name
-----------          --------------- ---------------- ----
2/24/2017 5:25:13 AM 1               True             RunShellScript
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DescribeEffectiveInstanceAssociations` 사용
<a name="ssm_example_ssm_DescribeEffectiveInstanceAssociations_section"></a>

다음 코드 예시는 `DescribeEffectiveInstanceAssociations`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**인스턴스에 대한 유효한 연결의 세부 정보를 가져오는 방법**  
다음 `describe-effective-instance-associations` 예제에서는 인스턴스에 대한 유효한 연결의 세부 정보를 검색합니다.  
명령:  

```
aws ssm describe-effective-instance-associations --instance-id "i-1234567890abcdef0"
```
출력:  

```
{
    "Associations": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "InstanceId": "i-1234567890abcdef0",
            "Content": "{\n    \"schemaVersion\": \"1.2\",\n    \"description\": \"Update the Amazon SSM Agent to the latest version or specified version.\",\n    \"parameters\": {\n        \"version\": {\n            \"default\": \"\",\n            \"description\": \"(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agent will be updated to the latest version.\",\n            \"type\": \"String\"\n        },\n        \"allowDowngrade\": {\n            \"default\": \"false\",\n            \"description\": \"(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.\",\n            \"type\": \"String\",\n            \"allowedValues\": [\n                \"true\",\n                \"false\"\n            ]\n        }\n    },\n    \"runtimeConfig\": {\n        \"aws:updateSsmAgent\": {\n            \"properties\": [\n                {\n                \"agentName\": \"amazon-ssm-agent\",\n                \"source\": \"https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json\",\n                \"allowDowngrade\": \"{{ allowDowngrade }}\",\n                \"targetVersion\": \"{{ version }}\"\n                }\n            ]\n        }\n    }\n}\n",
            "AssociationVersion": "1"
        }
    ]
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeEffectiveInstanceAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-effective-instance-associations.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스에 대한 유효한 연결을 설명합니다.**  

```
Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5
```
**출력:**  

```
AssociationId                        Content
-------------                        -------
d8617c07-2079-4c18-9847-1655fc2698b0 {...
```
**예제 2: 이 예제에서는 인스턴스에 대한 유효한 연결의 콘텐츠를 설명합니다.**  

```
(Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5).Content
```
**출력:**  

```
{
    "schemaVersion": "1.2",
    "description": "Update the Amazon SSM Agent to the latest version or specified version.",
    "parameters": {
        "version": {
            "default": "",
            "description": "(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agen
t will be updated to the latest version.",
            "type": "String"
        },
        "allowDowngrade": {
            "default": "false",
            "description": "(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set
 to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.",
            "type": "String",
            "allowedValues": [
                "true",
                "false"
            ]
        }
    },
    "runtimeConfig": {
        "aws:updateSsmAgent": {
            "properties": [
                {
                "agentName": "amazon-ssm-agent",
                "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json",
                "allowDowngrade": "{{ allowDowngrade }}",
                "targetVersion": "{{ version }}"
                }
            ]
        }
    }
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeEffectiveInstanceAssociations](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스에 대한 유효한 연결을 설명합니다.**  

```
Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5
```
**출력:**  

```
AssociationId                        Content
-------------                        -------
d8617c07-2079-4c18-9847-1655fc2698b0 {...
```
**예제 2: 이 예제에서는 인스턴스에 대한 유효한 연결의 콘텐츠를 설명합니다.**  

```
(Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5).Content
```
**출력:**  

```
{
    "schemaVersion": "1.2",
    "description": "Update the Amazon SSM Agent to the latest version or specified version.",
    "parameters": {
        "version": {
            "default": "",
            "description": "(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agen
t will be updated to the latest version.",
            "type": "String"
        },
        "allowDowngrade": {
            "default": "false",
            "description": "(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set
 to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.",
            "type": "String",
            "allowedValues": [
                "true",
                "false"
            ]
        }
    },
    "runtimeConfig": {
        "aws:updateSsmAgent": {
            "properties": [
                {
                "agentName": "amazon-ssm-agent",
                "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json",
                "allowDowngrade": "{{ allowDowngrade }}",
                "targetVersion": "{{ version }}"
                }
            ]
        }
    }
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeEffectiveInstanceAssociations](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeEffectivePatchesForPatchBaseline` 사용
<a name="ssm_example_ssm_DescribeEffectivePatchesForPatchBaseline_section"></a>

다음 코드 예시는 `DescribeEffectivePatchesForPatchBaseline`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 사용자 지정 패치 기준에서 정의한 모든 패치를 가져오는 방법**  
다음 `describe-effective-patches-for-patch-baseline` 예시에서는 현재 AWS 계정의 사용자 지정 패치 기준에 의해 정의된 패치를 반환합니다. 사용자 지정 기준의 경우 `--baseline-id`에는 ID만 필요합니다.  

```
aws ssm describe-effective-patches-for-patch-baseline \
    --baseline-id "pb-08b654cf9b9681f04"
```
출력:  

```
{
    "EffectivePatches": [
        {
            "Patch": {
                "Id": "fe6bd8c2-3752-4c8b-ab3e-1a7ed08767ba",
                "ReleaseDate": 1544047205.0,
                "Title": "2018-11 Update for Windows Server 2019 for x64-based Systems (KB4470788)",
                "Description": "Install this update to resolve issues in Windows. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article for more information. After you install this item, you may have to restart your computer.",
                "ContentUrl": "https://support.microsoft.com/en-us/kb/4470788",
                "Vendor": "Microsoft",
                "ProductFamily": "Windows",
                "Product": "WindowsServer2019",
                "Classification": "SecurityUpdates",
                "MsrcSeverity": "Critical",
                "KbNumber": "KB4470788",
                "MsrcNumber": "",
                "Language": "All"
            },
            "PatchStatus": {
                "DeploymentStatus": "APPROVED",
                "ComplianceLevel": "CRITICAL",
                "ApprovalDate": 1544047205.0
            }
        },
        {
            "Patch": {
                "Id": "915a6b1a-f556-4d83-8f50-b2e75a9a7e58",
                "ReleaseDate": 1549994400.0,
                "Title": "2019-02 Cumulative Update for .NET Framework 3.5 and 4.7.2 for Windows Server 2019 for x64 (KB4483452)",
                "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.",
                "ContentUrl": "https://support.microsoft.com/en-us/kb/4483452",
                "Vendor": "Microsoft",
                "ProductFamily": "Windows",
                "Product": "WindowsServer2019",
                "Classification": "SecurityUpdates",
                "MsrcSeverity": "Important",
                "KbNumber": "KB4483452",
                "MsrcNumber": "",
                "Language": "All"
            },
            "PatchStatus": {
                "DeploymentStatus": "APPROVED",
                "ComplianceLevel": "CRITICAL",
                "ApprovalDate": 1549994400.0
            }
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
**예제 2: AWS 관리형 패치 기준으로 정의된 모든 패치 가져오기**  
다음 `describe-effective-patches-for-patch-baseline` 예제에서는 AWS 관리형 패치 기준으로 정의된 패치를 반환합니다. AWS 관리형 기준의 경우 에는 전체 기준 ARN이 필요합니다. `--baseline-id`   

```
aws ssm describe-effective-patches-for-patch-baseline \
    --baseline-id "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-020d361a05defe4ed"
```
샘플 출력은 예 1을 참조하세요.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [보안 패치 선택 방법](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-how-it-works-selection.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeEffectivePatchesForPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-effective-patches-for-patch-baseline.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 최대 결과 목록이 1인 모든 패치 기준을 나열합니다.**  

```
Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1
```
**출력:**  

```
Patch                                      PatchStatus
-----                                      -----------
Amazon.SimpleSystemsManagement.Model.Patch Amazon.SimpleSystemsManagement.Model.PatchStatus
```
**예제 2: 이 예제에서는 최대 결과 목록이 1인 모든 패치 기준의 패치 상태를 표시합니다.**  

```
(Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1).PatchStatus
```
**출력:**  

```
ApprovalDate          DeploymentStatus
------------          ----------------
12/21/2010 6:00:00 PM APPROVED
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeEffectivePatchesForPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 최대 결과 목록이 1인 모든 패치 기준을 나열합니다.**  

```
Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1
```
**출력:**  

```
Patch                                      PatchStatus
-----                                      -----------
Amazon.SimpleSystemsManagement.Model.Patch Amazon.SimpleSystemsManagement.Model.PatchStatus
```
**예제 2: 이 예제에서는 최대 결과 목록이 1인 모든 패치 기준의 패치 상태를 표시합니다.**  

```
(Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1).PatchStatus
```
**출력:**  

```
ApprovalDate          DeploymentStatus
------------          ----------------
12/21/2010 6:00:00 PM APPROVED
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeEffectivePatchesForPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DescribeInstanceAssociationsStatus` 사용
<a name="ssm_example_ssm_DescribeInstanceAssociationsStatus_section"></a>

다음 코드 예시는 `DescribeInstanceAssociationsStatus`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**인스턴스 연결 상태를 설명하는 방법**  
이 예제에서는 인스턴스 연결의 세부 정보를 보여줍니다.  
명령:  

```
aws ssm describe-instance-associations-status --instance-id "i-1234567890abcdef0"
```
출력:  

```
{
  "InstanceAssociationStatusInfos": [
      {
          "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
          "Name": "AWS-GatherSoftwareInventory",
          "DocumentVersion": "1",
          "AssociationVersion": "1",
          "InstanceId": "i-1234567890abcdef0",
          "ExecutionDate": 1550501886.0,
          "Status": "Success",
          "ExecutionSummary": "1 out of 1 plugin processed, 1 success, 0 failed, 0 timedout, 0 skipped. ",
          "AssociationName": "Inventory-Association"
      },
      {
          "AssociationId": "5c5a31f6-6dae-46f9-944c-0123456789ab",
          "Name": "AWS-UpdateSSMAgent",
          "DocumentVersion": "1",
          "AssociationVersion": "1",
          "InstanceId": "i-1234567890abcdef0",
          "ExecutionDate": 1550505828.548,
          "Status": "Success",
          "DetailedStatus": "Success",
          "AssociationName": "UpdateSSMAgent"
      }
  ]
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeInstanceAssociationsStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-associations-status.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스 연결의 세부 정보를 보여줍니다.**  

```
Get-SSMInstanceAssociationsStatus -InstanceId "i-0000293ffd8c57862"
```
**출력:**  

```
AssociationId    : d8617c07-2079-4c18-9847-1655fc2698b0
DetailedStatus   : Pending
DocumentVersion  : 1
ErrorCode        :
ExecutionDate    : 2/20/2015 8:31:11 AM
ExecutionSummary : temp_status_change
InstanceId       : i-0000293ffd8c57862
Name             : AWS-UpdateSSMAgent
OutputUrl        :
Status           : Pending
```
**예제 2: 이 예제에서는 지정된 인스턴스 ID의 인스턴스 연결 상태를 확인하고 더 나아가 해당 연결의 실행 상태를 표시합니다.**  

```
Get-SSMInstanceAssociationsStatus -InstanceId i-012e3cb4df567e8aa | ForEach-Object {Get-SSMAssociationExecution -AssociationId .AssociationId}
```
**출력:**  

```
AssociationId         : 512a34a5-c678-1234-1234-12345678db9e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 512a34a5-c678-1234-1234-12345678db9e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=9}
Status                : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstanceAssociationsStatus](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스 연결의 세부 정보를 보여줍니다.**  

```
Get-SSMInstanceAssociationsStatus -InstanceId "i-0000293ffd8c57862"
```
**출력:**  

```
AssociationId    : d8617c07-2079-4c18-9847-1655fc2698b0
DetailedStatus   : Pending
DocumentVersion  : 1
ErrorCode        :
ExecutionDate    : 2/20/2015 8:31:11 AM
ExecutionSummary : temp_status_change
InstanceId       : i-0000293ffd8c57862
Name             : AWS-UpdateSSMAgent
OutputUrl        :
Status           : Pending
```
**예제 2: 이 예제에서는 지정된 인스턴스 ID의 인스턴스 연결 상태를 확인하고 더 나아가 해당 연결의 실행 상태를 표시합니다.**  

```
Get-SSMInstanceAssociationsStatus -InstanceId i-012e3cb4df567e8aa | ForEach-Object {Get-SSMAssociationExecution -AssociationId .AssociationId}
```
**출력:**  

```
AssociationId         : 512a34a5-c678-1234-1234-12345678db9e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 512a34a5-c678-1234-1234-12345678db9e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=9}
Status                : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstanceAssociationsStatus](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeInstanceInformation` 사용
<a name="ssm_example_ssm_DescribeInstanceInformation_section"></a>

다음 코드 예시는 `DescribeInstanceInformation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 관리형 인스턴스 정보를 설명하는 방법**  
다음 `describe-instance-information` 예제에서는 각 관리형 인스턴스의 세부 정보를 검색합니다.  

```
aws ssm describe-instance-information
```
**예제 2: 특정 관리형 인스턴스에 대한 정보를 설명하는 방법**  
다음 `describe-instance-information` 예제에서는 관리형 인스턴스 `i-028ea792daEXAMPLE`의 세부 정보를 보여줍니다.  

```
aws ssm describe-instance-information \
    --filters "Key=InstanceIds,Values=i-028ea792daEXAMPLE"
```
**예제 3: 특정 태그 키를 사용하는 관리형 인스턴스에 대한 정보를 설명하는 방법**  
다음 `describe-instance-information` 예제에서는 태그 키 `DEV`가 있는 관리형 인스턴스의 세부 정보를 보여줍니다.  

```
aws ssm describe-instance-information \
    --filters "Key=tag-key,Values=DEV"
```
출력:  

```
{
    "InstanceInformationList": [
        {
            "InstanceId": "i-028ea792daEXAMPLE",
            "PingStatus": "Online",
            "LastPingDateTime": 1582221233.421,
            "AgentVersion": "2.3.842.0",
            "IsLatestVersion": true,
            "PlatformType": "Linux",
            "PlatformName": "SLES",
            "PlatformVersion": "15.1",
            "ResourceType": "EC2Instance",
            "IPAddress": "192.0.2.0",
            "ComputerName": "ip-198.51.100.0.us-east-2.compute.internal",
            "AssociationStatus": "Success",
            "LastAssociationExecutionDate": 1582220806.0,
            "LastSuccessfulAssociationExecutionDate": 1582220806.0,
            "AssociationOverview": {
                "DetailedStatus": "Success",
                "InstanceAssociationStatusAggregatedCount": {
                    "Success": 2
                }
            }
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [관리형 인스턴스](https://docs.aws.amazon.com/systems-manager/latest/userguide/managed_instances.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeInstanceInformation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-information.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 각 인스턴스의 세부 정보를 보여줍니다.**  

```
Get-SSMInstanceInformation
```
**출력:**  

```
ActivationId                           :
AgentVersion                           : 2.0.672.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : ip-172-31-44-222.us-west-2.compute.internal
IamRole                                :
InstanceId                             : i-0cb2b964d3e14fd9f
IPAddress                              : 172.31.44.222
IsLatestVersion                        : True
LastAssociationExecutionDate           : 2/24/2017 3:18:09 AM
LastPingDateTime                       : 2/24/2017 3:35:03 AM
LastSuccessfulAssociationExecutionDate : 2/24/2017 3:18:09 AM
Name                                   :
PingStatus                             : ConnectionLost
PlatformName                           : Amazon Linux AMI
PlatformType                           : Linux
PlatformVersion                        : 2016.09
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**예제 2:이 예제에서는 -Filter 파라미터를 사용하여 `AgentVersion`가 `us-east-1`인 리전의 AWS Systems Manager 인스턴스로만 결과를 필터링하는 방법을 보여줍니다`2.2.800.0`. InstanceInformation API 참조 주제(https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformation.html\$1systemsmanager-Type-InstanceInformation-ActivationId)에서 유효한 -Filter 키 값 목록을 찾을 수 있습니다.**  

```
$Filters = @{
    Key="AgentVersion"
    Values="2.2.800.0"
}
Get-SSMInstanceInformation -Region us-east-1 -Filter $Filters
```
**출력:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.01
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.02
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**예제 3:이 예제에서는 -InstanceInformationFilterList 파라미터를 사용하여 `Windows` 또는 `PlatformTypes`가 `us-east-1` 있는 리전의 AWS Systems Manager 인스턴스로만 결과를 필터링하는 방법을 보여줍니다`Linux`. InstanceInformationFilter API 참조 주제(https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformationFilter.html)에서 유효한 -InstanceInformationFilterList 키 값 목록을 찾을 수 있습니다.**  

```
$Filters = @{
   Key="PlatformTypes"
   ValueSet=("Windows","Linux")
}
Get-SSMInstanceInformation -Region us-east-1 -InstanceInformationFilterList $Filters
```
**출력:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.27
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Ubuntu Server 18.04 LTS
PlatformType                           : Linux
PlatformVersion                        : 18.04
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.100
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**예제 4: 이 예제에서는 ssm 관리형 인스턴스를 나열하고 InstanceId, PingStatus, LastPingDateTime 및 PlatformName을 csv 파일로 내보냅니다.**  

```
Get-SSMInstanceInformation | Select-Object InstanceId, PingStatus, LastPingDateTime, PlatformName | Export-Csv Instance-details.csv -NoTypeInformation
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstanceInformation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 각 인스턴스의 세부 정보를 보여줍니다.**  

```
Get-SSMInstanceInformation
```
**출력:**  

```
ActivationId                           :
AgentVersion                           : 2.0.672.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : ip-172-31-44-222.us-west-2.compute.internal
IamRole                                :
InstanceId                             : i-0cb2b964d3e14fd9f
IPAddress                              : 172.31.44.222
IsLatestVersion                        : True
LastAssociationExecutionDate           : 2/24/2017 3:18:09 AM
LastPingDateTime                       : 2/24/2017 3:35:03 AM
LastSuccessfulAssociationExecutionDate : 2/24/2017 3:18:09 AM
Name                                   :
PingStatus                             : ConnectionLost
PlatformName                           : Amazon Linux AMI
PlatformType                           : Linux
PlatformVersion                        : 2016.09
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**예제 2:이 예제에서는 -Filter 파라미터를 사용하여 `AgentVersion`가 `us-east-1`인 리전의 AWS Systems Manager 인스턴스로만 결과를 필터링하는 방법을 보여줍니다`2.2.800.0`. InstanceInformation API 참조 주제(https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformation.html\$1systemsmanager-Type-InstanceInformation-ActivationId)에서 유효한 -Filter 키 값 목록을 찾을 수 있습니다.**  

```
$Filters = @{
    Key="AgentVersion"
    Values="2.2.800.0"
}
Get-SSMInstanceInformation -Region us-east-1 -Filter $Filters
```
**출력:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.01
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.02
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**예제 3:이 예제에서는 -InstanceInformationFilterList 파라미터를 사용하여 `Windows` 또는 `PlatformTypes`가 `us-east-1` 있는 리전의 AWS Systems Manager 인스턴스로만 결과를 필터링하는 방법을 보여줍니다`Linux`. InstanceInformationFilter API 참조 주제(https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformationFilter.html)에서 유효한 -InstanceInformationFilterList 키 값 목록을 찾을 수 있습니다.**  

```
$Filters = @{
   Key="PlatformTypes"
   ValueSet=("Windows","Linux")
}
Get-SSMInstanceInformation -Region us-east-1 -InstanceInformationFilterList $Filters
```
**출력:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.27
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Ubuntu Server 18.04 LTS
PlatformType                           : Linux
PlatformVersion                        : 18.04
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.100
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**예제 4: 이 예제에서는 ssm 관리형 인스턴스를 나열하고 InstanceId, PingStatus, LastPingDateTime 및 PlatformName을 csv 파일로 내보냅니다.**  

```
Get-SSMInstanceInformation | Select-Object InstanceId, PingStatus, LastPingDateTime, PlatformName | Export-Csv Instance-details.csv -NoTypeInformation
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstanceInformation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DescribeInstancePatchStates` 사용
<a name="ssm_example_ssm_DescribeInstancePatchStates_section"></a>

다음 코드 예시는 `DescribeInstancePatchStates`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**인스턴스의 패치 요약 상태를 가져오는 방법**  
이 `describe-instance-patch-states` 예제에서는 인스턴스의 패치 요약 상태를 가져옵니다.  

```
aws ssm describe-instance-patch-states \
    --instance-ids "i-1234567890abcdef0"
```
출력:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PatchGroup": "my-patch-group",
            "BaselineId": "pb-0713accee01234567",
            "SnapshotId": "521c3536-930c-4aa9-950e-01234567abcd",
            "CriticalNonCompliantCount": 2,
            "SecurityNonCompliantCount": 2,
            "OtherNonCompliantCount": 1,
            "InstalledCount": 123,
            "InstalledOtherCount": 334,
            "InstalledPendingRebootCount": 0,
            "InstalledRejectedCount": 0,
            "MissingCount": 1,
            "FailedCount": 2,
            "UnreportedNotApplicableCount": 11,
            "NotApplicableCount": 2063,
            "OperationStartTime": "2021-05-03T11:00:56-07:00",
            "OperationEndTime": "2021-05-03T11:01:09-07:00",
            "Operation": "Scan",
            "LastNoRebootInstallOperationTime": "2020-06-14T12:17:41-07:00",
            "RebootOption": "RebootIfNeeded"
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [패치 규정 준수 정보](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeInstancePatchStates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-patch-states.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스의 패치 요약 상태를 가져옵니다.**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407"
```
**예제 2: 이 예제에서는 두 인스턴스의 패치 요약 상태를 가져옵니다.**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407","i-09a618aec652973a9"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstancePatchStates](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스의 패치 요약 상태를 가져옵니다.**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407"
```
**예제 2: 이 예제에서는 두 인스턴스의 패치 요약 상태를 가져옵니다.**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407","i-09a618aec652973a9"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstancePatchStates](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeInstancePatchStatesForPatchGroup` 사용
<a name="ssm_example_ssm_DescribeInstancePatchStatesForPatchGroup_section"></a>

다음 코드 예시는 `DescribeInstancePatchStatesForPatchGroup`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 패치 그룹의 인스턴스 상태를 가져오는 방법**  
다음 `describe-instance-patch-states-for-patch-group` 예제에서는 지정된 패치 그룹의 인스턴스당 패치 요약 상태에 대한 세부 정보를 검색합니다.  

```
aws ssm describe-instance-patch-states-for-patch-group \
    --patch-group "Production"
```
출력:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-02573cafcfEXAMPLE",
            "PatchGroup": "Production",
            "BaselineId": "pb-0c10e65780EXAMPLE",
            "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE",
            "OwnerInformation": "",
            "InstalledCount": 32,
            "InstalledOtherCount": 1,
            "InstalledPendingRebootCount": 0,
            "InstalledRejectedCount": 0,
            "MissingCount": 2,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 2671,
            "NotApplicableCount": 400,
            "OperationStartTime": "2021-08-04T11:03:50.590000-07:00",
            "OperationEndTime": "2021-08-04T11:04:21.555000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 0
        },
        {
            "InstanceId": "i-0471e04240EXAMPLE",
            "PatchGroup": "Production",
            "BaselineId": "pb-09ca3fb51fEXAMPLE",
            "SnapshotId": "05d8ffb0-1bbe-4812-ba2d-d9b7bEXAMPLE",
            "OwnerInformation": "",
            "InstalledCount": 32,
            "InstalledOtherCount": 1,
            "InstalledPendingRebootCount": 0,
            "InstalledRejectedCount": 0,
            "MissingCount": 2,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 2671,
            "NotApplicableCount": 400,
            "OperationStartTime": "2021-08-04T22:06:20.340000-07:00",
            "OperationEndTime": "2021-08-04T22:07:11.220000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 0
        }
    ]
}
```
**예제 2: 패치가 5개 넘게 누락된 패치 그룹의 인스턴스 상태를 가져오는 방법**  
다음 `describe-instance-patch-states-for-patch-group` 예제에서는 패치가 5개 넘게 누락된 인스턴스에서 지정된 패치 그룹의 패치 요약 상태에 대한 세부 정보를 검색합니다.  

```
aws ssm describe-instance-patch-states-for-patch-group \
    --filters Key=MissingCount,Type=GreaterThan,Values=5 \
    --patch-group "Production"
```
출력:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-02573cafcfEXAMPLE",
            "PatchGroup": "Production",
            "BaselineId": "pb-0c10e65780EXAMPLE",
            "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE",
            "OwnerInformation": "",
            "InstalledCount": 46,
            "InstalledOtherCount": 4,
            "InstalledPendingRebootCount": 1,
            "InstalledRejectedCount": 1,
            "MissingCount": 7,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 232,
            "NotApplicableCount": 654,
            "OperationStartTime": "2021-08-04T11:03:50.590000-07:00",
            "OperationEndTime": "2021-08-04T11:04:21.555000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 1
        }
    ]
}
```
**예제 3: 재부팅이 필요한 인스턴스가 10개 미만인 패치 그룹의 인스턴스 상태를 가져오는 방법**  
다음 `describe-instance-patch-states-for-patch-group` 예제에서는 리부팅해야 하는 패치가 10개 미만인 인스턴스에서 지정된 패치 그룹의 패치 요약 상태에 대한 세부 정보를 검색합니다.  

```
aws ssm describe-instance-patch-states-for-patch-group \
    --filters Key=InstalledPendingRebootCount,Type=LessThan,Values=10 \
    --patch-group "Production"
```
출력:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-02573cafcfEXAMPLE",
            "BaselineId": "pb-0c10e65780EXAMPLE",
            "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE",
            "PatchGroup": "Production",
            "OwnerInformation": "",
            "InstalledCount": 32,
            "InstalledOtherCount": 1,
            "InstalledPendingRebootCount": 4,
            "InstalledRejectedCount": 0,
            "MissingCount": 2,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 846,
            "NotApplicableCount": 212,
            "OperationStartTime": "2021-08-046T11:03:50.590000-07:00",
            "OperationEndTime": "2021-08-06T11:04:21.555000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 0
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [패치 규정 준수 상태 값 이해](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance-states.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeInstancePatchStatesForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-patch-states-for-patch-group.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 그룹의 인스턴스당 패치 요약 상태를 가져옵니다.**  

```
Get-SSMInstancePatchStatesForPatchGroup -PatchGroup "Production"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstancePatchStatesForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 그룹의 인스턴스당 패치 요약 상태를 가져옵니다.**  

```
Get-SSMInstancePatchStatesForPatchGroup -PatchGroup "Production"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstancePatchStatesForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DescribeInstancePatches` 사용
<a name="ssm_example_ssm_DescribeInstancePatches_section"></a>

다음 코드 예시는 `DescribeInstancePatches`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 인스턴스의 패치 상태 세부 정보를 가져오는 방법**  
다음 `describe-instance-patches` 예제에서는 지정된 인스턴스의 패치에 대한 세부 정보를 검색합니다.  

```
aws ssm describe-instance-patches \
    --instance-id "i-1234567890abcdef0"
```
출력:  

```
{
    "Patches": [
        {
            "Title": "2019-01 Security Update for Adobe Flash Player for Windows Server 2016 for x64-based Systems (KB4480979)",
            "KBId": "KB4480979",
            "Classification": "SecurityUpdates",
            "Severity": "Critical",
            "State": "Installed",
            "InstalledTime": "2019-01-09T00:00:00+00:00"
        },
        {
            "Title": "",
            "KBId": "KB4481031",
            "Classification": "",
            "Severity": "",
            "State": "InstalledOther",
            "InstalledTime": "2019-02-08T00:00:00+00:00"
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
**예제 2: 인스턴스에서 누락 상태의 패치 목록을 가져오는 방법**  
다음 `describe-instance-patches` 예제에서는 지정된 인스턴스에서 누락 상태인 패치에 대한 정보를 검색합니다.  

```
aws ssm describe-instance-patches \
    --instance-id "i-1234567890abcdef0" \
    --filters Key=State,Values=Missing
```
출력:  

```
{
    "Patches": [
        {
            "Title": "Windows Malicious Software Removal Tool x64 - February 2019 (KB890830)",
            "KBId": "KB890830",
            "Classification": "UpdateRollups",
            "Severity": "Unspecified",
            "State": "Missing",
            "InstalledTime": "1970-01-01T00:00:00+00:00"
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [패치 규정 준수 상태 정보](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance-states.html)를 참조하세요.  
**예제 3: 인스턴스의 지정된 설치 시간 이후에 설치된 패치 목록을 가져오는 방법**  
다음 `describe-instance-patches` 예제에서는 `--filters` 및 `--query`의 사용을 조합하여 지정된 인스턴스에 대해 지정된 시간 이후에 설치된 패치에 대한 정보를 검색합니다.  

```
aws ssm describe-instance-patches \
    --instance-id "i-1234567890abcdef0" \
    --filters Key=State,Values=Installed \
    --query "Patches[?InstalledTime >= `2023-01-01T16:00:00`]"
```
출력:  

```
{
    "Patches": [
        {
            "Title": "2023-03 Cumulative Update for Windows Server 2019 (1809) for x64-based Systems (KB5023702)",
            "KBId": "KB5023702",
            "Classification": "SecurityUpdates",
            "Severity": "Critical",
            "State": "Installed",
            "InstalledTime": "2023-03-16T11:00:00+00:00"
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeInstancePatches](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-patches.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스에 대한 패치 규정 준수 세부 정보를 가져옵니다.**  

```
Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeInstancePatches](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스에 대한 패치 규정 준수 세부 정보를 가져옵니다.**  

```
Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeInstancePatches](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeMaintenanceWindowExecutionTaskInvocations` 사용
<a name="ssm_example_ssm_DescribeMaintenanceWindowExecutionTaskInvocations_section"></a>

다음 코드 예시는 `DescribeMaintenanceWindowExecutionTaskInvocations`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**유지 관리 기간 작업 실행을 위해 수행된 특정 작업 간접 호출을 가져오는 방법**  
다음 `describe-maintenance-window-execution-task-invocations` 예제에서는 지정된 유지 관리 기간 실행의 일부로 실행된 작업에 간접 호출을 나열합니다.  

```
aws ssm describe-maintenance-window-execution-task-invocations \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2a638355" \
    --task-id "ac0c6ae1-daa3-4a89-832e-d384503b6586"
```
출력:  

```
{
    "WindowExecutionTaskInvocationIdentities": [
        {
            "Status": "SUCCESS",
            "Parameters": "{\"documentName\":\"AWS-RunShellScript\",\"instanceIds\":[\"i-0000293ffd8c57862\"],\"parameters\":{\"commands\":[\"df\"]},\"maxConcurrency\":\"1\",\"maxErrors\":\"1\"}",
            "InvocationId": "e274b6e1-fe56-4e32-bd2a-8073c6381d8b",
            "StartTime": 1487692834.723,
            "EndTime": 1487692834.871,
            "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2a638355",
            "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d384503b6586"
        }
    ]
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [작업 및 작업 실행(AWS CLI)에 대한 정보 보기를 참조하세요](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html).  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeMaintenanceWindowExecutionTaskInvocations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-execution-task-invocations.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간 실행의 일부로 실행된 작업에 대한 간접 호출을 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionTaskInvocationList -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:34 PM
ExecutionId       :
InvocationId      : e274b6e1-fe56-4e32-bd2a-8073c6381d8b
OwnerInformation  :
Parameters        : {"documentName":"AWS-RunShellScript","instanceIds":["i-0000293ffd8c57862"],"parameters":{"commands":["df"]},"maxConcurrency":"1",
                    "maxErrors":"1"}
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The instance IDs list contains an invalid entry.
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
WindowTargetId    :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeMaintenanceWindowExecutionTaskInvocations](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간 실행의 일부로 실행된 작업에 대한 간접 호출을 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionTaskInvocationList -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:34 PM
ExecutionId       :
InvocationId      : e274b6e1-fe56-4e32-bd2a-8073c6381d8b
OwnerInformation  :
Parameters        : {"documentName":"AWS-RunShellScript","instanceIds":["i-0000293ffd8c57862"],"parameters":{"commands":["df"]},"maxConcurrency":"1",
                    "maxErrors":"1"}
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The instance IDs list contains an invalid entry.
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
WindowTargetId    :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeMaintenanceWindowExecutionTaskInvocations](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeMaintenanceWindowExecutionTasks` 사용
<a name="ssm_example_ssm_DescribeMaintenanceWindowExecutionTasks_section"></a>

다음 코드 예시는 `DescribeMaintenanceWindowExecutionTasks`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**유지 관리 기간 실행과 연결된 모든 작업을 나열하는 방법**  
다음 `ssm describe-maintenance-window-execution-tasks` 예제에서는 지정된 유지 관리 기간 실행과 연결된 작업을 나열합니다.  

```
aws ssm describe-maintenance-window-execution-tasks \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE"
```
출력:  

```
{
    "WindowExecutionTaskIdentities": [
        {
            "Status": "SUCCESS",
            "TaskArn": "AWS-RunShellScript",
            "StartTime": 1487692834.684,
            "TaskType": "RUN_COMMAND",
            "EndTime": 1487692835.005,
            "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE",
            "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE"
        }
    ]
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [작업 및 작업 실행(AWS CLI)에 대한 정보 보기를 참조하세요](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html).  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeMaintenanceWindowExecutionTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-execution-tasks.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간 실행과 연결된 작업을 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionTaskList -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : SUCCESS
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskType          : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeMaintenanceWindowExecutionTasks](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간 실행과 연결된 작업을 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionTaskList -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : SUCCESS
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskType          : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeMaintenanceWindowExecutionTasks](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeMaintenanceWindowExecutions` 사용
<a name="ssm_example_ssm_DescribeMaintenanceWindowExecutions_section"></a>

다음 코드 예시는 `DescribeMaintenanceWindowExecutions`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 유지 관리 기간의 모든 실행을 나열하는 방법**  
다음 `describe-maintenance-window-executions` 예제에서는 지정된 유지 관리 기간의 모든 실행을 나열합니다.  

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-ab12cd34eEXAMPLE"
```
출력:  

```
{
    "WindowExecutions": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowExecutionId": "6027b513-64fe-4cf0-be7d-1191aEXAMPLE",
            "Status": "IN_PROGRESS",
            "StartTime": "2021-08-04T11:00:00.000000-07:00"

        },
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowExecutionId": "ff75b750-4834-4377-8f61-b3cadEXAMPLE",
            "Status": "SUCCESS",
            "StartTime": "2021-08-03T11:00:00.000000-07:00",
            "EndTime": "2021-08-03T11:37:21.450000-07:00"
        },
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowExecutionId": "9fac7dd9-ff21-42a5-96ad-bbc4bEXAMPLE",
            "Status": "FAILED",
            "StatusDetails": "One or more tasks in the orchestration failed.",
            "StartTime": "2021-08-02T11:00:00.000000-07:00",
            "EndTime": "2021-08-02T11:22:36.190000-07:00"
        }
    ]
}
```
**예제 2: 지정된 날짜 이전의 유지 관리 기간에 대한 모든 실행을 나열하는 방법**  
다음 `describe-maintenance-window-executions` 예제에서는 지정된 날짜 이전에 지정된 유지 관리 기간의 모든 실행을 나열합니다.  

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=ExecutedBefore,Values=2021-08-03T00:00:00Z"
```
출력:  

```
{
    "WindowExecutions": [
        {
        "WindowId": "mw-ab12cd34eEXAMPLE",
        "WindowExecutionId": "9fac7dd9-ff21-42a5-96ad-bbc4bEXAMPLE",
        "Status": "FAILED",
        "StatusDetails": "One or more tasks in the orchestration failed.",
        "StartTime": "2021-08-02T11:00:00.000000-07:00",
        "EndTime": "2021-08-02T11:22:36.190000-07:00"
    }
    ]
}
```
**예제 3: 지정된 날짜 이후 유지 관리 기간에 대한 모든 실행을 나열하는 방법**  
다음 `describe-maintenance-window-executions` 예제에서는 지정된 날짜 이후에 지정된 유지 관리 기간의 모든 실행을 나열합니다.  

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=ExecutedAfter,Values=2021-08-04T00:00:00Z"
```
출력:  

```
{
    "WindowExecutions": [
        {
        "WindowId": "mw-ab12cd34eEXAMPLE",
        "WindowExecutionId": "6027b513-64fe-4cf0-be7d-1191aEXAMPLE",
        "Status": "IN_PROGRESS",
        "StartTime": "2021-08-04T11:00:00.000000-07:00"
        }
    ]
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [작업 및 작업 실행(AWS CLI)에 대한 정보 보기를 참조하세요](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html).  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeMaintenanceWindowExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-executions.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간의 모든 실행을 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d"
```
**출력:**  

```
EndTime           : 2/20/2017 6:30:17 PM
StartTime         : 2/20/2017 6:30:16 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
WindowExecutionId : 6f3215cf-4101-4fa0-9b7b-9523269599c7
WindowId          : mw-03eb9db42890fb82d
```
**예제 2: 이 예제에서는 지정된 날짜 이전에 유지 관리 기간의 모든 실행을 나열합니다.**  

```
$option1 = @{Key="ExecutedBefore";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
**예제 3: 이 예제에서는 지정된 날짜 이후에 유지 관리 기간의 모든 실행을 나열합니다.**  

```
$option1 = @{Key="ExecutedAfter";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeMaintenanceWindowExecutions](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간의 모든 실행을 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d"
```
**출력:**  

```
EndTime           : 2/20/2017 6:30:17 PM
StartTime         : 2/20/2017 6:30:16 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
WindowExecutionId : 6f3215cf-4101-4fa0-9b7b-9523269599c7
WindowId          : mw-03eb9db42890fb82d
```
**예제 2: 이 예제에서는 지정된 날짜 이전에 유지 관리 기간의 모든 실행을 나열합니다.**  

```
$option1 = @{Key="ExecutedBefore";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
**예제 3: 이 예제에서는 지정된 날짜 이후에 유지 관리 기간의 모든 실행을 나열합니다.**  

```
$option1 = @{Key="ExecutedAfter";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeMaintenanceWindowExecutions](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeMaintenanceWindowTargets` 사용
<a name="ssm_example_ssm_DescribeMaintenanceWindowTargets_section"></a>

다음 코드 예시는 `DescribeMaintenanceWindowTargets`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 유지 관리 기간의 모든 대상을 나열하는 방법**  
다음 `describe-maintenance-window-targets` 예제에서는 유지 관리 기간의 모든 대상을 나열합니다.  

```
aws ssm describe-maintenance-window-targets \
    --window-id "mw-06cf17cbefEXAMPLE"
```
출력:  

```
{
    "Targets": [
        {
            "ResourceType": "INSTANCE",
            "OwnerInformation": "Single instance",
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "Targets": [
                {
                    "Values": [
                        "i-0000293ffdEXAMPLE"
                    ],
                    "Key": "InstanceIds"
                }
            ],
            "WindowTargetId": "350d44e6-28cc-44e2-951f-4b2c9EXAMPLE"
        },
        {
            "ResourceType": "INSTANCE",
            "OwnerInformation": "Two instances in a list",
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "Targets": [
                {
                    "Values": [
                        "i-0000293ffdEXAMPLE",
                        "i-0cb2b964d3EXAMPLE"
                    ],
                    "Key": "InstanceIds"
                }
            ],
            "WindowTargetId": "e078a987-2866-47be-bedd-d9cf4EXAMPLE"
        }
    ]
}
```
**예제 2: 특정 소유자 정보 값과 일치하는 유지 관리 기간의 대상을 나열하는 방법**  
이 `describe-maintenance-window-targets` 예제에서는 특정 값이 있는 유지 관리 기간의 모든 대상을 나열합니다.  

```
aws ssm describe-maintenance-window-targets \
    --window-id "mw-0ecb1226ddEXAMPLE" \
    --filters "Key=OwnerInformation,Values=CostCenter1"
```
출력:  

```
{
    "Targets": [
        {
            "WindowId": "mw-0ecb1226ddEXAMPLE",
            "WindowTargetId": "da89dcc3-7f9c-481d-ba2b-edcb7d0057f9",
            "ResourceType": "INSTANCE",
            "Targets": [
                {
                    "Key": "tag:Environment",
                    "Values": [
                        "Prod"
                    ]
                }
            ],
            "OwnerInformation": "CostCenter1",
            "Name": "ProdTarget1"
        }
    ]
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [유지 관리 기간에 대한 정보 보기(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeMaintenanceWindowTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-targets.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간의 모든 대상을 나열합니다.**  

```
Get-SSMMaintenanceWindowTarget -WindowId "mw-06cf17cbefcb4bf4f"
```
**출력:**  

```
OwnerInformation : Single instance
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : 350d44e6-28cc-44e2-951f-4b2c985838f6

OwnerInformation : Two instances in a list
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : e078a987-2866-47be-bedd-d9cf49177d3a
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeMaintenanceWindowTargets](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간의 모든 대상을 나열합니다.**  

```
Get-SSMMaintenanceWindowTarget -WindowId "mw-06cf17cbefcb4bf4f"
```
**출력:**  

```
OwnerInformation : Single instance
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : 350d44e6-28cc-44e2-951f-4b2c985838f6

OwnerInformation : Two instances in a list
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : e078a987-2866-47be-bedd-d9cf49177d3a
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeMaintenanceWindowTargets](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeMaintenanceWindowTasks` 사용
<a name="ssm_example_ssm_DescribeMaintenanceWindowTasks_section"></a>

다음 코드 예시는 `DescribeMaintenanceWindowTasks`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 유지 관리 기간의 모든 작업을 나열하는 방법**  
다음 `describe-maintenance-window-tasks` 예제에서는 지정된 유지 관리 기간의 모든 작업을 나열합니다.  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-06cf17cbefEXAMPLE"
```
출력:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "WindowTaskId": "018b31c3-2d77-4b9e-bd48-c91edEXAMPLE",
            "TaskArn": "AWS-RestartEC2Instance",
            "TaskParameters": {},
            "Type": "AUTOMATION",
            "Description": "Restarting EC2 Instance for maintenance",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "My-Automation-Example-Task",
            "Priority": 0,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ]
        },
        {
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "WindowTaskId": "1943dee0-0a17-4978-9bf4-3cc2fEXAMPLE",
            "TaskArn": "AWS-DisableS3BucketPublicReadWrite",
            "TaskParameters": {},
            "Type": "AUTOMATION",
            "Description": "Automation task to disable read/write access on public S3 buckets",
            "MaxConcurrency": "10",
            "MaxErrors": "5",
            "Name": "My-Disable-S3-Public-Read-Write-Access-Automation-Task",
            "Priority": 0,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ]
        }
    ]
}
```
**예제 2: AWS-RunPowerShellScript 명령 문서를 호출하는 유지 관리 기간의 모든 작업을 나열하는 방법**  
다음 `describe-maintenance-window-tasks` 예제에서는 `AWS-RunPowerShellScript` 명령 문서를 간접 호출하는 지정된 유지 관리 기간의 모든 작업을 나열합니다.  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=TaskArn,Values=AWS-RunPowerShellScript"
```
출력:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE",
            "TaskArn": "AWS-RunPowerShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "MyTask"
        }
    ]
}
```
**예제 3: 우선순위가 3인 유지 관리 기간의 모든 작업을 나열하는 방법**  
다음 `describe-maintenance-window-tasks` 예제에서는 `3`이 `Priority`인 지정된 유지 관리 기간의 모든 작업을 나열합니다.  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=Priority,Values=3"
```
출력:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE",
            "TaskArn": "AWS-RunPowerShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 3,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "MyRunCommandTask"
        },
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "ee45feff-ad65-4a6c-b478-5cab8EXAMPLE",
            "TaskArn": "AWS-RestartEC2Instance",
            "Type": "AUTOMATION",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 3,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "10",
            "MaxErrors": "5",
            "Name": "My-Automation-Task",
            "Description": "A description for my Automation task"
        }
    ]
}
```
**예제 4: 우선순위가 1이고 Run Command를 사용하는 유지 관리 기간의 모든 작업을 나열하는 방법**  
이 `describe-maintenance-window-tasks` 예제에서는 `1`이 `Priority`이고 `Run Command`를 사용하는 지정된 유지 관리 기간의 모든 작업을 나열합니다.  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=Priority,Values=1" "Key=TaskType,Values=RUN_COMMAND"
```
출력:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE",
            "TaskArn": "AWS-RunPowerShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "MyRunCommandTask"
        }
    ]
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [유지 관리 기간에 대한 정보 보기(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeMaintenanceWindowTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-tasks.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간의 모든 작업을 나열합니다.**  

```
Get-SSMMaintenanceWindowTaskList -WindowId "mw-06cf17cbefcb4bf4f"
```
**출력:**  

```
LoggingInfo    :
MaxConcurrency : 1
MaxErrors      : 1
Priority       : 10
ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
Targets        : {InstanceIds}
TaskArn        : AWS-RunShellScript
TaskParameters : {[commands, Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression]}
Type           : RUN_COMMAND
WindowId       : mw-06cf17cbefcb4bf4f
WindowTaskId   : a23e338d-ff30-4398-8aa3-09cd052ebf17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeMaintenanceWindowTasks](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간의 모든 작업을 나열합니다.**  

```
Get-SSMMaintenanceWindowTaskList -WindowId "mw-06cf17cbefcb4bf4f"
```
**출력:**  

```
LoggingInfo    :
MaxConcurrency : 1
MaxErrors      : 1
Priority       : 10
ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
Targets        : {InstanceIds}
TaskArn        : AWS-RunShellScript
TaskParameters : {[commands, Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression]}
Type           : RUN_COMMAND
WindowId       : mw-06cf17cbefcb4bf4f
WindowTaskId   : a23e338d-ff30-4398-8aa3-09cd052ebf17
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeMaintenanceWindowTasks](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribeMaintenanceWindows` 사용
<a name="ssm_example_ssm_DescribeMaintenanceWindows_section"></a>

다음 코드 예시는 `DescribeMaintenanceWindows`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 모든 유지 관리 기간을 나열하는 방법**  
다음 `describe-maintenance-windows` 예시에서는 현재 리전의 AWS 계정에 있는 모든 유지 관리 기간을 나열합니다.  

```
aws ssm describe-maintenance-windows
```
출력:  

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-0ecb1226ddEXAMPLE",
            "Name": "MyMaintenanceWindow-1",
            "Enabled": true,
            "Duration": 2,
            "Cutoff": 1,
            "Schedule": "rate(180 minutes)",
            "NextExecutionTime": "2020-02-12T23:19:20.596Z"
        },
        {
            "WindowId": "mw-03eb9db428EXAMPLE",
            "Name": "MyMaintenanceWindow-2",
            "Enabled": true,
            "Duration": 3,
            "Cutoff": 1,
            "Schedule": "rate(7 days)",
            "NextExecutionTime": "2020-02-17T23:22:00.956Z"
        },
    ]
}
```
**예제 2: 활성화된 모든 유지 관리 기간을 나열하는 방법**  
다음 `describe-maintenance-windows` 예제에서는 활성화된 모든 유지 관리 기간을 나열합니다.  

```
aws ssm describe-maintenance-windows \
    --filters "Key=Enabled,Values=true"
```
**예제 3: 특정 이름과 일치하는 유지 관리 기간을 나열하는 방법**  
이 `describe-maintenance-windows` 예제에서는 지정된 이름의 모든 유지 관리 기간을 나열합니다.  

```
aws ssm describe-maintenance-windows \
    --filters "Key=Name,Values=MyMaintenanceWindow"
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [유지 관리 기간에 대한 정보 보기(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeMaintenanceWindows](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-windows.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 계정의 모든 유지 관리 기간을 나열합니다.**  

```
Get-SSMMaintenanceWindowList
```
**출력:**  

```
Cutoff   : 1
Duration : 4
Enabled  : True
Name     : My-First-Maintenance-Window
WindowId : mw-06d59c1a07c022145
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeMaintenanceWindows](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 계정의 모든 유지 관리 기간을 나열합니다.**  

```
Get-SSMMaintenanceWindowList
```
**출력:**  

```
Cutoff   : 1
Duration : 4
Enabled  : True
Name     : My-First-Maintenance-Window
WindowId : mw-06d59c1a07c022145
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeMaintenanceWindows](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `DescribeOpsItems` 함께 사용
<a name="ssm_example_ssm_DescribeOpsItems_section"></a>

다음 코드 예시는 `DescribeOpsItems`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**OpsItems 세트를 나열하는 방법**  
다음 `describe-ops-items` 예시에서는 AWS 계정에서 열려 있는 모든 OpsItems 표시합니다.  

```
aws ssm describe-ops-items \
    --ops-item-filters "Key=Status,Values=Open,Operator=Equal"
```
출력:  

```
{
    "OpsItemSummaries": [
        {
            "CreatedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "CreatedTime": "2020-03-14T17:02:46.375000-07:00",
            "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "LastModifiedTime": "2020-03-14T17:02:46.375000-07:00",
            "Source": "SSM",
            "Status": "Open",
            "OpsItemId": "oi-7cfc5EXAMPLE",
            "Title": "SSM Maintenance Window execution failed",
            "OperationalData": {
                "/aws/dedup": {
                    "Value": "{\"dedupString\":\"SSMOpsItems-SSM-maintenance-window-execution-failed\"}",
                    "Type": "SearchableString"
                },
                "/aws/resources": {
                    "Value": "[{\"arn\":\"arn:aws:ssm:us-east-2:111222333444:maintenancewindow/mw-034093d322EXAMPLE\"}]",
                    "Type": "SearchableString"
                }
            },
            "Category": "Availability",
            "Severity": "3"
        },
        {
            "CreatedBy": "arn:aws:sts::1112223233444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "CreatedTime": "2020-02-26T11:43:15.426000-08:00",
            "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "LastModifiedTime": "2020-02-26T11:43:15.426000-08:00",
            "Source": "EC2",
            "Status": "Open",
            "OpsItemId": "oi-6f966EXAMPLE",
            "Title": "EC2 instance stopped",
            "OperationalData": {
                "/aws/automations": {
                    "Value": "[ { \"automationType\": \"AWS:SSM:Automation\", \"automationId\": \"AWS-RestartEC2Instance\" } ]",
                    "Type": "SearchableString"
                },
                "/aws/dedup": {
                    "Value": "{\"dedupString\":\"SSMOpsItems-EC2-instance-stopped\"}",
                    "Type": "SearchableString"
                },
                "/aws/resources": {
                    "Value": "[{\"arn\":\"arn:aws:ec2:us-east-2:111222333444:instance/i-0beccfbc02EXAMPLE\"}]",
                    "Type": "SearchableString"
                }
            },
            "Category": "Availability",
            "Severity": "3"
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [OpsItems 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeOpsItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-ops-items.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Describes AWS SSM OpsItems asynchronously.
     *
     * @param key The key to filter OpsItems by (e.g., OPS_ITEM_ID).
     *
     * This method initiates an asynchronous request to describe SSM OpsItems.
     * If the request is successful, it prints the title and status of each OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void describeOpsItems(String key) {
        OpsItemFilter filter = OpsItemFilter.builder()
                .key(OpsItemFilterKey.OPS_ITEM_ID)
                .values(key)
                .operator(OpsItemFilterOperator.EQUAL)
                .build();

        DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder()
                .maxResults(10)
                .opsItemFilters(filter)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().describeOpsItems(itemsRequest)
                    .thenAccept(itemsResponse -> {
                        List<OpsItemSummary> items = itemsResponse.opsItemSummaries();
                        for (OpsItemSummary item : items) {
                            System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString());
                        }
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API에 대한 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DescribeOpsItems](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DescribeOpsItems)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import {
  OpsItemFilterOperator,
  OpsItemFilterKey,
  paginateDescribeOpsItems,
  SSMClient,
} from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Describe SSM OpsItems.
 * @param {{ opsItemId: string }}
 */
export const main = async ({ opsItemId }) => {
  const client = new SSMClient({});
  try {
    const describeOpsItemsPaginated = [];
    for await (const page of paginateDescribeOpsItems(
      { client },
      {
        OpsItemFilters: {
          Key: OpsItemFilterKey.OPSITEM_ID,
          Operator: OpsItemFilterOperator.EQUAL,
          Values: opsItemId,
        },
      },
    )) {
      describeOpsItemsPaginated.push(...page.OpsItemSummaries);
    }
    console.log("Here are the ops items:");
    console.log(describeOpsItemsPaginated);
    return { OpsItemSummaries: describeOpsItemsPaginated };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide this value?`);
    }
    throw caught;
  }
};
```
+  API에 대한 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DescribeOpsItems](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DescribeOpsItemsCommand)를 참조하세요.

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

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def describe(self):
        """
        Describe an OpsItem.
        """
        try:
            paginator = self.ssm_client.get_paginator("describe_ops_items")
            ops_items = []
            for page in paginator.paginate(
                OpsItemFilters=[
                    {"Key": "OpsItemId", "Values": [self.id], "Operator": "Equal"}
                ]
            ):
                ops_items.extend(page["OpsItemSummaries"])

            for item in ops_items:
                print(
                    f"The item title is {item['Title']} and the status is {item['Status']}"
                )
            return len(ops_items) > 0
        except ClientError as err:
            logger.error(
                "Couldn't describe ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DescribeOpsItems](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DescribeOpsItems)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        " Create filter for OpsItem ID
        DATA(lt_filters) = VALUE /aws1/cl_ssmopsitemfilter=>tt_opsitemfilters(
          ( NEW /aws1/cl_ssmopsitemfilter(
              iv_key = 'OpsItemId'
              it_values = VALUE /aws1/cl_ssmopsitemfiltvals_w=>tt_opsitemfiltervalues(
                ( NEW /aws1/cl_ssmopsitemfiltvals_w( iv_value = iv_ops_item_id ) )
              )
              iv_operator = 'Equal'
            ) )
        ).

        " Use paginator to get all results
        DATA(lo_paginator) = lo_ssm->get_paginator( ).
        DATA(lo_iterator) = lo_paginator->describeopsitems(
          it_opsitemfilters = lt_filters ).

        rv_found = abap_false.

        WHILE lo_iterator->has_next( ).
          DATA(lo_result) = CAST /aws1/cl_ssmdescropsitemsrsp( lo_iterator->get_next( ) ).
          LOOP AT lo_result->get_opsitemsummaries( ) INTO DATA(lo_item).
            DATA(lv_title) = lo_item->get_title( ).
            DATA(lv_status) = lo_item->get_status( ).
            MESSAGE |The OpsItem title is { lv_title } and the status is { lv_status }| TYPE 'I'.
            rv_found = abap_true.
          ENDLOOP.
        ENDWHILE.
      CATCH /aws1/cx_ssminternalservererr.
        MESSAGE 'Internal server error occurred.' TYPE 'I'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DescribeOpsItems](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# AWS SDK 또는 CLI와 `DescribeParameters` 함께 사용
<a name="ssm_example_ssm_DescribeParameters_section"></a>

다음 코드 예시는 `DescribeParameters`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예 1: 모든 파라미터를 나열하는 방법**  
다음 `describe-parameters` 예시에서는 현재 AWS 계정 및 리전의 모든 파라미터를 나열합니다.  

```
aws ssm describe-parameters
```
출력:  

```
{
    "Parameters": [
        {
            "Name": "MySecureStringParameter",
            "Type": "SecureString",
            "KeyId": "alias/aws/ssm",
            "LastModifiedDate": 1582155479.205,
            "LastModifiedUser": "arn:aws:sts::111222333444:assumed-role/Admin/Richard-Roe-Managed",
            "Description": "This is a SecureString parameter",
            "Version": 2,
            "Tier": "Advanced",
            "Policies": [
                {
                    "PolicyText": "{\"Type\":\"Expiration\",\"Version\":\"1.0\",\"Attributes\":{\"Timestamp\":\"2020-07-07T22:30:00Z\"}}",
                    "PolicyType": "Expiration",
                    "PolicyStatus": "Pending"
                },
                {
                    "PolicyText": "{\"Type\":\"ExpirationNotification\",\"Version\":\"1.0\",\"Attributes\":{\"Before\":\"12\",\"Unit\":\"Hours\"}}",
                    "PolicyType": "ExpirationNotification",
                    "PolicyStatus": "Pending"
                }
            ]
        },
        {
            "Name": "MyStringListParameter",
            "Type": "StringList",
            "LastModifiedDate": 1582154764.222,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is a StringList parameter",
            "Version": 1,
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582154711.976,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Alejandro-Rosalez",
            "Description": "This is a String parameter",
            "Version": 1,
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "latestAmi",
            "Type": "String",
            "LastModifiedDate": 1580862415.521,
            "LastModifiedUser": "arn:aws:sts::111222333444:assumed-role/lambda-ssm-role/Automation-UpdateSSM-Param",
            "Version": 3,
            "Tier": "Standard",
            "Policies": []
        }
    ]
}
```
**예 2: 특정 메타데이터와 일치하는 모든 파라미터를 나열하는 방법**  
이 `describe-parameters` 예시에서는 필터와 일치하는 모든 파라미터를 나열합니다.  
aws ssm describe-parameters --filters "Key=Type,Values=StringList"  
출력:  

```
{
    "Parameters": [
        {
            "Name": "MyStringListParameter",
            "Type": "StringList",
            "LastModifiedDate": 1582154764.222,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is a StringList parameter",
            "Version": 1,
            "Tier": "Standard",
            "Policies": []
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 파라미터 검색](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-search.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribeParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-parameters.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.GetParameterRequest;
import software.amazon.awssdk.services.ssm.model.GetParameterResponse;
import software.amazon.awssdk.services.ssm.model.SsmException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class GetParameter {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <paraName>

                Where:
                    paraName - The name of the parameter.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String paraName = args[0];
        Region region = Region.US_EAST_1;
        SsmClient ssmClient = SsmClient.builder()
                .region(region)
                .build();

        getParaValue(ssmClient, paraName);
        ssmClient.close();
    }

    public static void getParaValue(SsmClient ssmClient, String paraName) {
        try {
            GetParameterRequest parameterRequest = GetParameterRequest.builder()
                    .name(paraName)
                    .build();

            GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest);
            System.out.println("The parameter value is " + parameterResponse.parameter().value());

        } catch (SsmException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API에 대한 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DescribeParameters](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DescribeParameters)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 모든 파라미터를 나열합니다.**  

```
Get-SSMParameterList
```
**출력:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:58:23 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribeParameters](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 모든 파라미터를 나열합니다.**  

```
Get-SSMParameterList
```
**출력:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:58:23 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribeParameters](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn show_parameters(client: &Client) -> Result<(), Error> {
    let resp = client.describe_parameters().send().await?;

    for param in resp.parameters() {
        println!("  {}", param.name().unwrap_or_default());
    }

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DescribeParameters](https://docs.rs/aws-sdk-ssm/latest/aws_sdk_ssm/client/struct.Client.html#method.describe_parameters)를 참조하세요.

------

# CLI로 `DescribePatchBaselines` 사용
<a name="ssm_example_ssm_DescribePatchBaselines_section"></a>

다음 코드 예시는 `DescribePatchBaselines`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 모든 패치 기준을 나열하는 방법**  
다음 `describe-patch-baselines` 예제에서는 현재 리전의 계정에서 모든 패치 기준에 대한 세부 정보를 가져옵니다.  

```
aws ssm describe-patch-baselines
```
출력:  

```
{
    "BaselineIdentities": [
        {
            "BaselineName": "AWS-SuseDefaultPatchBaseline",
            "DefaultBaseline": true,
            "BaselineDescription": "Default Patch Baseline for Suse Provided by AWS.",
            "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-0123fdb36e334a3b2",
            "OperatingSystem": "SUSE"
        },
        {
            "BaselineName": "AWS-DefaultPatchBaseline",
            "DefaultBaseline": false,
            "BaselineDescription": "Default Patch Baseline Provided by AWS.",
            "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-020d361a05defe4ed",
            "OperatingSystem": "WINDOWS"
        },
        ...
        {
            "BaselineName": "MyWindowsPatchBaseline",
            "DefaultBaseline": true,
            "BaselineDescription": "My patch baseline for EC2 instances for Windows Server",
            "BaselineId": "pb-0ad00e0dd7EXAMPLE",
            "OperatingSystem": "WINDOWS"
        }
    ]
}
```
**예제 2:에서 제공하는 모든 패치 기준을 나열하는 방법 AWS**  
다음 `describe-patch-baselines` 예시에서는에서 제공하는 모든 패치 기준을 나열합니다 AWS.  

```
aws ssm describe-patch-baselines \
    --filters "Key=OWNER,Values=[AWS]"
```
**예제 3: 소유한 모든 패치 기준을 나열하는 방법**  
다음 `describe-patch-baselines` 예제에서는 현재 리전의 계정에서 생성된 모든 사용자 지정 패치 기준을 나열합니다.  

```
aws ssm describe-patch-baselines \
    --filters "Key=OWNER,Values=[Self]"
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [사전 정의된 패치 기준 및 사용자 지정 패치 기준 정보](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baselines.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribePatchBaselines](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-patch-baselines.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 모든 패치 기준을 나열합니다.**  

```
Get-SSMPatchBaseline
```
**출력:**  

```
BaselineDescription                                             BaselineId                                                            BaselineName
-------------------                                             ----------                                                            ------------
Default Patch Baseline Provided by AWS.                         arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultP...
Baseline containing all updates approved for production systems pb-045f10b4f382baeda                                                  Production-B...
Baseline containing all updates approved for production systems pb-0a2f1059b670ebd31                                                  Production-B...
```
**예제 2:이 예제에서는에서 제공하는 모든 패치 기준을 나열합니다 AWS. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="OWNER";Values=@("AWS")}
```
**출력:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**예제 3: 이 예제에서는 사용자가 소유자인 모든 패치 기준을 나열합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="OWNER";Values=@("Self")}
```
**출력:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**예제 4: PowerShell 버전 2에서 각 태그를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "OWNER"
$filter1.Values = "AWS"

Get-SSMPatchBaseline -Filter $filter1
```
**출력:**  

```
BaselineDescription                     BaselineId                                                            BaselineName             DefaultBaselin
                                                                                                                                       e
-------------------                     ----------                                                            ------------             --------------
Default Patch Baseline Provided by AWS. arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultPatchBaseline True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribePatchBaselines](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 모든 패치 기준을 나열합니다.**  

```
Get-SSMPatchBaseline
```
**출력:**  

```
BaselineDescription                                             BaselineId                                                            BaselineName
-------------------                                             ----------                                                            ------------
Default Patch Baseline Provided by AWS.                         arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultP...
Baseline containing all updates approved for production systems pb-045f10b4f382baeda                                                  Production-B...
Baseline containing all updates approved for production systems pb-0a2f1059b670ebd31                                                  Production-B...
```
**예제 2:이 예제에서는에서 제공하는 모든 패치 기준을 나열합니다 AWS. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="OWNER";Values=@("AWS")}
```
**출력:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**예제 3: 이 예제에서는 사용자가 소유자인 모든 패치 기준을 나열합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="OWNER";Values=@("Self")}
```
**출력:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**예제 4: PowerShell 버전 2에서 각 태그를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "OWNER"
$filter1.Values = "AWS"

Get-SSMPatchBaseline -Filter $filter1
```
**출력:**  

```
BaselineDescription                     BaselineId                                                            BaselineName             DefaultBaselin
                                                                                                                                       e
-------------------                     ----------                                                            ------------             --------------
Default Patch Baseline Provided by AWS. arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultPatchBaseline True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribePatchBaselines](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribePatchGroupState` 사용
<a name="ssm_example_ssm_DescribePatchGroupState_section"></a>

다음 코드 예시는 `DescribePatchGroupState`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 그룹의 상태를 가져오는 방법**  
다음 `describe-patch-group-state` 예제에서는 패치 그룹에 대한 개요 수준의 패치 규정 준수 요약을 검색합니다.  

```
aws ssm describe-patch-group-state \
    --patch-group "Production"
```
출력:  

```
{
    "Instances": 21,
    "InstancesWithCriticalNonCompliantPatches": 1,
    "InstancesWithFailedPatches": 2,
    "InstancesWithInstalledOtherPatches": 3,
    "InstancesWithInstalledPatches": 21,
    "InstancesWithInstalledPendingRebootPatches": 2,
    "InstancesWithInstalledRejectedPatches": 1,
    "InstancesWithMissingPatches": 3,
    "InstancesWithNotApplicablePatches": 4,
    "InstancesWithOtherNonCompliantPatches": 1,
    "InstancesWithSecurityNonCompliantPatches": 1,
    "InstancesWithUnreportedNotApplicablePatches": 2
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 패치 그룹 정보(<https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-patchgroups.html>\$1\$1)와 [패치 규정 준수 상태 값 이해](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance-states.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribePatchGroupState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-patch-group-state.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 그룹에 대한 개요 수준의 패치 규정 준수 요약을 가져옵니다.**  

```
Get-SSMPatchGroupState -PatchGroup "Production"
```
**출력:**  

```
Instances                          : 4
InstancesWithFailedPatches         : 1
InstancesWithInstalledOtherPatches : 4
InstancesWithInstalledPatches      : 3
InstancesWithMissingPatches        : 0
InstancesWithNotApplicablePatches  : 0
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribePatchGroupState](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 그룹에 대한 개요 수준의 패치 규정 준수 요약을 가져옵니다.**  

```
Get-SSMPatchGroupState -PatchGroup "Production"
```
**출력:**  

```
Instances                          : 4
InstancesWithFailedPatches         : 1
InstancesWithInstalledOtherPatches : 4
InstancesWithInstalledPatches      : 3
InstancesWithMissingPatches        : 0
InstancesWithNotApplicablePatches  : 0
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribePatchGroupState](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DescribePatchGroups` 사용
<a name="ssm_example_ssm_DescribePatchGroups_section"></a>

다음 코드 예시는 `DescribePatchGroups`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 그룹 등록을 표시하는 방법**  
다음 `describe-patch-groups` 예제에서는 패치 그룹 등록을 나열합니다.  

```
aws ssm describe-patch-groups
```
출력:  

```
{
    "Mappings": [
        {
            "PatchGroup": "Production",
            "BaselineIdentity": {
                "BaselineId": "pb-0123456789abcdef0",
                "BaselineName": "ProdPatching",
                "OperatingSystem": "WINDOWS",
                "BaselineDescription": "Patches for Production",
                "DefaultBaseline": false
            }
        },
        {
            "PatchGroup": "Development",
            "BaselineIdentity": {
                "BaselineId": "pb-0713accee01234567",
                "BaselineName": "DevPatching",
                "OperatingSystem": "WINDOWS",
                "BaselineDescription": "Patches for Development",
                "DefaultBaseline": true
            }
        },
        ...
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 패치 그룹 생성(<https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-tagging.html>\$1\$1)과 [패치 기준에 패치 그룹 추가](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DescribePatchGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-patch-groups.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 그룹 등록을 나열합니다.**  

```
Get-SSMPatchGroup
```
**출력:**  

```
BaselineIdentity                                           PatchGroup
----------------                                           ----------
Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [DescribePatchGroups](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 그룹 등록을 나열합니다.**  

```
Get-SSMPatchGroup
```
**출력:**  

```
BaselineIdentity                                           PatchGroup
----------------                                           ----------
Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DescribePatchGroups](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetAutomationExecution` 사용
<a name="ssm_example_ssm_GetAutomationExecution_section"></a>

다음 코드 예시는 `GetAutomationExecution`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**자동화 실행에 대한 세부 정보를 표시하는 방법**  
다음 `get-automation-execution` 예제에서는 자동화 실행에 대한 세부 정보를 표시합니다.  

```
aws ssm get-automation-execution \
    --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE
```
출력:  

```
{
    "AutomationExecution": {
        "AutomationExecutionId": "73c8eef8-f4ee-4a05-820c-e354fEXAMPLE",
        "DocumentName": "AWS-StartEC2Instance",
        "DocumentVersion": "1",
        "ExecutionStartTime": 1583737233.748,
        "ExecutionEndTime": 1583737234.719,
        "AutomationExecutionStatus": "Success",
        "StepExecutions": [
            {
                "StepName": "startInstances",
                "Action": "aws:changeInstanceState",
                "ExecutionStartTime": 1583737234.134,
                "ExecutionEndTime": 1583737234.672,
                "StepStatus": "Success",
                "Inputs": {
                    "DesiredState": "\"running\"",
                    "InstanceIds": "[\"i-0cb99161f6EXAMPLE\"]"
                },
                "Outputs": {
                    "InstanceStates": [
                        "running"
                    ]
                },
                "StepExecutionId": "95e70479-cf20-4d80-8018-7e4e2EXAMPLE",
                "OverriddenParameters": {}
            }
        ],
        "StepExecutionsTruncated": false,
        "Parameters": {
            "AutomationAssumeRole": [
                ""
            ],
            "InstanceId": [
                "i-0cb99161f6EXAMPLE"
            ]
        },
        "Outputs": {},
        "Mode": "Auto",
        "ExecutedBy": "arn:aws:sts::29884EXAMPLE:assumed-role/mw_service_role/OrchestrationService",
        "Targets": [],
        "ResolvedTargets": {
            "ParameterValues": [],
            "Truncated": false
        }
    }
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [연습: Linux AMI 패치(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-walk-patch-linux-ami-cli.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetAutomationExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-automation-execution.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 자동화 실행의 세부 정보를 표시합니다.**  

```
Get-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
**출력:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
FailureMessage            : Step launchInstance failed maximum allowed times. You are not authorized to perform this operation. Encoded
                            authorization failure message: B_V2QyyN7NhSZQYpmVzpEc4oSnj2GLTNYnXUHsTbqJkNMoDgubmbtthLmZyaiUYekORIrA42-fv1x-04q5Fjff6glh
                            Yb6TI5b0GQeeNrpwNvpDzmO-PSR1swlAbg9fdM9BcNjyrznspUkWpuKu9EC1Ou6v3OXU1KC9nZ7mPlWMFZNkSioQqpwWEvMw-GZktsQzm67qOhUhBNOLWYhbS
                            pkfiqzY-5nw3S0obx30fhd3EJa5O_-GjV_a0nFXQJa70ik40bFOrEh3MtCSbrQT6--DvFy_FQ8TKvkIXadyVskeJI84XOF5WmA60f1pi5GI08i-nRfZS6oDeU
                            gELBjjoFKD8s3L2aI0B6umWVxnQOjqhQRxwJ53b54sZJ2PW3v_mtg9-q0CK0ezS3xfh_y0ilaUGOAZG-xjQFuvU_JZedWpla3xi-MZsmblAifBI
                            (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID:
                            6a002f94-ba37-43fd-99e6-39517715fce5)
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
Parameters                : {[AutomationAssumeRole, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [InstanceIamRole,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [SourceAmiId,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
StepExecutions            : {launchInstance, updateOSSoftware, stopInstance, createImage...}
```
**예제 2: 이 예제에서는 지정된 자동화 실행 ID에 대한 단계 세부 정보를 나열합니다.**  

```
Get-SSMAutomationExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object -ExpandProperty StepExecutions | Select-Object StepName, Action, StepStatus, ValidNextSteps
```
**출력:**  

```
StepName                  Action                  StepStatus ValidNextSteps
--------                  ------                  ---------- --------------
LaunchInstance            aws:runInstances        Success    {OSCompatibilityCheck}
OSCompatibilityCheck      aws:runCommand          Success    {RunPreUpdateScript}
RunPreUpdateScript        aws:runCommand          Success    {UpdateEC2Config}
UpdateEC2Config           aws:runCommand          Cancelled  {}
UpdateSSMAgent            aws:runCommand          Pending    {}
UpdateAWSPVDriver         aws:runCommand          Pending    {}
UpdateAWSEnaNetworkDriver aws:runCommand          Pending    {}
UpdateAWSNVMe             aws:runCommand          Pending    {}
InstallWindowsUpdates     aws:runCommand          Pending    {}
RunPostUpdateScript       aws:runCommand          Pending    {}
RunSysprepGeneralize      aws:runCommand          Pending    {}
StopInstance              aws:changeInstanceState Pending    {}
CreateImage               aws:createImage         Pending    {}
TerminateInstance         aws:changeInstanceState Pending    {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetAutomationExecution](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 자동화 실행의 세부 정보를 표시합니다.**  

```
Get-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
**출력:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
FailureMessage            : Step launchInstance failed maximum allowed times. You are not authorized to perform this operation. Encoded
                            authorization failure message: B_V2QyyN7NhSZQYpmVzpEc4oSnj2GLTNYnXUHsTbqJkNMoDgubmbtthLmZyaiUYekORIrA42-fv1x-04q5Fjff6glh
                            Yb6TI5b0GQeeNrpwNvpDzmO-PSR1swlAbg9fdM9BcNjyrznspUkWpuKu9EC1Ou6v3OXU1KC9nZ7mPlWMFZNkSioQqpwWEvMw-GZktsQzm67qOhUhBNOLWYhbS
                            pkfiqzY-5nw3S0obx30fhd3EJa5O_-GjV_a0nFXQJa70ik40bFOrEh3MtCSbrQT6--DvFy_FQ8TKvkIXadyVskeJI84XOF5WmA60f1pi5GI08i-nRfZS6oDeU
                            gELBjjoFKD8s3L2aI0B6umWVxnQOjqhQRxwJ53b54sZJ2PW3v_mtg9-q0CK0ezS3xfh_y0ilaUGOAZG-xjQFuvU_JZedWpla3xi-MZsmblAifBI
                            (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID:
                            6a002f94-ba37-43fd-99e6-39517715fce5)
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
Parameters                : {[AutomationAssumeRole, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [InstanceIamRole,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [SourceAmiId,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
StepExecutions            : {launchInstance, updateOSSoftware, stopInstance, createImage...}
```
**예제 2: 이 예제에서는 지정된 자동화 실행 ID에 대한 단계 세부 정보를 나열합니다.**  

```
Get-SSMAutomationExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object -ExpandProperty StepExecutions | Select-Object StepName, Action, StepStatus, ValidNextSteps
```
**출력:**  

```
StepName                  Action                  StepStatus ValidNextSteps
--------                  ------                  ---------- --------------
LaunchInstance            aws:runInstances        Success    {OSCompatibilityCheck}
OSCompatibilityCheck      aws:runCommand          Success    {RunPreUpdateScript}
RunPreUpdateScript        aws:runCommand          Success    {UpdateEC2Config}
UpdateEC2Config           aws:runCommand          Cancelled  {}
UpdateSSMAgent            aws:runCommand          Pending    {}
UpdateAWSPVDriver         aws:runCommand          Pending    {}
UpdateAWSEnaNetworkDriver aws:runCommand          Pending    {}
UpdateAWSNVMe             aws:runCommand          Pending    {}
InstallWindowsUpdates     aws:runCommand          Pending    {}
RunPostUpdateScript       aws:runCommand          Pending    {}
RunSysprepGeneralize      aws:runCommand          Pending    {}
StopInstance              aws:changeInstanceState Pending    {}
CreateImage               aws:createImage         Pending    {}
TerminateInstance         aws:changeInstanceState Pending    {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetCommandInvocation` 사용
<a name="ssm_example_ssm_GetCommandInvocation_section"></a>

다음 코드 예시는 `GetCommandInvocation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**명령 간접 호출의 세부 정보를 표시하는 방법**  
다음 `get-command-invocation` 예제에서는 지정된 인스턴스에서 지정된 명령의 모든 간접 호출을 나열합니다.  

```
aws ssm get-command-invocation \
    --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" \
    --instance-id "i-1234567890abcdef0"
```
출력:  

```
{
    "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678",
    "InstanceId": "i-1234567890abcdef0",
    "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
    "DocumentName": "AWS-UpdateSSMAgent",
    "DocumentVersion": "",
    "PluginName": "aws:updateSsmAgent",
    "ResponseCode": 0,
    "ExecutionStartDateTime": "2020-02-19T18:18:03.419Z",
    "ExecutionElapsedTime": "PT0.091S",
    "ExecutionEndDateTime": "2020-02-19T18:18:03.419Z",
    "Status": "Success",
    "StatusDetails": "Success",
    "StandardOutputContent": "Updating amazon-ssm-agent from 2.3.842.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\namazon-ssm-agent 2.3.842.0 has already been installed, update skipped\n",
    "StandardOutputUrl": "",
    "StandardErrorContent": "",
    "StandardErrorUrl": "",
    "CloudWatchOutputConfig": {
        "CloudWatchLogGroupName": "",
        "CloudWatchOutputEnabled": false
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [명령 상태 이해](https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetCommandInvocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-command-invocation.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스에서 실행된 명령의 세부 정보를 표시합니다.**  

```
Get-SSMCommandInvocationDetail -InstanceId "i-0cb2b964d3e14fd9f" -CommandId "b8eac879-0541-439d-94ec-47a80d554f44"
```
**출력:**  

```
CommandId              : b8eac879-0541-439d-94ec-47a80d554f44
Comment                : IP config
DocumentName           : AWS-RunShellScript
ExecutionElapsedTime   : PT0.004S
ExecutionEndDateTime   : 2017-02-22T20:13:16.651Z
ExecutionStartDateTime : 2017-02-22T20:13:16.651Z
InstanceId             : i-0cb2b964d3e14fd9f
PluginName             : aws:runShellScript
ResponseCode           : 0
StandardErrorContent   :
StandardErrorUrl       :
StandardOutputContent  :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetCommandInvocation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스에서 실행된 명령의 세부 정보를 표시합니다.**  

```
Get-SSMCommandInvocationDetail -InstanceId "i-0cb2b964d3e14fd9f" -CommandId "b8eac879-0541-439d-94ec-47a80d554f44"
```
**출력:**  

```
CommandId              : b8eac879-0541-439d-94ec-47a80d554f44
Comment                : IP config
DocumentName           : AWS-RunShellScript
ExecutionElapsedTime   : PT0.004S
ExecutionEndDateTime   : 2017-02-22T20:13:16.651Z
ExecutionStartDateTime : 2017-02-22T20:13:16.651Z
InstanceId             : i-0cb2b964d3e14fd9f
PluginName             : aws:runShellScript
ResponseCode           : 0
StandardErrorContent   :
StandardErrorUrl       :
StandardOutputContent  :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetCommandInvocation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetConnectionStatus` 사용
<a name="ssm_example_ssm_GetConnectionStatus_section"></a>

다음 코드 예시는 `GetConnectionStatus`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**관리형 인스턴스의 연결 상태를 표시하는 방법**  
이 `get-connection-status` 예제에서는 지정된 관리형 인스턴스의 연결 상태를 반환합니다.  

```
aws ssm get-connection-status \
    --target i-1234567890abcdef0
```
출력:  

```
{
    "Target": "i-1234567890abcdef0",
    "Status": "connected"
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetConnectionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-connection-status.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스의 세션 관리자 연결 상태를 검색하여 인스턴스가 연결되어 있고 세션 관리자 연결을 수신할 준비가 되었는지 확인합니다.**  

```
Get-SSMConnectionStatus -Target i-0a1caf234f12d3dc4
```
**출력:**  

```
Status    Target
------    ------
Connected i-0a1caf234f12d3dc4
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetConnectionStatus](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스의 세션 관리자 연결 상태를 검색하여 인스턴스가 연결되어 있고 세션 관리자 연결을 수신할 준비가 되었는지 확인합니다.**  

```
Get-SSMConnectionStatus -Target i-0a1caf234f12d3dc4
```
**출력:**  

```
Status    Target
------    ------
Connected i-0a1caf234f12d3dc4
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetDefaultPatchBaseline` 사용
<a name="ssm_example_ssm_GetDefaultPatchBaseline_section"></a>

다음 코드 예시는 `GetDefaultPatchBaseline`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 기본 Windows 패치 기준을 표시하는 방법**  
다음 `get-default-patch-baseline` 예제에서는 Windows Server의 기본 패치 기준에 대한 세부 정보를 검색합니다.  

```
aws ssm get-default-patch-baseline
```
출력:  

```
{
  "BaselineId": "pb-0713accee01612345",
  "OperatingSystem": "WINDOWS"
}
```
**예제 2: Amazon Linux의 기본 패치 기준을 표시하는 방법**  
다음 `get-default-patch-baseline` 예제에서는 Amazon Linux의 기본 패치 기준에 대한 세부 정보를 검색합니다.  

```
aws ssm get-default-patch-baseline \
    --operating-system AMAZON_LINUX
```
출력:  

```
{
    "BaselineId": "pb-047c6eb9c8fc12345",
    "OperatingSystem": "AMAZON_LINUX"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 사전 정의된 패치 기준 및 사용자 지정 패치 기준 정보(<https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baselines.html>\$1\$1)와 [기존 패치 기준을 기본값으로 설정](https://docs.aws.amazon.com/systems-manager/latest/userguide/set-default-patch-baseline.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetDefaultPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-default-patch-baseline.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 기본 패치 기준을 표시합니다.**  

```
Get-SSMDefaultPatchBaseline
```
**출력:**  

```
arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 기본 패치 기준을 표시합니다.**  

```
Get-SSMDefaultPatchBaseline
```
**출력:**  

```
arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetDeployablePatchSnapshotForInstance` 사용
<a name="ssm_example_ssm_GetDeployablePatchSnapshotForInstance_section"></a>

다음 코드 예시는 `GetDeployablePatchSnapshotForInstance`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**인스턴스에서 사용하는 패치 기준에 대한 현재 스냅샷을 검색하는 방법**  
다음 `get-deployable-patch-snapshot-for-instance` 예제에서는 인스턴스에서 사용하는 지정된 패치 기준의 현재 스냅샷에 대한 세부 정보를 검색합니다. 이 명령은 인스턴스 자격 증명을 사용하여 인스턴스에서 실행해야 합니다. 인스턴스 자격 증명을 사용하도록 하려면 `aws configure`를 실행하고 인스턴스의 리전만 지정합니다. `Access Key` 및 `Secret Key` 필드는 비워 둡니다.  
팁: `uuidgen`을 사용하여 `snapshot-id`를 생성합니다.  

```
aws ssm get-deployable-patch-snapshot-for-instance \
    --instance-id "i-1234567890abcdef0" \
    --snapshot-id "521c3536-930c-4aa9-950e-01234567abcd"
```
출력:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "SnapshotId": "521c3536-930c-4aa9-950e-01234567abcd",
    "Product": "AmazonLinux2018.03",
    "SnapshotDownloadUrl": "https://patch-baseline-snapshot-us-east-1.s3.amazonaws.com/ed85194ef27214f5984f28b4d664d14f7313568fea7d4b6ac6c10ad1f729d7e7-773304212436/AMAZON_LINUX-521c3536-930c-4aa9-950e-01234567abcd?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190215T164031Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAJ5C56P35AEBRX2QQ%2F20190215%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=efaaaf6e3878e77f48a6697e015efdbda9c426b09c5822055075c062f6ad2149"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [파라미터 이름: 스냅샷 ID](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-about-aws-runpatchbaseline.html#patch-manager-about-aws-runpatchbaseline-parameters-snapshot-id)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetDeployablePatchSnapshotForInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-deployable-patch-snapshot-for-instance.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스에서 사용하는 패치 기준의 현재 스냅샷을 표시합니다. 이 명령은 인스턴스 자격 증명을 사용하여 인스턴스에서 실행해야 합니다. 이 예제에서는 인스턴스 자격 증명을 사용하는지 확인하기 위해 자격 증명 파라미터에 `Amazon.Runtime.InstanceProfileAWSCredentials` 객체를 전달합니다.**  

```
$credentials = [Amazon.Runtime.InstanceProfileAWSCredentials]::new()
Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f" -Credentials $credentials
```
**출력:**  

```
InstanceId          SnapshotDownloadUrl
----------          -------------------
i-0cb2b964d3e14fd9f https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...1692/4681775b-098f-4435...
```
**예제 2: 이 예제에서는 전체 SnapshotDownloadUrl을 가져오는 방법을 보여줍니다. 이 명령은 인스턴스 자격 증명을 사용하여 인스턴스에서 실행해야 합니다. 인스턴스 자격 증명을 사용하는지 확인하기 위해 이 예제에서는 `Amazon.Runtime.InstanceProfileAWSCredentials` 객체를 사용하도록 PowerShell 세션을 구성합니다.**  

```
Set-AWSCredential -Credential ([Amazon.Runtime.InstanceProfileAWSCredentials]::new())
(Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f").SnapshotDownloadUrl
```
**출력:**  

```
https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetDeployablePatchSnapshotForInstance](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스에서 사용하는 패치 기준의 현재 스냅샷을 표시합니다. 이 명령은 인스턴스 자격 증명을 사용하여 인스턴스에서 실행해야 합니다. 이 예제에서는 인스턴스 자격 증명을 사용하는지 확인하기 위해 자격 증명 파라미터에 `Amazon.Runtime.InstanceProfileAWSCredentials` 객체를 전달합니다.**  

```
$credentials = [Amazon.Runtime.InstanceProfileAWSCredentials]::new()
Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f" -Credentials $credentials
```
**출력:**  

```
InstanceId          SnapshotDownloadUrl
----------          -------------------
i-0cb2b964d3e14fd9f https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...1692/4681775b-098f-4435...
```
**예제 2: 이 예제에서는 전체 SnapshotDownloadUrl을 가져오는 방법을 보여줍니다. 이 명령은 인스턴스 자격 증명을 사용하여 인스턴스에서 실행해야 합니다. 인스턴스 자격 증명을 사용하는지 확인하기 위해 이 예제에서는 `Amazon.Runtime.InstanceProfileAWSCredentials` 객체를 사용하도록 PowerShell 세션을 구성합니다.**  

```
Set-AWSCredential -Credential ([Amazon.Runtime.InstanceProfileAWSCredentials]::new())
(Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f").SnapshotDownloadUrl
```
**출력:**  

```
https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetDeployablePatchSnapshotForInstance](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetDocument` 사용
<a name="ssm_example_ssm_GetDocument_section"></a>

다음 코드 예시는 `GetDocument`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서 콘텐츠를 가져오는 방법**  
다음 `get-document` 예제에서는 Systems Manager 문서의 콘텐츠를 표시합니다.  

```
aws ssm get-document \
    --name "AWS-RunShellScript"
```
출력:  

```
{
    "Name": "AWS-RunShellScript",
    "DocumentVersion": "1",
    "Status": "Active",
    "Content": "{\n    \"schemaVersion\":\"1.2\",\n    \"description\":\"Run a shell script or specify the commands to run.\",\n    \"parameters\":{\n        \"commands\":{\n            \"type\":\"StringList\",\n            \"description\":\"(Required) Specify a shell script or a command to run.\",\n            \"minItems\":1,\n            \"displayType\":\"textarea\"\n        },\n        \"workingDirectory\":{\n            \"type\":\"String\",\n            \"default\":\"\",\n            \"description\":\"(Optional) The path to the working directory on your instance.\",\n            \"maxChars\":4096\n        },\n        \"executionTimeout\":{\n            \"type\":\"String\",\n            \"default\":\"3600\",\n            \"description\":\"(Optional) The time in seconds for a command to complete before it is considered to have failed. Default is 3600 (1 hour). Maximum is 172800 (48 hours).\",\n            \"allowedPattern\":\"([1-9][0-9]{0,4})|(1[0-6][0-9]{4})|(17[0-1][0-9]{3})|(172[0-7][0-9]{2})|(172800)\"\n        }\n    },\n    \"runtimeConfig\":{\n        \"aws:runShellScript\":{\n            \"properties\":[\n                {\n                    \"id\":\"0.aws:runShellScript\",\n                    \"runCommand\":\"{{ commands }}\",\n                    \"workingDirectory\":\"{{ workingDirectory }}\",\n                    \"timeoutSeconds\":\"{{ executionTimeout }}\"\n                }\n            ]\n        }\n    }\n}\n",
    "DocumentType": "Command",
    "DocumentFormat": "JSON"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [AWS Systems Manager 문서](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-document.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 문서의 콘텐츠를 반환합니다.**  

```
Get-SSMDocument -Name "RunShellScript"
```
**출력:**  

```
Content
-------
{...
```
**예제 2: 이 예제에서는 문서의 전체 콘텐츠를 표시합니다.**  

```
(Get-SSMDocument -Name "RunShellScript").Content
{
   "schemaVersion":"2.0",
   "description":"Run an updated script",
   "parameters":{
      "commands":{
         "type":"StringList",
         "description":"(Required) Specify a shell script or a command to run.",
         "minItems":1,
         "displayType":"textarea"
      }
   },
   "mainSteps":[
      {
         "action":"aws:runShellScript",
         "name":"runShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      },
      {
         "action":"aws:runPowerShellScript",
         "name":"runPowerShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      }
   ]
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetDocument](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 문서의 콘텐츠를 반환합니다.**  

```
Get-SSMDocument -Name "RunShellScript"
```
**출력:**  

```
Content
-------
{...
```
**예제 2: 이 예제에서는 문서의 전체 콘텐츠를 표시합니다.**  

```
(Get-SSMDocument -Name "RunShellScript").Content
{
   "schemaVersion":"2.0",
   "description":"Run an updated script",
   "parameters":{
      "commands":{
         "type":"StringList",
         "description":"(Required) Specify a shell script or a command to run.",
         "minItems":1,
         "displayType":"textarea"
      }
   },
   "mainSteps":[
      {
         "action":"aws:runShellScript",
         "name":"runShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      },
      {
         "action":"aws:runPowerShellScript",
         "name":"runPowerShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      }
   ]
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetDocument](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetInventory` 사용
<a name="ssm_example_ssm_GetInventory_section"></a>

다음 코드 예시는 `GetInventory`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**인벤토리 페이지를 보는 방법**  
이 예제에서는 인벤토리의 사용자 지정 메타데이터를 가져옵니다.  
명령:  

```
aws ssm get-inventory
```
출력:  

```
{
  "Entities": [
      {
          "Data": {
              "AWS:InstanceInformation": {
                  "Content": [
                      {
                          "ComputerName": "ip-172-31-44-222.us-west-2.compute.internal",
                          "InstanceId": "i-0cb2b964d3e14fd9f",
                          "IpAddress": "172.31.44.222",
                          "AgentType": "amazon-ssm-agent",
                          "ResourceType": "EC2Instance",
                          "AgentVersion": "2.0.672.0",
                          "PlatformVersion": "2016.09",
                          "PlatformName": "Amazon Linux AMI",
                          "PlatformType": "Linux"
                      }
                  ],
                  "TypeName": "AWS:InstanceInformation",
                  "SchemaVersion": "1.0",
                  "CaptureTime": "2017-02-20T18:03:58Z"
              }
          },
          "Id": "i-0cb2b964d3e14fd9f"
      }
  ]
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetInventory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-inventory.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인벤토리의 사용자 지정 메타데이터를 가져옵니다.**  

```
Get-SSMInventory
```
**출력:**  

```
Data                                                                                  Id
----                                                                                  --
{[AWS:InstanceInformation, Amazon.SimpleSystemsManagement.Model.InventoryResultItem]} i-0cb2b964d3e14fd9f
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetInventory](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인벤토리의 사용자 지정 메타데이터를 가져옵니다.**  

```
Get-SSMInventory
```
**출력:**  

```
Data                                                                                  Id
----                                                                                  --
{[AWS:InstanceInformation, Amazon.SimpleSystemsManagement.Model.InventoryResultItem]} i-0cb2b964d3e14fd9f
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetInventory](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetInventorySchema` 사용
<a name="ssm_example_ssm_GetInventorySchema_section"></a>

다음 코드 예시는 `GetInventorySchema`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**인벤토리 스키마를 보는 방법**  
이 예제에서는 계정의 인벤토리 유형 이름 목록을 반환합니다.  
명령:  

```
aws ssm get-inventory-schema
```
출력:  

```
{
  "Schemas": [
      {
          "TypeName": "AWS:AWSComponent",
          "Version": "1.0",
          "Attributes": [
              {
                  "Name": "Name",
                  "DataType": "STRING"
              },
              {
                  "Name": "ApplicationType",
                  "DataType": "STRING"
              },
              {
                  "Name": "Publisher",
                  "DataType": "STRING"
              },
              {
                  "Name": "Version",
                  "DataType": "STRING"
              },
              {
                  "Name": "InstalledTime",
                  "DataType": "STRING"
              },
              {
                  "Name": "Architecture",
                  "DataType": "STRING"
              },
              {
                  "Name": "URL",
                  "DataType": "STRING"
              }
          ]
      },
      ...
  ],
  "NextToken": "--token string truncated--"
}
```
**특정 인벤토리 유형의 인벤토리 스키마를 보는 방법**  
이 예제에서는 AWS:AWS Component 인벤토리 유형에 대한 인벤토리 스키마를 반환합니다.  
명령:  

```
aws ssm get-inventory-schema --type-name "AWS:AWSComponent"
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetInventorySchema](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-inventory-schema.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 계정의 인벤토리 유형 이름 목록을 반환합니다.**  

```
Get-SSMInventorySchema
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetInventorySchema](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 계정의 인벤토리 유형 이름 목록을 반환합니다.**  

```
Get-SSMInventorySchema
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetInventorySchema](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetMaintenanceWindow` 사용
<a name="ssm_example_ssm_GetMaintenanceWindow_section"></a>

다음 코드 예시는 `GetMaintenanceWindow`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**유지 관리 기간에 대한 정보를 가져오는 방법**  
다음 `get-maintenance-window` 예제에서는 지정된 유지 관리 기간에 대한 세부 정보를 검색합니다.  

```
aws ssm get-maintenance-window \
    --window-id "mw-03eb9db428EXAMPLE"
```
출력:  

```
{
    "AllowUnassociatedTargets": true,
    "CreatedDate": 1515006912.957,
    "Cutoff": 1,
    "Duration": 6,
    "Enabled": true,
    "ModifiedDate": 2020-01-01T10:04:04.099Z,
    "Name": "My-Maintenance-Window",
    "Schedule": "rate(3 days)",
    "WindowId": "mw-03eb9db428EXAMPLE",
    "NextExecutionTime": "2020-02-25T00:08:15.099Z"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [유지 관리 기간에 대한 정보 보기(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간에 대한 세부 정보를 가져옵니다.**  

```
Get-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d"
```
**출력:**  

```
AllowUnassociatedTargets : False
CreatedDate              : 2/20/2017 6:14:05 PM
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
ModifiedDate             : 2/20/2017 6:14:05 PM
Name                     : TestMaintWin
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간에 대한 세부 정보를 가져옵니다.**  

```
Get-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d"
```
**출력:**  

```
AllowUnassociatedTargets : False
CreatedDate              : 2/20/2017 6:14:05 PM
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
ModifiedDate             : 2/20/2017 6:14:05 PM
Name                     : TestMaintWin
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetMaintenanceWindowExecution` 사용
<a name="ssm_example_ssm_GetMaintenanceWindowExecution_section"></a>

다음 코드 예시는 `GetMaintenanceWindowExecution`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**유지 관리 기간 작업 실행에 대한 정보를 가져오는 방법**  
다음 `get-maintenance-window-execution` 예제에서는 지정된 유지 관리 기간 실행의 일부로 실행된 작업에 대한 정보를 나열합니다.  

```
aws ssm get-maintenance-window-execution \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE"
```
출력:  

```
{
    "Status": "SUCCESS",
    "TaskIds": [
        "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE"
    ],
    "StartTime": 1487692834.595,
    "EndTime": 1487692835.051,
    "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE",
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [작업 및 작업 실행(AWS CLI)에 대한 정보 보기를 참조하세요](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html).  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetMaintenanceWindowExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window-execution.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간 실행의 일부로 실행된 작업에 대한 정보를 나열합니다.**  

```
Get-SSMMaintenanceWindowExecution -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
TaskIds           : {ac0c6ae1-daa3-4a89-832e-d384503b6586}
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetMaintenanceWindowExecution](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간 실행의 일부로 실행된 작업에 대한 정보를 나열합니다.**  

```
Get-SSMMaintenanceWindowExecution -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
TaskIds           : {ac0c6ae1-daa3-4a89-832e-d384503b6586}
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetMaintenanceWindowExecution](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetMaintenanceWindowExecutionTask` 사용
<a name="ssm_example_ssm_GetMaintenanceWindowExecutionTask_section"></a>

다음 코드 예시는 `GetMaintenanceWindowExecutionTask`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**유지 관리 기간 작업 실행에 대한 정보를 가져오는 방법**  
다음 `get-maintenance-window-execution-task` 예제에서는 지정된 유지 관리 기간 실행의 일부인 작업에 대한 정보를 나열합니다.  

```
aws ssm get-maintenance-window-execution-task \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE" \
    --task-id "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE"
```
출력:  

```
{
    "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE",
    "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE",
    "TaskArn": "AWS-RunPatchBaseline",
    "ServiceRole": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
    "Type": "RUN_COMMAND",
    "TaskParameters": [
        {
            "BaselineOverride": {
                "Values": [
                    ""
                ]
            },
            "InstallOverrideList": {
                "Values": [
                    ""
                ]
            },
            "Operation": {
                "Values": [
                    "Scan"
                ]
            },
            "RebootOption": {
                "Values": [
                    "RebootIfNeeded"
                ]
            },
            "SnapshotId": {
                "Values": [
                    "{{ aws:ORCHESTRATION_ID }}"
                ]
            },
            "aws:InstanceId": {
                "Values": [
                    "i-02573cafcfEXAMPLE",
                    "i-0471e04240EXAMPLE",
                    "i-07782c72faEXAMPLE"
                ]
            }
        }
    ],
    "Priority": 1,
    "MaxConcurrency": "1",
    "MaxErrors": "3",
    "Status": "SUCCESS",
    "StartTime": "2021-08-04T11:45:35.088000-07:00",
    "EndTime": "2021-08-04T11:53:09.079000-07:00"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [작업 및 작업 실행(AWS CLI)에 대한 정보 보기를 참조하세요](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html).  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetMaintenanceWindowExecutionTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window-execution-task.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간 실행의 일부였던 작업에 대한 정보를 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionTask -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:35 PM
MaxConcurrency    : 1
MaxErrors         : 1
Priority          : 10
ServiceRole       : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The maximum error count was exceeded.
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskParameters    : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskPara
                    meterValueExpression]}
Type              : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetMaintenanceWindowExecutionTask](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간 실행의 일부였던 작업에 대한 정보를 나열합니다.**  

```
Get-SSMMaintenanceWindowExecutionTask -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**출력:**  

```
EndTime           : 2/21/2017 4:00:35 PM
MaxConcurrency    : 1
MaxErrors         : 1
Priority          : 10
ServiceRole       : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The maximum error count was exceeded.
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskParameters    : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskPara
                    meterValueExpression]}
Type              : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetMaintenanceWindowExecutionTask](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `GetParameter` 함께 사용
<a name="ssm_example_ssm_GetParameter_section"></a>

다음 코드 예시는 `GetParameter`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 파라미터 값을 표시하는 방법**  
다음 `get-parameter` 예제에서는 지정된 단일 파라미터의 값을 나열합니다.  

```
aws ssm get-parameter \
    --name "MyStringParameter"
```
출력:  

```
{
    "Parameter": {
        "Name": "MyStringParameter",
        "Type": "String",
        "Value": "Veni",
        "Version": 1,
        "LastModifiedDate": 1530018761.888,
        "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MyStringParameter"
        "DataType": "text"
    }
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Parameter Store 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)을 참조하세요.  
**예제 2: SecureString 파라미터의 값을 해독하는 방법**  
다음 `get-parameter` 예제에서는 지정된 `SecureString` 파라미터의 값을 해독합니다.  

```
aws ssm get-parameter \
    --name "MySecureStringParameter" \
    --with-decryption
```
출력:  

```
{
    "Parameter": {
        "Name": "MySecureStringParameter",
        "Type": "SecureString",
        "Value": "16679b88-310b-4895-a943-e0764EXAMPLE",
        "Version": 2,
        "LastModifiedDate": 1582155479.205,
        "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MySecureStringParameter"
        "DataType": "text"
    }
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Parameter Store 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)을 참조하세요.  
**예제 3: 레이블을 사용하여 파라미터 값을 표시하는 방법**  
다음 `get-parameter` 예제에서는 지정된 레이블을 포함하는 지정된 단일 파라미터 값을 나열합니다.  

```
aws ssm get-parameter \
    --name "MyParameter:label"
```
출력:  

```
{
    "Parameter": {
        "Name": "MyParameter",
        "Type": "String",
        "Value": "parameter version 2",
        "Version": 2,
        "Selector": ":label",
        "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00",
        "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter",
        "DataType": "text"
    }
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [파라미터 레이블 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)을 참조하세요.  
**예제 4: 버전을 사용하여 파라미터 값을 표시하는 방법**  
다음 `get-parameter` 예제에서는 지정된 단일 파라미터 버전의 값을 나열합니다.  

```
aws ssm get-parameter \
    --name "MyParameter:2"
```
출력:  

```
{
    "Parameter": {
        "Name": "MyParameter",
        "Type": "String",
        "Value": "parameter version 2",
        "Version": 2,
        "Selector": ":2",
        "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00",
        "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter",
        "DataType": "text"
    }
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [파라미터 레이블 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetParameter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-parameter.html)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    pub async fn list_path(&self, path: &str) -> Result<Vec<Parameter>, EC2Error> {
        let maybe_params: Vec<Result<Parameter, _>> = TryFlatMap::new(
            self.inner
                .get_parameters_by_path()
                .path(path)
                .into_paginator()
                .send(),
        )
        .flat_map(|item| item.parameters.unwrap_or_default())
        .collect()
        .await;
        // Fail on the first error
        let params = maybe_params
            .into_iter()
            .collect::<Result<Vec<Parameter>, _>>()?;
        Ok(params)
    }
```
+  API 세부 정보는 **AWS SDK for Rust API 참조의 [GetParameter](https://docs.rs/aws-sdk-ssm/latest/aws_sdk_ssm/client/struct.Client.html#method.get_parameter)를 참조하세요.

------

# CLI로 `GetParameterHistory` 사용
<a name="ssm_example_ssm_GetParameterHistory_section"></a>

다음 코드 예시는 `GetParameterHistory`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**파라미터 값 기록을 가져오는 방법**  
다음 `get-parameter-history` 예제에서는 해당 값을 포함하여 지정된 파라미터의 변경 기록을 나열합니다.  

```
aws ssm get-parameter-history \
    --name "MyStringParameter"
```
출력:  

```
{
    "Parameters": [
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582154711.976,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is the first version of my String parameter",
            "Value": "Veni",
            "Version": 1,
            "Labels": [],
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582156093.471,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is the second version of my String parameter",
            "Value": "Vidi",
            "Version": 2,
            "Labels": [],
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582156117.545,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is the third version of my String parameter",
            "Value": "Vici",
            "Version": 3,
            "Labels": [],
            "Tier": "Standard",
            "Policies": []
        }
    ]
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [파라미터 버전 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-versions.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetParameterHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-parameter-history.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 파라미터 값 기록을 나열합니다.**  

```
Get-SSMParameterHistory -Name "Welcome"
```
**출력:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:55:25 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
Value            : helloWorld
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetParameterHistory](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 파라미터 값 기록을 나열합니다.**  

```
Get-SSMParameterHistory -Name "Welcome"
```
**출력:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:55:25 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
Value            : helloWorld
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetParameterHistory](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetParameters` 사용
<a name="ssm_example_ssm_GetParameters_section"></a>

다음 코드 예시는 `GetParameters`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 파라미터 값을 나열하는 방법**  
다음 `get-parameters` 예제에서는 지정된 세 개의 파라미터 값을 나열합니다.  

```
aws ssm get-parameters \
    --names "MyStringParameter" "MyStringListParameter" "MyInvalidParameterName"
```
출력:  

```
{
    "Parameters": [
        {
            "Name": "MyStringListParameter",
            "Type": "StringList",
            "Value": "alpha,beta,gamma",
            "Version": 1,
            "LastModifiedDate": 1582154764.222,
            "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MyStringListParameter"
            "DataType": "text"
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "Value": "Vici",
            "Version": 3,
            "LastModifiedDate": 1582156117.545,
            "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MyStringParameter"
            "DataType": "text"
        }
    ],
    "InvalidParameters": [
        "MyInvalidParameterName"
    ]
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Parameter Store 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)을 참조하세요.  
**예제 2: ''--query'' 옵션을 사용하여 여러 파라미터의 이름과 값을 나열하는 방법**  
다음 `get-parameters` 예제에서는 지정된 파라미터의 이름 및 값을 나열합니다.  

```
aws ssm get-parameters \
    --names MyStringParameter MyStringListParameter \
    --query "Parameters[*].{Name:Name,Value:Value}"
```
출력:  

```
[
    {
        "Name": "MyStringListParameter",
        "Value": "alpha,beta,gamma"
    },
    {
        "Name": "MyStringParameter",
        "Value": "Vidi"
    }
]
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Parameter Store 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)을 참조하세요.  
**예제 3: 레이블을 사용하여 파라미터 값을 표시하는 방법**  
다음 `get-parameter` 예제에서는 지정된 레이블을 포함하는 지정된 단일 파라미터 값을 나열합니다.  

```
aws ssm get-parameter \
    --name "MyParameter:label"
```
출력:  

```
{
    "Parameters": [
        {
            "Name": "MyLabelParameter",
            "Type": "String",
            "Value": "parameter by label",
            "Version": 1,
            "Selector": ":label",
            "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00",
            "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter",
            "DataType": "text"
        },
        {
            "Name": "MyVersionParameter",
            "Type": "String",
            "Value": "parameter by version",
            "Version": 2,
            "Selector": ":2",
            "LastModifiedDate": "2021-03-24T16:20:28.236000-07:00",
            "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/unlabel-param",
            "DataType": "text"
        }
    ],
    "InvalidParameters": []
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [파라미터 레이블 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-parameters.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 파라미터 값을 나열합니다.**  

```
Get-SSMParameterValue -Name "Welcome"
```
**출력:**  

```
InvalidParameters Parameters
----------------- ----------
{}                {Welcome}
```
**예제 2: 이 예제에서는 값의 세부 정보를 나열합니다.**  

```
(Get-SSMParameterValue -Name "Welcome").Parameters
```
**출력:**  

```
Name    Type   Value
----    ----   -----
Welcome String Good day, Sunshine!
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetParameters](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 파라미터 값을 나열합니다.**  

```
Get-SSMParameterValue -Name "Welcome"
```
**출력:**  

```
InvalidParameters Parameters
----------------- ----------
{}                {Welcome}
```
**예제 2: 이 예제에서는 값의 세부 정보를 나열합니다.**  

```
(Get-SSMParameterValue -Name "Welcome").Parameters
```
**출력:**  

```
Name    Type   Value
----    ----   -----
Welcome String Good day, Sunshine!
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetParameters](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetPatchBaseline` 사용
<a name="ssm_example_ssm_GetPatchBaseline_section"></a>

다음 코드 예시는 `GetPatchBaseline`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 기준을 표시하는 방법**  
다음 `get-patch-baseline` 예제에서는 지정된 패치 기준에 대한 세부 정보를 검색합니다.  

```
aws ssm get-patch-baseline \
    --baseline-id "pb-0123456789abcdef0"
```
출력:  

```
{
    "BaselineId": "pb-0123456789abcdef0",
    "Name": "WindowsPatching",
    "OperatingSystem": "WINDOWS",
    "GlobalFilters": {
        "PatchFilters": []
    },
    "ApprovalRules": {
        "PatchRules": [
            {
                "PatchFilterGroup": {
                    "PatchFilters": [
                        {
                            "Key": "PRODUCT",
                            "Values": [
                                "WindowsServer2016"
                            ]
                        }
                    ]
                },
                "ComplianceLevel": "CRITICAL",
                "ApproveAfterDays": 0,
                "EnableNonSecurity": false
            }
        ]
    },
    "ApprovedPatches": [],
    "ApprovedPatchesComplianceLevel": "UNSPECIFIED",
    "ApprovedPatchesEnableNonSecurity": false,
    "RejectedPatches": [],
    "RejectedPatchesAction": "ALLOW_AS_DEPENDENCY",
    "PatchGroups": [
        "QA",
        "DEV"
    ],
    "CreatedDate": 1550244180.465,
    "ModifiedDate": 1550244180.465,
    "Description": "Patches for Windows Servers",
    "Sources": []
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [패치 기준 정보](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-baselines.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-patch-baseline.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 기준의 세부 정보를 표시합니다.**  

```
Get-SSMPatchBaselineDetail -BaselineId "pb-03da896ca3b68b639"
```
**출력:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:02:19 PM
Name            : Production-Baseline
PatchGroups     : {}
RejectedPatches : {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 기준의 세부 정보를 표시합니다.**  

```
Get-SSMPatchBaselineDetail -BaselineId "pb-03da896ca3b68b639"
```
**출력:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:02:19 PM
Name            : Production-Baseline
PatchGroups     : {}
RejectedPatches : {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetPatchBaselineForPatchGroup` 사용
<a name="ssm_example_ssm_GetPatchBaselineForPatchGroup_section"></a>

다음 코드 예시는 `GetPatchBaselineForPatchGroup`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 그룹의 패치 기준을 표시하는 방법**  
다음 `get-patch-baseline-for-patch-group` 예제에서는 지정된 패치 그룹의 패치 기준에 대한 세부 정보를 검색합니다.  

```
aws ssm get-patch-baseline-for-patch-group \
    --patch-group "DEV"
```
출력:  

```
{
    "PatchGroup": "DEV",
    "BaselineId": "pb-0123456789abcdef0",
    "OperatingSystem": "WINDOWS"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 패치 그룹 생성(<https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-tagging.html>\$1\$1)과 [패치 기준에 패치 그룹 추가](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetPatchBaselineForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-patch-baseline-for-patch-group.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 그룹의 패치 기준을 표시합니다.**  

```
Get-SSMPatchBaselineForPatchGroup -PatchGroup "Production"
```
**출력:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [GetPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 그룹의 패치 기준을 표시합니다.**  

```
Get-SSMPatchBaselineForPatchGroup -PatchGroup "Production"
```
**출력:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `ListAssociationVersions` 사용
<a name="ssm_example_ssm_ListAssociationVersions_section"></a>

다음 코드 예시는 `ListAssociationVersions`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**특정 연결 ID의 모든 연결 버전을 가져오는 방법**  
다음 `list-association-versions` 예제에서는 지정된 연결의 모든 버전을 나열합니다.  

```
aws ssm list-association-versions \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
출력:  

```
{
"AssociationVersions": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "CreatedDate": 1550505536.726,
            "Name": "AWS-UpdateSSMAgent",
            "Parameters": {
                "allowDowngrade": [
                    "false"
                ],
                "version": [
                    ""
                ]
            },
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-1234567890abcdef0"
                    ]
                }
            ],
            "ScheduleExpression": "cron(0 00 12 ? * SUN *)",
            "AssociationName": "UpdateSSMAgent"
        }
    ]
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Systems Manager에서 연결 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListAssociationVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-association-versions.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 제공된 연결의 모든 버전을 검색합니다.**  

```
Get-SSMAssociationVersionList -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**출력:**  

```
AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    :
AssociationVersion : 2
ComplianceSeverity :
CreatedDate        : 3/12/2019 9:21:01 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression :
Targets            : {InstanceIds}

AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    : test-case-1234567890
AssociationVersion : 1
ComplianceSeverity :
CreatedDate        : 3/2/2019 8:53:29 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression : rate(30minutes)
Targets            : {InstanceIds}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListAssociationVersions](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 제공된 연결의 모든 버전을 검색합니다.**  

```
Get-SSMAssociationVersionList -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**출력:**  

```
AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    :
AssociationVersion : 2
ComplianceSeverity :
CreatedDate        : 3/12/2019 9:21:01 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression :
Targets            : {InstanceIds}

AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    : test-case-1234567890
AssociationVersion : 1
ComplianceSeverity :
CreatedDate        : 3/2/2019 8:53:29 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression : rate(30minutes)
Targets            : {InstanceIds}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListAssociationVersions](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListAssociations` 사용
<a name="ssm_example_ssm_ListAssociations_section"></a>

다음 코드 예시는 `ListAssociations`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 특정 인스턴스의 연결을 나열하는 방법**  
다음 list-associations 예제에서는 AssociationName인 UpdateSSMAgent인 모든 연결을 나열합니다.  

```
aws ssm list-associations /
    --association-filter-list "key=AssociationName,value=UpdateSSMAgent"
```
출력:  

```
{
    "Associations": [
        {
            "Name": "AWS-UpdateSSMAgent",
            "InstanceId": "i-1234567890abcdef0",
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-016648b75dd622dab"
                    ]
                }
            ],
            "Overview": {
                "Status": "Pending",
                "DetailedStatus": "Associated",
                "AssociationStatusAggregatedCount": {
                    "Pending": 1
                }
            },
            "ScheduleExpression": "cron(0 00 12 ? * SUN *)",
            "AssociationName": "UpdateSSMAgent"
        }
    ]
}
```
자세한 내용은 ** Systems Manager 사용 설명서의 [Systems Manager에서 연결 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)을 참조하세요.  
**예제 2: 특정 문서의 연결을 나열하는 방법**  
다음 list-associations 예제에서는 지정된 문서의 모든 연결을 나열합니다.  

```
aws ssm list-associations /
    --association-filter-list "key=Name,value=AWS-UpdateSSMAgent"
```
출력:  

```
{
    "Associations": [
        {
            "Name": "AWS-UpdateSSMAgent",
            "InstanceId": "i-1234567890abcdef0",
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-1234567890abcdef0"
                    ]
                }
            ],
            "LastExecutionDate": 1550505828.548,
            "Overview": {
                "Status": "Success",
                "DetailedStatus": "Success",
                "AssociationStatusAggregatedCount": {
                    "Success": 1
                }
            },
            "ScheduleExpression": "cron(0 00 12 ? * SUN *)",
            "AssociationName": "UpdateSSMAgent"
        },
    {
            "Name": "AWS-UpdateSSMAgent",
            "InstanceId": "i-9876543210abcdef0",
            "AssociationId": "fbc07ef7-b985-4684-b82b-0123456789ab",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-9876543210abcdef0"
                    ]
                }
            ],
            "LastExecutionDate": 1550507531.0,
            "Overview": {
                "Status": "Success",
                "AssociationStatusAggregatedCount": {
                    "Success": 1
                }
            }
        }
    ]
}
```
자세한 내용은 ** Systems Manager 사용 설명서의 [Systems Manager에서 연결 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-associations.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스의 모든 연결을 나열합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="InstanceId";Value=@("i-0000293ffd8c57862")}
Get-SSMAssociationList -AssociationFilterList $filter1
```
**출력:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**예제 2: 이 예제에서는 구성 문서의 모든 연결을 나열합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter2 = @{Key="Name";Value=@("AWS-UpdateSSMAgent")}
Get-SSMAssociationList -AssociationFilterList $filter2
```
**출력:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**예제 3: PowerShell 버전 2에서 각 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.AssociationFilter
$filter1.Key = "InstanceId"
$filter1.Value = "i-0000293ffd8c57862"

Get-SSMAssociationList -AssociationFilterList $filter1
```
**출력:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListAssociations](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스의 모든 연결을 나열합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter1 = @{Key="InstanceId";Value=@("i-0000293ffd8c57862")}
Get-SSMAssociationList -AssociationFilterList $filter1
```
**출력:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**예제 2: 이 예제에서는 구성 문서의 모든 연결을 나열합니다. 이 예제에서 사용하는 구문에는 PowerShell 버전 3 이상이 필요합니다.**  

```
$filter2 = @{Key="Name";Value=@("AWS-UpdateSSMAgent")}
Get-SSMAssociationList -AssociationFilterList $filter2
```
**출력:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**예제 3: PowerShell 버전 2에서 각 필터를 생성하려면 New-Object를 사용해야 합니다.**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.AssociationFilter
$filter1.Key = "InstanceId"
$filter1.Value = "i-0000293ffd8c57862"

Get-SSMAssociationList -AssociationFilterList $filter1
```
**출력:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListAssociations](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `ListCommandInvocations` 함께 사용
<a name="ssm_example_ssm_ListCommandInvocations_section"></a>

다음 코드 예시는 `ListCommandInvocations`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md) 

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

**AWS CLI**  
**특정 명령의 간접 호출을 나열하는 방법**  
다음 `list-command-invocations` 예제에서는 명령의 모든 간접 호출을 나열합니다.  

```
aws ssm list-command-invocations \
    --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" \
    --details
```
출력:  

```
{
    "CommandInvocations": [
        {
            "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678",
            "InstanceId": "i-02573cafcfEXAMPLE",
            "InstanceName": "",
            "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
            "DocumentName": "AWS-UpdateSSMAgent",
            "DocumentVersion": "",
            "RequestedDateTime": 1582136283.089,
            "Status": "Success",
            "StatusDetails": "Success",
            "StandardOutputUrl": "",
            "StandardErrorUrl": "",
            "CommandPlugins": [
                {
                    "Name": "aws:updateSsmAgent",
                    "Status": "Success",
                    "StatusDetails": "Success",
                    "ResponseCode": 0,
                    "ResponseStartDateTime": 1582136283.419,
                    "ResponseFinishDateTime": 1582136283.51,
                    "Output": "Updating amazon-ssm-agent from 2.3.842.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\namazon-ssm-agent 2.3.842.0 has already been installed, update skipped\n",
                    "StandardOutputUrl": "",
                    "StandardErrorUrl": "",
                    "OutputS3Region": "us-east-2",
                    "OutputS3BucketName": "",
                    "OutputS3KeyPrefix": ""
                }
            ],
            "ServiceRole": "",
            "NotificationConfig": {
                "NotificationArn": "",
                "NotificationEvents": [],
                "NotificationType": ""
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        },
        {
            "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678",
            "InstanceId": "i-0471e04240EXAMPLE",
            "InstanceName": "",
            "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
            "DocumentName": "AWS-UpdateSSMAgent",
            "DocumentVersion": "",
            "RequestedDateTime": 1582136283.02,
            "Status": "Success",
            "StatusDetails": "Success",
            "StandardOutputUrl": "",
            "StandardErrorUrl": "",
            "CommandPlugins": [
                {
                    "Name": "aws:updateSsmAgent",
                    "Status": "Success",
                    "StatusDetails": "Success",
                    "ResponseCode": 0,
                    "ResponseStartDateTime": 1582136283.812,
                    "ResponseFinishDateTime": 1582136295.031,
                    "Output": "Updating amazon-ssm-agent from 2.3.672.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent-updater/2.3.842.0/amazon-ssm-agent-updater-snap-amd64.tar.gz\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.672.0/amazon-ssm-agent-snap-amd64.tar.gz\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.842.0/amazon-ssm-agent-snap-amd64.tar.gz\nInitiating amazon-ssm-agent update to 2.3.842.0\namazon-ssm-agent updated successfully to 2.3.842.0",
                    "StandardOutputUrl": "",
                    "StandardErrorUrl": "",
                    "OutputS3Region": "us-east-2",
                    "OutputS3BucketName": "",
                    "OutputS3KeyPrefix": "8bee3135-398c-4d31-99b6-e42d2EXAMPLE/i-0471e04240EXAMPLE/awsupdateSsmAgent"
                }
            ],
            "ServiceRole": "",
            "NotificationConfig": {
                "NotificationArn": "",
                "NotificationEvents": [],
                "NotificationType": ""
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [명령 상태 이해](https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListCommandInvocations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-command-invocations.html)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { paginateListCommandInvocations, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * List SSM command invocations on an instance.
 * @param {{ instanceId: string }}
 */
export const main = async ({ instanceId }) => {
  const client = new SSMClient({});
  try {
    const listCommandInvocationsPaginated = [];
    // The paginate function is a wrapper around the base command.
    const paginator = paginateListCommandInvocations(
      { client },
      {
        InstanceId: instanceId,
      },
    );
    for await (const page of paginator) {
      listCommandInvocationsPaginated.push(...page.CommandInvocations);
    }
    console.log("Here is the list of command invocations:");
    console.log(listCommandInvocationsPaginated);
    return { CommandInvocations: listCommandInvocationsPaginated };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ValidationError") {
      console.warn(`${caught.message}. Did you provide a valid instance ID?`);
    }
    throw caught;
  }
};
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [ListCommandInvocations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/ListCommandInvocationsCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 명령의 모든 간접 호출을 나열합니다.**  

```
Get-SSMCommandInvocation -CommandId "b8eac879-0541-439d-94ec-47a80d554f44" -Detail $true
```
**출력:**  

```
CommandId          : b8eac879-0541-439d-94ec-47a80d554f44
CommandPlugins     : {aws:runShellScript}
Comment            : IP config
DocumentName       : AWS-RunShellScript
InstanceId         : i-0cb2b964d3e14fd9f
InstanceName       :
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
RequestedDateTime  : 2/22/2017 8:13:16 PM
ServiceRole        :
StandardErrorUrl   :
StandardOutputUrl  :
Status             : Success
StatusDetails      : Success
TraceOutput        :
```
**예제 2: 이 예제에서는 명령 ID e1eb2e3c-ed4c-5123-45c1-234f5612345f의 간접 호출에 대한 CommandPlugins를 나열합니다.**  

```
Get-SSMCommandInvocation -CommandId e1eb2e3c-ed4c-5123-45c1-234f5612345f -Detail:$true | Select-Object -ExpandProperty CommandPlugins
```
**출력:**  

```
Name                   : aws:runPowerShellScript
Output                 : Completed 17.7 KiB/17.7 KiB (40.1 KiB/s) with 1 file(s) remainingdownload: s3://dd-aess-r-ctmer/KUMO.png to ..\..\programdata\KUMO.png
                         kumo available

OutputS3BucketName     :
OutputS3KeyPrefix      :
OutputS3Region         : eu-west-1
ResponseCode           : 0
ResponseFinishDateTime : 4/3/2019 11:53:23 AM
ResponseStartDateTime  : 4/3/2019 11:53:21 AM
StandardErrorUrl       :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListCommandInvocations](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 명령의 모든 간접 호출을 나열합니다.**  

```
Get-SSMCommandInvocation -CommandId "b8eac879-0541-439d-94ec-47a80d554f44" -Detail $true
```
**출력:**  

```
CommandId          : b8eac879-0541-439d-94ec-47a80d554f44
CommandPlugins     : {aws:runShellScript}
Comment            : IP config
DocumentName       : AWS-RunShellScript
InstanceId         : i-0cb2b964d3e14fd9f
InstanceName       :
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
RequestedDateTime  : 2/22/2017 8:13:16 PM
ServiceRole        :
StandardErrorUrl   :
StandardOutputUrl  :
Status             : Success
StatusDetails      : Success
TraceOutput        :
```
**예제 2: 이 예제에서는 명령 ID e1eb2e3c-ed4c-5123-45c1-234f5612345f의 간접 호출에 대한 CommandPlugins를 나열합니다.**  

```
Get-SSMCommandInvocation -CommandId e1eb2e3c-ed4c-5123-45c1-234f5612345f -Detail:$true | Select-Object -ExpandProperty CommandPlugins
```
**출력:**  

```
Name                   : aws:runPowerShellScript
Output                 : Completed 17.7 KiB/17.7 KiB (40.1 KiB/s) with 1 file(s) remainingdownload: s3://dd-aess-r-ctmer/KUMO.png to ..\..\programdata\KUMO.png
                         kumo available

OutputS3BucketName     :
OutputS3KeyPrefix      :
OutputS3Region         : eu-west-1
ResponseCode           : 0
ResponseFinishDateTime : 4/3/2019 11:53:23 AM
ResponseStartDateTime  : 4/3/2019 11:53:21 AM
StandardErrorUrl       :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListCommandInvocations](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 list_command_invocations(self, instance_id):
        """
        Lists the commands for an instance.

        :param instance_id: The ID of the instance.
        :return: The list of commands.
        """
        try:
            paginator = self.ssm_client.get_paginator("list_command_invocations")
            command_invocations = []
            for page in paginator.paginate(InstanceId=instance_id):
                command_invocations.extend(page["CommandInvocations"])
            num_of_commands = len(command_invocations)
            print(
                f"{num_of_commands} command invocation(s) found for instance {instance_id}."
            )

            if num_of_commands > 10:
                print("Displaying the first 10 commands:")
                num_of_commands = 10
            date_format = "%A, %d %B %Y %I:%M%p"
            for command in command_invocations[:num_of_commands]:
                print(
                    f"   The time of command invocation is {command['RequestedDateTime'].strftime(date_format)}"
                )
        except ClientError as err:
            logger.error(
                "Couldn't list commands for %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListCommandInvocations](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/ListCommandInvocations)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        " Use paginator to get all results
        DATA(lo_paginator) = lo_ssm->get_paginator( ).
        DATA(lo_iterator) = lo_paginator->listcommandinvocations(
          iv_instanceid = iv_instance_id ).

        DATA lv_count TYPE i VALUE 0.

        WHILE lo_iterator->has_next( ).
          DATA(lo_result) = CAST /aws1/cl_ssmlistcmdinvcsresult( lo_iterator->get_next( ) ).
          LOOP AT lo_result->get_commandinvocations( ) INTO DATA(lo_invocation).
            lv_count = lv_count + 1.
            DATA(lv_requested_datetime) = lo_invocation->get_requesteddatetime( ).
            MESSAGE |Command invocation requested at: { lv_requested_datetime }| TYPE 'I'.
          ENDLOOP.
        ENDWHILE.

        MESSAGE |{ lv_count } command invocation(s) found for instance { iv_instance_id }.| TYPE 'I'.
      CATCH /aws1/cx_ssminvalidinstanceid.
        MESSAGE 'Invalid instance ID.' TYPE 'I'.
      CATCH /aws1/cx_ssminvalidcommandid.
        MESSAGE 'Invalid command ID.' TYPE 'I'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListCommandInvocations](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `ListCommands` 사용
<a name="ssm_example_ssm_ListCommands_section"></a>

다음 코드 예시는 `ListCommands`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 특정 명령의 상태를 가져오는 방법**  
다음 `list-commands` 예제에서는 지정된 명령의 상태를 검색하고 표시합니다.  

```
aws ssm list-commands \
    --command-id "0831e1a8-a1ac-4257-a1fd-c831bEXAMPLE"
```
**예제 2: 특정 날짜 이후에 요청된 명령의 상태를 가져오는 방법**  
다음 `list-commands` 예제에서는 지정된 날짜 이후에 요청된 명령의 세부 정보를 검색합니다.  

```
aws ssm list-commands \
    --filter "key=InvokedAfter,value=2020-02-01T00:00:00Z"
```
**예제 3: AWS 계정에서 요청된 모든 명령 나열**  
다음 `list-commands` 예시에서는 현재 AWS 계정 및 리전의 사용자가 요청한 모든 명령을 나열합니다.  

```
aws ssm list-commands
```
출력:  

```
{
    "Commands": [
        {
            "CommandId": "8bee3135-398c-4d31-99b6-e42d2EXAMPLE",
            "DocumentName": "AWS-UpdateSSMAgent",
            "DocumentVersion": "",
            "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
            "ExpiresAfter": "2020-02-19T11:28:02.500000-08:00",
            "Parameters": {},
            "InstanceIds": [
                "i-028ea792daEXAMPLE",
                "i-02feef8c46EXAMPLE",
                "i-038613f3f0EXAMPLE",
                "i-03a530a2d4EXAMPLE",
                "i-083b678d37EXAMPLE",
                "i-0dee81debaEXAMPLE"
            ],
            "Targets": [],
            "RequestedDateTime": "2020-02-19T10:18:02.500000-08:00",
            "Status": "Success",
            "StatusDetails": "Success",
            "OutputS3BucketName": "",
            "OutputS3KeyPrefix": "",
            "MaxConcurrency": "50",
            "MaxErrors": "100%",
            "TargetCount": 6,
            "CompletedCount": 6,
            "ErrorCount": 0,
            "DeliveryTimedOutCount": 0,
            "ServiceRole": "",
            "NotificationConfig": {
                "NotificationArn": "",
                "NotificationEvents": [],
                "NotificationType": ""
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
        {
            "CommandId": "e9ade581-c03d-476b-9b07-26667EXAMPLE",
            "DocumentName": "AWS-FindWindowsUpdates",
            "DocumentVersion": "1",
            "Comment": "",
            "ExpiresAfter": "2020-01-24T12:37:31.874000-08:00",
            "Parameters": {
                "KbArticleIds": [
                    ""
                ],
                "UpdateLevel": [
                    "All"
                ]
            },
            "InstanceIds": [],
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-00ec29b21eEXAMPLE",
                        "i-09911ddd90EXAMPLE"
                    ]
                }
            ],
            "RequestedDateTime": "2020-01-24T11:27:31.874000-08:00",
            "Status": "Success",
            "StatusDetails": "Success",
            "OutputS3BucketName": "my-us-east-2-bucket",
            "OutputS3KeyPrefix": "my-rc-output",
            "MaxConcurrency": "50",
            "MaxErrors": "0",
            "TargetCount": 2,
            "CompletedCount": 2,
            "ErrorCount": 0,
            "DeliveryTimedOutCount": 0,
            "ServiceRole": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "NotificationConfig": {
                "NotificationArn": "arn:aws:sns:us-east-2:111222333444:my-us-east-2-notification-arn",
                "NotificationEvents": [
                    "All"
                ],
                "NotificationType": "Invocation"
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
        {
            "CommandId": "d539b6c3-70e8-4853-80e5-0ce4fEXAMPLE",
            "DocumentName": "AWS-RunPatchBaseline",
            "DocumentVersion": "1",
            "Comment": "",
            "ExpiresAfter": "2020-01-24T12:21:04.350000-08:00",
            "Parameters": {
                "InstallOverrideList": [
                    ""
                ],
                "Operation": [
                    "Install"
                ],
                "RebootOption": [
                    "RebootIfNeeded"
                ],
                "SnapshotId": [
                    ""
                ]
            },
            "InstanceIds": [],
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-00ec29b21eEXAMPLE",
                        "i-09911ddd90EXAMPLE"
                    ]
                }
            ],
            "RequestedDateTime": "2020-01-24T11:11:04.350000-08:00",
            "Status": "Success",
            "StatusDetails": "Success",
            "OutputS3BucketName": "my-us-east-2-bucket",
            "OutputS3KeyPrefix": "my-rc-output",
            "MaxConcurrency": "50",
            "MaxErrors": "0",
            "TargetCount": 2,
            "CompletedCount": 2,
            "ErrorCount": 0,
            "DeliveryTimedOutCount": 0,
            "ServiceRole": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "NotificationConfig": {
                "NotificationArn": "arn:aws:sns:us-east-2:111222333444:my-us-east-2-notification-arn",
                "NotificationEvents": [
                    "All"
                ],
                "NotificationType": "Invocation"
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager Run Command를 사용하여 명령 실행](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListCommands](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-commands.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 요청된 모든 명령을 나열합니다.**  

```
Get-SSMCommand
```
**출력:**  

```
CommandId          : 4b75a163-d39a-4d97-87c9-98ae52c6be35
Comment            : Apply association with id at update time: 4cc73e42-d5ae-4879-84f8-57e09c0efcd0
CompletedCount     : 1
DocumentName       : AWS-RefreshAssociation
ErrorCount         : 0
ExpiresAfter       : 2/24/2017 3:19:08 AM
InstanceIds        : {i-0cb2b964d3e14fd9f}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName :
OutputS3KeyPrefix  :
OutputS3Region     :
Parameters         : {[associationIds, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 2/24/2017 3:18:08 AM
ServiceRole        :
Status             : Success
StatusDetails      : Success
TargetCount        : 1
Targets            : {}
```
**예제 2: 이 예제는 특정 명령의 상태를 가져옵니다.**  

```
Get-SSMCommand -CommandId "4b75a163-d39a-4d97-87c9-98ae52c6be35"
```
**예제 3: 이 예제에서는 2019-04-01T00:00:00Z 이후에 간접 호출된 모든 SSM 명령을 검색합니다.**  

```
Get-SSMCommand -Filter @{Key="InvokedAfter";Value="2019-04-01T00:00:00Z"} | Select-Object CommandId, DocumentName, Status, RequestedDateTime | Sort-Object -Property RequestedDateTime -Descending
```
**출력:**  

```
CommandId                            DocumentName               Status    RequestedDateTime
---------                            ------------               ------    -----------------
edb1b23e-456a-7adb-aef8-90e-012ac34f AWS-RunPowerShellScript    Cancelled 4/16/2019 5:45:23 AM
1a2dc3fb-4567-890d-a1ad-234b5d6bc7d9 AWS-ConfigureAWSPackage    Success   4/6/2019 9:19:42 AM
12c3456c-7e90-4f12-1232-1234f5b67893 KT-Retrieve-Cloud-Type-Win Failed    4/2/2019 4:13:07 AM
fe123b45-240c-4123-a2b3-234bdd567ecf AWS-RunInspecChecks        Failed    4/1/2019 2:27:31 PM
1eb23aa4-567d-4123-12a3-4c1c2ab34561 AWS-RunPowerShellScript    Success   4/1/2019 1:05:55 PM
1c2f3bb4-ee12-4bc1-1a23-12345eea123e AWS-RunInspecChecks        Failed    4/1/2019 11:13:09 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListCommands](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 요청된 모든 명령을 나열합니다.**  

```
Get-SSMCommand
```
**출력:**  

```
CommandId          : 4b75a163-d39a-4d97-87c9-98ae52c6be35
Comment            : Apply association with id at update time: 4cc73e42-d5ae-4879-84f8-57e09c0efcd0
CompletedCount     : 1
DocumentName       : AWS-RefreshAssociation
ErrorCount         : 0
ExpiresAfter       : 2/24/2017 3:19:08 AM
InstanceIds        : {i-0cb2b964d3e14fd9f}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName :
OutputS3KeyPrefix  :
OutputS3Region     :
Parameters         : {[associationIds, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 2/24/2017 3:18:08 AM
ServiceRole        :
Status             : Success
StatusDetails      : Success
TargetCount        : 1
Targets            : {}
```
**예제 2: 이 예제는 특정 명령의 상태를 가져옵니다.**  

```
Get-SSMCommand -CommandId "4b75a163-d39a-4d97-87c9-98ae52c6be35"
```
**예제 3: 이 예제에서는 2019-04-01T00:00:00Z 이후에 간접 호출된 모든 SSM 명령을 검색합니다.**  

```
Get-SSMCommand -Filter @{Key="InvokedAfter";Value="2019-04-01T00:00:00Z"} | Select-Object CommandId, DocumentName, Status, RequestedDateTime | Sort-Object -Property RequestedDateTime -Descending
```
**출력:**  

```
CommandId                            DocumentName               Status    RequestedDateTime
---------                            ------------               ------    -----------------
edb1b23e-456a-7adb-aef8-90e-012ac34f AWS-RunPowerShellScript    Cancelled 4/16/2019 5:45:23 AM
1a2dc3fb-4567-890d-a1ad-234b5d6bc7d9 AWS-ConfigureAWSPackage    Success   4/6/2019 9:19:42 AM
12c3456c-7e90-4f12-1232-1234f5b67893 KT-Retrieve-Cloud-Type-Win Failed    4/2/2019 4:13:07 AM
fe123b45-240c-4123-a2b3-234bdd567ecf AWS-RunInspecChecks        Failed    4/1/2019 2:27:31 PM
1eb23aa4-567d-4123-12a3-4c1c2ab34561 AWS-RunPowerShellScript    Success   4/1/2019 1:05:55 PM
1c2f3bb4-ee12-4bc1-1a23-12345eea123e AWS-RunInspecChecks        Failed    4/1/2019 11:13:09 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListCommands](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListComplianceItems` 사용
<a name="ssm_example_ssm_ListComplianceItems_section"></a>

다음 코드 예시는 `ListComplianceItems`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**특정 인스턴스의 규정 준수 항목을 나열하는 방법**  
이 예제에서는 지정된 인스턴스의 모든 규정 준수 항목을 나열합니다.  
명령:  

```
aws ssm list-compliance-items --resource-ids "i-1234567890abcdef0" --resource-types "ManagedInstance"
```
출력:  

```
{
  "ComplianceItems": [
      {
          "ComplianceType": "Association",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-1234567890abcdef0",
          "Id": "8dfe3659-4309-493a-8755-0123456789ab",
          "Title": "",
          "Status": "COMPLIANT",
          "Severity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550408470.0
          },
          "Details": {
              "DocumentName": "AWS-GatherSoftwareInventory",
              "DocumentVersion": "1"
          }
      },
      {
          "ComplianceType": "Association",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-1234567890abcdef0",
          "Id": "e4c2ed6d-516f-41aa-aa2a-0123456789ab",
          "Title": "",
          "Status": "COMPLIANT",
          "Severity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550508475.0
          },
          "Details": {
              "DocumentName": "AWS-UpdateSSMAgent",
              "DocumentVersion": "1"
          }
      },
              ...
  ],
  "NextToken": "--token string truncated--"
}
```
**특정 인스턴스 및 연결 ID에 대한 규정 준수 항목을 나열하는 방법**  
이 예제에서는 지정된 인스턴스 및 연결 ID의 모든 규정 준수 항목을 나열합니다.  
명령:  

```
aws ssm list-compliance-items --resource-ids "i-1234567890abcdef0" --resource-types "ManagedInstance" --filters "Key=ComplianceType,Values=Association,Type=EQUAL" "Key=Id,Values=e4c2ed6d-516f-41aa-aa2a-0123456789ab,Type=EQUAL"
```
**특정 날짜 및 시간 이후 인스턴스의 규정 준수 항목을 나열하는 방법**  
이 예제에서는 지정된 날짜 및 시간 이후 인스턴스에 대한 모든 규정 준수 항목을 나열합니다.  
명령:  

```
aws ssm list-compliance-items --resource-ids "i-1234567890abcdef0" --resource-types "ManagedInstance" --filters "Key=ExecutionTime,Values=2019-02-18T16:00:00Z,Type=GREATER_THAN"
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListComplianceItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-compliance-items.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 리소스 ID 및 유형에 대한 규정 준수 항목 목록을 나열하며, 이때 필터링 규정 준수 유형은 '연결'로 필터링됩니다.**  

```
Get-SSMComplianceItemList -ResourceId i-1a2caf345f67d0dc2 -ResourceType ManagedInstance -Filter @{Key="ComplianceType";Values="Association"}
```
**출력:**  

```
ComplianceType   : Association
Details          : {[DocumentName, AWS-GatherSoftwareInventory], [DocumentVersion, 1]}
ExecutionSummary : Amazon.SimpleSystemsManagement.Model.ComplianceExecutionSummary
Id               : 123a45a1-c234-1234-1245-67891236db4e
ResourceId       : i-1a2caf345f67d0dc2
ResourceType     : ManagedInstance
Severity         : UNSPECIFIED
Status           : COMPLIANT
Title            :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListComplianceItems](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 리소스 ID 및 유형에 대한 규정 준수 항목 목록을 나열하며, 이때 필터링 규정 준수 유형은 '연결'로 필터링됩니다.**  

```
Get-SSMComplianceItemList -ResourceId i-1a2caf345f67d0dc2 -ResourceType ManagedInstance -Filter @{Key="ComplianceType";Values="Association"}
```
**출력:**  

```
ComplianceType   : Association
Details          : {[DocumentName, AWS-GatherSoftwareInventory], [DocumentVersion, 1]}
ExecutionSummary : Amazon.SimpleSystemsManagement.Model.ComplianceExecutionSummary
Id               : 123a45a1-c234-1234-1245-67891236db4e
ResourceId       : i-1a2caf345f67d0dc2
ResourceType     : ManagedInstance
Severity         : UNSPECIFIED
Status           : COMPLIANT
Title            :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListComplianceSummaries` 사용
<a name="ssm_example_ssm_ListComplianceSummaries_section"></a>

다음 코드 예시는 `ListComplianceSummaries`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**모든 규정 준수 유형에 대한 규정 준수 요약을 나열하는 방법**  
이 예제에서는 계정의 모든 규정 준수 유형에 대한 규정 준수 요약을 나열합니다.  
명령:  

```
aws ssm list-compliance-summaries
```
출력:  

```
{
  "ComplianceSummaryItems": [
      {
          "ComplianceType": "Association",
          "CompliantSummary": {
              "CompliantCount": 2,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 2
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 0,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      },
      {
          "ComplianceType": "Patch",
          "CompliantSummary": {
              "CompliantCount": 1,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 1
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 1,
              "SeveritySummary": {
                  "CriticalCount": 1,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      },
              ...
  ],
  "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ=="
}
```
**특정 규정 준수 유형에 대한 규정 준수 요약을 나열하는 방법**  
이 예제에서는 패치 규정 준수 유형에 대한 규정 준수 요약을 나열합니다.  
명령:  

```
aws ssm list-compliance-summaries --filters "Key=ComplianceType,Values=Patch,Type=EQUAL"
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListComplianceSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-compliance-summaries.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 모든 규정 준수 유형에 대한 규정 준수 및 규정 미준수 리소스의 요약 개수를 반환합니다.**  

```
Get-SSMComplianceSummaryList
```
**출력:**  

```
ComplianceType CompliantSummary                                      NonCompliantSummary
-------------- ----------------                                      -------------------
FleetTotal     Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Association    Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Custom:InSpec  Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Patch          Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListComplianceSummaries](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 모든 규정 준수 유형에 대한 규정 준수 및 규정 미준수 리소스의 요약 개수를 반환합니다.**  

```
Get-SSMComplianceSummaryList
```
**출력:**  

```
ComplianceType CompliantSummary                                      NonCompliantSummary
-------------- ----------------                                      -------------------
FleetTotal     Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Association    Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Custom:InSpec  Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Patch          Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListDocumentVersions` 사용
<a name="ssm_example_ssm_ListDocumentVersions_section"></a>

다음 코드 예시는 `ListDocumentVersions`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서 버전을 나열하는 방법**  
다음 `list-document-versions` 예제에서는 Systems Manager 문서의 모든 버전을 나열합니다.  

```
aws ssm list-document-versions \
    --name "Example"
```
출력:  

```
{
    "DocumentVersions": [
        {
            "Name": "Example",
            "DocumentVersion": "1",
            "CreatedDate": 1583257938.266,
            "IsDefaultVersion": true,
            "DocumentFormat": "YAML",
            "Status": "Active"
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [문서 버전 파라미터를 사용하는 명령 전송](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command-version.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListDocumentVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-document-versions.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 문서의 모든 버전을 나열합니다.**  

```
Get-SSMDocumentVersionList -Name "AWS-UpdateSSMAgent"
```
**출력:**  

```
CreatedDate       : 6/1/2021 5:19:10 PM
DocumentFormat    : JSON
DocumentVersion   : 1
IsDefaultVersion  : True
Name              : AWS-UpdateSSMAgent
Status            : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListDocumentVersions](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 문서의 모든 버전을 나열합니다.**  

```
Get-SSMDocumentVersionList -Name "AWS-UpdateSSMAgent"
```
**출력:**  

```
CreatedDate       : 6/1/2021 5:19:10 PM
DocumentFormat    : JSON
DocumentVersion   : 1
IsDefaultVersion  : True
Name              : AWS-UpdateSSMAgent
Status            : Active
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListDocumentVersions](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListDocuments` 사용
<a name="ssm_example_ssm_ListDocuments_section"></a>

다음 코드 예시는 `ListDocuments`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 문서를 나열하는 방법**  
다음 `list-documents` 예제에서는 사용자 지정 태그로 지정된 요청 계정에서 소유한 문서를 나열합니다.  

```
aws ssm list-documents \
    --filters Key=Owner,Values=Self Key=tag:DocUse,Values=Testing
```
출력:  

```
{
    "DocumentIdentifiers": [
        {
            "Name": "Example",
            "Owner": "29884EXAMPLE",
            "PlatformTypes": [
                "Windows",
                "Linux"
            ],
            "DocumentVersion": "1",
            "DocumentType": "Automation",
            "SchemaVersion": "0.3",
            "DocumentFormat": "YAML",
            "Tags": [
                {
                    "Key": "DocUse",
                    "Value": "Testing"
                }
            ]
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [AWS Systems Manager 문서](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html)를 참조하세요.  
**예제 2: 공유 문서를 나열하는 방법**  
다음 `list-documents` 예시에서는 소유하지 않은 프라이빗 공유 문서를 포함하여 공유 문서를 나열합니다 AWS.  

```
aws ssm list-documents \
    --filters Key=Name,Values=sharedDocNamePrefix  Key=Owner,Values=Private
```
출력:  

```
{
    "DocumentIdentifiers": [
        {
            "Name": "Example",
            "Owner": "12345EXAMPLE",
            "PlatformTypes": [
                "Windows",
                "Linux"
            ],
            "DocumentVersion": "1",
            "DocumentType": "Command",
            "SchemaVersion": "0.3",
            "DocumentFormat": "YAML",
            "Tags": []
        }
    ]
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [AWS Systems Manager 문서](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListDocuments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-documents.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 계정의 모든 구성 문서를 나열합니다.**  

```
Get-SSMDocumentList
```
**출력:**  

```
DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ApplyPatchBaseline
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureAWSPackage
Owner           : Amazon
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 2.0

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureCloudWatch
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2
...
```
**예제 2: 이 예제에서는 이름이 'Platform'과 일치하는 모든 자동화 문서를 검색합니다.**  

```
Get-SSMDocumentList -DocumentFilterList @{Key="DocumentType";Value="Automation"} | Where-Object Name -Match "Platform"
```
**출력:**  

```
DocumentFormat  : JSON
DocumentType    : Automation
DocumentVersion : 7
Name            : KT-Get-Platform
Owner           : 987654123456
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 0.3
Tags            : {}
TargetType      :
VersionName     :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListDocuments](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 계정의 모든 구성 문서를 나열합니다.**  

```
Get-SSMDocumentList
```
**출력:**  

```
DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ApplyPatchBaseline
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureAWSPackage
Owner           : Amazon
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 2.0

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureCloudWatch
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2
...
```
**예제 2: 이 예제에서는 이름이 'Platform'과 일치하는 모든 자동화 문서를 검색합니다.**  

```
Get-SSMDocumentList -DocumentFilterList @{Key="DocumentType";Value="Automation"} | Where-Object Name -Match "Platform"
```
**출력:**  

```
DocumentFormat  : JSON
DocumentType    : Automation
DocumentVersion : 7
Name            : KT-Get-Platform
Owner           : 987654123456
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 0.3
Tags            : {}
TargetType      :
VersionName     :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListDocuments](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListInventoryEntries` 사용
<a name="ssm_example_ssm_ListInventoryEntries_section"></a>

다음 코드 예시는 `ListInventoryEntries`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 인스턴스의 특정 인벤토리 유형 항목을 보는 방법**  
다음 `list-inventory-entries` 예시에서는 특정 인스턴스의 AWS:Application 인벤토리 유형에 대한 인벤토리 항목을 나열합니다.  

```
aws ssm list-inventory-entries \
    --instance-id "i-1234567890abcdef0" \
    --type-name "AWS:Application"
```
출력:  

```
{
  "TypeName": "AWS:Application",
  "InstanceId": "i-1234567890abcdef0",
  "SchemaVersion": "1.1",
  "CaptureTime": "2019-02-15T12:17:55Z",
  "Entries": [
    {
      "Architecture": "i386",
      "Name": "Amazon SSM Agent",
      "PackageId": "{88a60be2-89a1-4df8-812a-80863c2a2b68}",
      "Publisher": "Amazon Web Services",
      "Version": "2.3.274.0"
    },
    {
      "Architecture": "x86_64",
      "InstalledTime": "2018-05-03T13:42:34Z",
      "Name": "AmazonCloudWatchAgent",
      "Publisher": "",
      "Version": "1.200442.0"
    }
  ]
}
```
**예제 2: 인스턴스에 할당된 사용자 지정 인벤토리 항목을 보는 방법**  
다음 `list-inventory-entries` 예제에서는 인스턴스에 할당된 사용자 지정 인벤토리 항목을 나열합니다.  

```
aws ssm list-inventory-entries \
    --instance-id "i-1234567890abcdef0" \
    --type-name "Custom:RackInfo"
```
출력:  

```
{
  "TypeName": "Custom:RackInfo",
  "InstanceId": "i-1234567890abcdef0",
  "SchemaVersion": "1.0",
  "CaptureTime": "2021-05-22T10:01:01Z",
  "Entries": [
    {
      "RackLocation": "Bay B/Row C/Rack D/Shelf E"
    }
  ]
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListInventoryEntries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-inventory-entries.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스의 모든 사용자 지정 인벤토리 항목을 나열합니다.**  

```
Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo"
```
**출력:**  

```
CaptureTime   : 2016-08-22T10:01:01Z
Entries       : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,System.String]}
InstanceId    : i-0cb2b964d3e14fd9f
NextToken     :
SchemaVersion : 1.0
TypeName      : Custom:RackInfo
```
**예제 2: 이 예제에서는 세부 정보를 나열합니다.**  

```
(Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo").Entries
```
**출력:**  

```
Key          Value
---          -----
RackLocation Bay B/Row C/Rack D/Shelf E
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListInventoryEntries](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스의 모든 사용자 지정 인벤토리 항목을 나열합니다.**  

```
Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo"
```
**출력:**  

```
CaptureTime   : 2016-08-22T10:01:01Z
Entries       : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,System.String]}
InstanceId    : i-0cb2b964d3e14fd9f
NextToken     :
SchemaVersion : 1.0
TypeName      : Custom:RackInfo
```
**예제 2: 이 예제에서는 세부 정보를 나열합니다.**  

```
(Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo").Entries
```
**출력:**  

```
Key          Value
---          -----
RackLocation Bay B/Row C/Rack D/Shelf E
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListInventoryEntries](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListResourceComplianceSummaries` 사용
<a name="ssm_example_ssm_ListResourceComplianceSummaries_section"></a>

다음 코드 예시는 `ListResourceComplianceSummaries`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**리소스 수준 규정 준수 요약 수를 나열하는 방법**  
이 예제에서는 리소스 수준 규정 준수 요약 수를 나열합니다.  
명령:  

```
aws ssm list-resource-compliance-summaries
```
출력:  

```
{
  "ResourceComplianceSummaryItems": [
      {
          "ComplianceType": "Association",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-1234567890abcdef0",
          "Status": "COMPLIANT",
          "OverallSeverity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550509273.0
          },
          "CompliantSummary": {
              "CompliantCount": 2,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 2
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 0,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      },
      {
          "ComplianceType": "Patch",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-9876543210abcdef0",
          "Status": "COMPLIANT",
          "OverallSeverity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550248550.0,
              "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
              "ExecutionType": "Command"
          },
          "CompliantSummary": {
              "CompliantCount": 397,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 397
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 0,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      }
  ],
  "NextToken": "--token string truncated--"
}
```
**특정 규정 준수 유형에 대한 리소스 수준 규정 준수 요약을 나열하는 방법**  
이 예제에서는 패치 규정 준수 유형에 대한 리소스 수준 규정 준수 요약을 나열합니다.  
명령:  

```
aws ssm list-resource-compliance-summaries --filters "Key=ComplianceType,Values=Patch,Type=EQUAL"
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListResourceComplianceSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-resource-compliance-summaries.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 리소스 수준 요약 수를 가져옵니다. 요약에는 'Windows10'과 일치하는 제품의 규정 준수 및 비준수 상태에 대한 정보와 자세한 규정 준수 항목의 심각도 수가 포함됩니다. 파라미터가 지정되지 않은 경우 MaxResult의 기본값은 100이지만 이 값은 유효하지 않으므로 MaxResult 파라미터가 추가되고 값은 50으로 설정됩니다.**  

```
$FilterValues = @{
		"Key"="Product"
        "Type"="EQUAL"
        "Values"="Windows10"
}
        Get-SSMResourceComplianceSummaryList -Filter $FilterValues -MaxResult 50
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListResourceComplianceSummaries](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 리소스 수준 요약 수를 가져옵니다. 요약에는 'Windows10'과 일치하는 제품의 규정 준수 및 비준수 상태에 대한 정보와 자세한 규정 준수 항목의 심각도 수가 포함됩니다. 파라미터가 지정되지 않은 경우 MaxResult의 기본값은 100이지만 이 값은 유효하지 않으므로 MaxResult 파라미터가 추가되고 값은 50으로 설정됩니다.**  

```
$FilterValues = @{
		"Key"="Product"
        "Type"="EQUAL"
        "Values"="Windows10"
}
        Get-SSMResourceComplianceSummaryList -Filter $FilterValues -MaxResult 50
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListResourceComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListTagsForResource` 사용
<a name="ssm_example_ssm_ListTagsForResource_section"></a>

다음 코드 예시는 `ListTagsForResource`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 기준에 적용된 태그를 나열하는 방법**  
다음 `list-tags-for-resource` 예제에서는 패치 기준의 태그를 나열합니다.  

```
aws ssm list-tags-for-resource \
    --resource-type "PatchBaseline" \
    --resource-id "pb-0123456789abcdef0"
```
출력:  

```
{
    "TagList": [
        {
            "Key": "Environment",
            "Value": "Production"
        },
        {
            "Key": "Region",
            "Value": "EMEA"
        }
    ]
}
```
자세한 내용은 *AWS 일반* 참조의 [AWS 리소스 태그 지정](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-tags-for-resource.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간의 태그를 나열합니다.**  

```
Get-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow"
```
**출력:**  

```
Key   Value
---   -----
Stack Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간의 태그를 나열합니다.**  

```
Get-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow"
```
**출력:**  

```
Key   Value
---   -----
Stack Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ModifyDocumentPermission` 사용
<a name="ssm_example_ssm_ModifyDocumentPermission_section"></a>

다음 코드 예시는 `ModifyDocumentPermission`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서 권한을 수정하는 방법**  
다음 `modify-document-permission` 예제에서는 Systems Manager 문서를 공개적으로 공유합니다.  

```
aws ssm modify-document-permission \
    --name "Example" \
    --permission-type "Share" \
    --account-ids-to-add "All"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [Systems Manager 문서 공유](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-how-to-share.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ModifyDocumentPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/modify-document-permission.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 문서의 모든 계정에 '공유' 권한을 추가합니다. 명령이 성공해도 출력은 없습니다.**  

```
Edit-SSMDocumentPermission -Name "RunShellScript" -PermissionType "Share" -AccountIdsToAdd all
```
**예제 2: 이 예제에서는 문서의 특정 계정에 '공유' 권한을 추가합니다. 명령이 성공해도 출력은 없습니다.**  

```
Edit-SSMDocumentPermission -Name "RunShellScriptNew" -PermissionType "Share" -AccountIdsToAdd "123456789012"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ModifyDocumentPermission](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 문서의 모든 계정에 '공유' 권한을 추가합니다. 명령이 성공해도 출력은 없습니다.**  

```
Edit-SSMDocumentPermission -Name "RunShellScript" -PermissionType "Share" -AccountIdsToAdd all
```
**예제 2: 이 예제에서는 문서의 특정 계정에 '공유' 권한을 추가합니다. 명령이 성공해도 출력은 없습니다.**  

```
Edit-SSMDocumentPermission -Name "RunShellScriptNew" -PermissionType "Share" -AccountIdsToAdd "123456789012"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ModifyDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `PutComplianceItems` 사용
<a name="ssm_example_ssm_PutComplianceItems_section"></a>

다음 코드 예시는 `PutComplianceItems`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**지정된 인스턴스에 규정 준수 유형 및 규정 준수 세부 정보를 등록하는 방법**  
이 예제에서는 지정된 관리형 인스턴스에 규정 준수 유형 `Custom:AVCheck`를 등록합니다. 명령이 성공해도 출력은 없습니다.  
명령:  

```
aws ssm put-compliance-items --resource-id "i-1234567890abcdef0" --resource-type "ManagedInstance" --compliance-type "Custom:AVCheck" --execution-summary "ExecutionTime=2019-02-18T16:00:00Z" --items "Id=Version2.0,Title=ScanHost,Severity=CRITICAL,Status=COMPLIANT"
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutComplianceItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/put-compliance-items.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정된 관리형 인스턴스에 대한 사용자 지정 규정 준수 항목을 작성합니다.**  

```
$item = [Amazon.SimpleSystemsManagement.Model.ComplianceItemEntry]::new()
$item.Id = "07Jun2019-3"
$item.Severity="LOW"
$item.Status="COMPLIANT"
$item.Title="Fin-test-1 - custom"
Write-SSMComplianceItem -ResourceId mi-012dcb3ecea45b678 -ComplianceType Custom:VSSCompliant2 -ResourceType ManagedInstance -Item $item -ExecutionSummary_ExecutionTime "07-Jun-2019"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [PutComplianceItems](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정된 관리형 인스턴스에 대한 사용자 지정 규정 준수 항목을 작성합니다.**  

```
$item = [Amazon.SimpleSystemsManagement.Model.ComplianceItemEntry]::new()
$item.Id = "07Jun2019-3"
$item.Severity="LOW"
$item.Status="COMPLIANT"
$item.Title="Fin-test-1 - custom"
Write-SSMComplianceItem -ResourceId mi-012dcb3ecea45b678 -ComplianceType Custom:VSSCompliant2 -ResourceType ManagedInstance -Item $item -ExecutionSummary_ExecutionTime "07-Jun-2019"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `PutInventory` 사용
<a name="ssm_example_ssm_PutInventory_section"></a>

다음 코드 예시는 `PutInventory`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**인스턴스에 사용자 지정 메타데이터를 할당하는 방법**  
이번 예에서는 인스턴스에 랙 위치 정보를 할당합니다. 명령이 성공해도 출력은 없습니다.  
명령(Linux):  

```
aws ssm put-inventory --instance-id "i-016648b75dd622dab" --items '[{"TypeName": "Custom:RackInfo","SchemaVersion": "1.0","CaptureTime": "2019-01-22T10:01:01Z","Content":[{"RackLocation": "Bay B/Row C/Rack D/Shelf E"}]}]'
```
명령(Windows):  

```
aws ssm put-inventory --instance-id "i-016648b75dd622dab" --items "TypeName=Custom:RackInfo,SchemaVersion=1.0,CaptureTime=2019-01-22T10:01:01Z,Content=[{RackLocation='Bay B/Row C/Rack D/Shelf F'}]"
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutInventory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/put-inventory.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스에 랙 위치 정보를 할당합니다. 명령이 성공해도 출력은 없습니다.**  

```
$data = New-Object "System.Collections.Generic.Dictionary[System.String,System.String]"
$data.Add("RackLocation", "Bay B/Row C/Rack D/Shelf F")

$items = New-Object "System.Collections.Generic.List[System.Collections.Generic.Dictionary[System.String, System.String]]"
$items.Add($data)

$customInventoryItem = New-Object Amazon.SimpleSystemsManagement.Model.InventoryItem
$customInventoryItem.CaptureTime = "2016-08-22T10:01:01Z"
$customInventoryItem.Content = $items
$customInventoryItem.TypeName = "Custom:TestRackInfo2"
$customInventoryItem.SchemaVersion = "1.0"

$inventoryItems = @($customInventoryItem)

Write-SSMInventory -InstanceId "i-0cb2b964d3e14fd9f" -Item $inventoryItems
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [PutInventory](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스에 랙 위치 정보를 할당합니다. 명령이 성공해도 출력은 없습니다.**  

```
$data = New-Object "System.Collections.Generic.Dictionary[System.String,System.String]"
$data.Add("RackLocation", "Bay B/Row C/Rack D/Shelf F")

$items = New-Object "System.Collections.Generic.List[System.Collections.Generic.Dictionary[System.String, System.String]]"
$items.Add($data)

$customInventoryItem = New-Object Amazon.SimpleSystemsManagement.Model.InventoryItem
$customInventoryItem.CaptureTime = "2016-08-22T10:01:01Z"
$customInventoryItem.Content = $items
$customInventoryItem.TypeName = "Custom:TestRackInfo2"
$customInventoryItem.SchemaVersion = "1.0"

$inventoryItems = @($customInventoryItem)

Write-SSMInventory -InstanceId "i-0cb2b964d3e14fd9f" -Item $inventoryItems
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutInventory](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `PutParameter` 함께 사용
<a name="ssm_example_ssm_PutParameter_section"></a>

다음 코드 예시는 `PutParameter`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예 1: 파라미터 값을 변경하는 방법**  
다음 `put-parameter` 예시에서는 지정된 파라미터의 값을 변경합니다.  

```
aws ssm put-parameter \
    --name "MyStringParameter" \
    --type "String" \
    --value "Vici" \
    --overwrite
```
출력:  

```
{
    "Version": 2,
    "Tier": "Standard"
}
```
자세한 내용은 [Systems Manager 사용 설명서의 Systems Manager 파라미터 생성(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html), [파라미터 티어 관리](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) 및 [파라미터 정책 작업을](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) 참조하세요. *AWS *   
**예 2: 고급 파라미터를 생성하는 방법**  
다음 `put-parameter` 예시에서는 고급 파라미터를 생성합니다.  

```
aws ssm put-parameter \
    --name "MyAdvancedParameter" \
    --description "This is an advanced parameter" \
    --value "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat [truncated]" \
    --type "String" \
    --tier Advanced
```
출력:  

```
{
    "Version": 1,
    "Tier": "Advanced"
}
```
자세한 내용은 [Systems Manager 사용 설명서의 Systems Manager 파라미터 생성(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html), [파라미터 티어 관리](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) 및 [파라미터 정책 작업을](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) 참조하세요. *AWS *   
**예 3: 표준 파라미터를 고급 파라미터로 변환하는 방법**  
다음 `put-parameter` 예시에서는 기존 표준 파라미터를 고급 파라미터로 변환합니다.  

```
aws ssm put-parameter \
    --name "MyConvertedParameter" \
    --value "abc123" \
    --type "String" \
    --tier Advanced \
    --overwrite
```
출력:  

```
{
    "Version": 2,
    "Tier": "Advanced"
}
```
자세한 내용은 [Systems Manager 사용 설명서의 Systems Manager 파라미터 생성(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html), [파라미터 티어 관리](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) 및 [파라미터 정책 작업을](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) 참조하세요. *AWS *   
**예 4: 정책이 연결된 파라미터를 생성하는 방법**  
다음 `put-parameter` 예시에서는 파라미터 정책이 연결된 고급 파라미터를 생성합니다.  

```
aws ssm put-parameter \
    --name "/Finance/Payroll/q2accesskey" \
    --value "P@sSwW)rd" \
    --type "SecureString" \
    --tier Advanced \
    --policies "[{\"Type\":\"Expiration\",\"Version\":\"1.0\",\"Attributes\":{\"Timestamp\":\"2020-06-30T00:00:00.000Z\"}},{\"Type\":\"ExpirationNotification\",\"Version\":\"1.0\",\"Attributes\":{\"Before\":\"5\",\"Unit\":\"Days\"}},{\"Type\":\"NoChangeNotification\",\"Version\":\"1.0\",\"Attributes\":{\"After\":\"60\",\"Unit\":\"Days\"}}]"
```
출력:  

```
{
    "Version": 1,
    "Tier": "Advanced"
}
```
자세한 내용은 [Systems Manager 사용 설명서의 Systems Manager 파라미터 생성(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html), [파라미터 티어 관리](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) 및 [파라미터 정책 작업을](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) 참조하세요. *AWS *   
**예 5: 기존 파라미터에 정책을 추가하는 방법**  
다음 `put-parameter` 예시에서는 정책을 기존 고급 파라미터에 연결합니다.  

```
aws ssm put-parameter \
    --name "/Finance/Payroll/q2accesskey" \
    --value "N3wP@sSwW)rd" \
    --type "SecureString" \
    --tier Advanced \
    --policies "[{\"Type\":\"Expiration\",\"Version\":\"1.0\",\"Attributes\":{\"Timestamp\":\"2020-06-30T00:00:00.000Z\"}},{\"Type\":\"ExpirationNotification\",\"Version\":\"1.0\",\"Attributes\":{\"Before\":\"5\",\"Unit\":\"Days\"}},{\"Type\":\"NoChangeNotification\",\"Version\":\"1.0\",\"Attributes\":{\"After\":\"60\",\"Unit\":\"Days\"}}]"
    --overwrite
```
출력:  

```
{
    "Version": 2,
    "Tier": "Advanced"
}
```
자세한 내용은 [Systems Manager 사용 설명서의 Systems Manager 파라미터 생성(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html), [파라미터 티어 관리](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) 및 [파라미터 정책 작업을](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) 참조하세요. *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutParameter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/put-parameter.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.ParameterType;
import software.amazon.awssdk.services.ssm.model.PutParameterRequest;
import software.amazon.awssdk.services.ssm.model.SsmException;

public class PutParameter {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <paraName>

                Where:
                    paraName - The name of the parameter.
                    paraValue - The value of the parameter.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String paraName = args[0];
        String paraValue = args[1];
        Region region = Region.US_EAST_1;
        SsmClient ssmClient = SsmClient.builder()
                .region(region)
                .build();

        putParaValue(ssmClient, paraName, paraValue);
        ssmClient.close();
    }

    public static void putParaValue(SsmClient ssmClient, String paraName, String value) {
        try {
            PutParameterRequest parameterRequest = PutParameterRequest.builder()
                    .name(paraName)
                    .type(ParameterType.STRING)
                    .value(value)
                    .build();

            ssmClient.putParameter(parameterRequest);
            System.out.println("The parameter was successfully added.");

        } catch (SsmException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API에 대한 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [PutParameter](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/PutParameter)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 파라미터를 생성합니다. 명령이 성공해도 출력은 없습니다.**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "helloWorld"
```
**예제 2: 이 예제에서는 파라미터를 변경합니다. 명령이 성공해도 출력은 없습니다.**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "Good day, Sunshine!" -Overwrite $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [PutParameter](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 파라미터를 생성합니다. 명령이 성공해도 출력은 없습니다.**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "helloWorld"
```
**예제 2: 이 예제에서는 파라미터를 변경합니다. 명령이 성공해도 출력은 없습니다.**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "Good day, Sunshine!" -Overwrite $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutParameter](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn make_parameter(
    client: &Client,
    name: &str,
    value: &str,
    description: &str,
) -> Result<(), Error> {
    let resp = client
        .put_parameter()
        .overwrite(true)
        .r#type(ParameterType::String)
        .name(name)
        .value(value)
        .description(description)
        .send()
        .await?;

    println!("Success! Parameter now has version: {}", resp.version());

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [PutParameter](https://docs.rs/aws-sdk-ssm/latest/aws_sdk_ssm/client/struct.Client.html#method.put_parameter)를 참조하세요.

------

# CLI로 `RegisterDefaultPatchBaseline` 사용
<a name="ssm_example_ssm_RegisterDefaultPatchBaseline_section"></a>

다음 코드 예시는 `RegisterDefaultPatchBaseline`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**기본 패치 기준을 설정하는 방법**  
다음 `register-default-patch-baseline` 예제에서는 지정된 사용자 지정 패치 기준을 지원하는 운영 체제 유형의 기본 패치 기준으로 등록합니다.  

```
aws ssm register-default-patch-baseline \
    --baseline-id "pb-abc123cf9bEXAMPLE"
```
출력:  

```
{
    "BaselineId":"pb-abc123cf9bEXAMPLE"
}
```
다음 `register-default-patch-baseline` 예제에서는 CentOS AWS 용에서 제공하는 기본 패치 기준을 기본 패치 기준으로 등록합니다.  

```
aws ssm register-default-patch-baseline \
    --baseline-id "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-0574b43a65ea646ed"
```
출력:  

```
{
    "BaselineId":"pb-abc123cf9bEXAMPLE"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [사전 정의된 패치 기준 및 사용자 지정 패치 기준 정보](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baselines.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [RegisterDefaultPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-default-patch-baseline.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 기준을 기본 패치 기준으로 등록합니다.**  

```
Register-SSMDefaultPatchBaseline -BaselineId "pb-03da896ca3b68b639"
```
**출력:**  

```
pb-03da896ca3b68b639
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RegisterDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 기준을 기본 패치 기준으로 등록합니다.**  

```
Register-SSMDefaultPatchBaseline -BaselineId "pb-03da896ca3b68b639"
```
**출력:**  

```
pb-03da896ca3b68b639
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RegisterDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `RegisterPatchBaselineForPatchGroup` 사용
<a name="ssm_example_ssm_RegisterPatchBaselineForPatchGroup_section"></a>

다음 코드 예시는 `RegisterPatchBaselineForPatchGroup`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 그룹에 대해 패치 기준을 등록하는 방법**  
다음 `register-patch-baseline-for-patch-group` 예제에서는 패치 그룹의 패치 기준을 등록합니다.  

```
aws ssm register-patch-baseline-for-patch-group \
    --baseline-id "pb-045f10b4f382baeda" \
    --patch-group "Production"
```
출력:  

```
{
    "BaselineId": "pb-045f10b4f382baeda",
    "PatchGroup": "Production"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 패치 그룹 생성(<https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-tagging.html>\$1\$1)과 [패치 기준에 패치 그룹 추가](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [RegisterPatchBaselineForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-patch-baseline-for-patch-group.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 패치 그룹의 패치 기준을 등록합니다.**  

```
Register-SSMPatchBaselineForPatchGroup -BaselineId "pb-03da896ca3b68b639" -PatchGroup "Production"
```
**출력:**  

```
BaselineId           PatchGroup
----------           ----------
pb-03da896ca3b68b639 Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RegisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 패치 그룹의 패치 기준을 등록합니다.**  

```
Register-SSMPatchBaselineForPatchGroup -BaselineId "pb-03da896ca3b68b639" -PatchGroup "Production"
```
**출력:**  

```
BaselineId           PatchGroup
----------           ----------
pb-03da896ca3b68b639 Production
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RegisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `RegisterTargetWithMaintenanceWindow` 사용
<a name="ssm_example_ssm_RegisterTargetWithMaintenanceWindow_section"></a>

다음 코드 예시는 `RegisterTargetWithMaintenanceWindow`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 유지 관리 기간에 단일 대상을 등록하는 방법**  
다음 `register-target-with-maintenance-window` 예제에서는 유지 관리 기간에 인스턴스를 등록합니다.  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --target "Key=InstanceIds,Values=i-0000293ffd8c57862" \
    --owner-information "Single instance" \
    --resource-type "INSTANCE"
```
출력:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**예제 2: 인스턴스 ID를 사용하여 유지 관리 기간에 여러 대상을 등록하는 방법**  
다음 `register-target-with-maintenance-window` 예제에서는 인스턴스 ID를 지정하여 유지 관리 기간에 두 인스턴스를 등록합니다.  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --target "Key=InstanceIds,Values=i-0000293ffd8c57862,i-0cb2b964d3e14fd9f" \
    --owner-information "Two instances in a list" \
    --resource-type "INSTANCE"
```
출력:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**예제 3: 리소스 태그를 사용하여 유지 관리 기간에 대상을 등록하는 방법**  
다음 `register-target-with-maintenance-window` 예제에서는 인스턴스에 적용되는 리소스 태그를 지정하여 유지 관리 기간에 인스턴스를 등록합니다.  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-06cf17cbefcb4bf4f" \
    --targets "Key=tag:Environment,Values=Prod" "Key=Role,Values=Web" \
    --owner-information "Production Web Servers" \
    --resource-type "INSTANCE"
```
출력:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**예제 4: 태그 키 그룹을 사용하여 대상을 등록하는 방법**  
다음 `register-target-with-maintenance-window` 예제에서는 키 값에 상관없이 모두 하나 이상의 태그가 지정된 인스턴스를 등록합니다.  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=tag-key,Values=Name,Instance-Type,CostCenter"
```
출력:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**예제 5: 리소스 그룹 이름을 사용하여 대상을 등록하는 방법**  
다음 `register-target-with-maintenance-window` 예제에서는 포함된 리소스 유형에 상관없이 지정된 리소스 그룹을 등록합니다.  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "RESOURCE_GROUP" \
    --target "Key=resource-groups:Name,Values=MyResourceGroup"
```
출력:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*[의 유지 관리 기간에 대상 인스턴스 등록(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-targets.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [RegisterTargetWithMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-target-with-maintenance-window.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간에 한 인스턴스를 등록합니다.**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**출력:**  

```
d8e47760-23ed-46a5-9f28-927337725398
```
**예제 2: 이 예제에서는 유지 관리 기간에 여러 인스턴스를 등록합니다.**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862","i-0cb2b964d3e14fd9f")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**출력:**  

```
6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
**예제 3: 이 예제에서는 EC2 태그를 사용하여 유지 관리 기간에 인스턴스를 등록합니다.**  

```
$option1 = @{Key="tag:Environment";Values=@("Production")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Production Web Servers" -ResourceType "INSTANCE"
```
**출력:**  

```
2994977e-aefb-4a71-beac-df620352f184
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RegisterTargetWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간에 한 인스턴스를 등록합니다.**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**출력:**  

```
d8e47760-23ed-46a5-9f28-927337725398
```
**예제 2: 이 예제에서는 유지 관리 기간에 여러 인스턴스를 등록합니다.**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862","i-0cb2b964d3e14fd9f")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**출력:**  

```
6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
**예제 3: 이 예제에서는 EC2 태그를 사용하여 유지 관리 기간에 인스턴스를 등록합니다.**  

```
$option1 = @{Key="tag:Environment";Values=@("Production")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Production Web Servers" -ResourceType "INSTANCE"
```
**출력:**  

```
2994977e-aefb-4a71-beac-df620352f184
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RegisterTargetWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `RegisterTaskWithMaintenanceWindow` 사용
<a name="ssm_example_ssm_RegisterTaskWithMaintenanceWindow_section"></a>

다음 코드 예시는 `RegisterTaskWithMaintenanceWindow`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 유지 관리 기간에 자동화 작업을 등록하는 방법**  
다음 `register-task-with-maintenance-window` 예제에서는 인스턴스에서 대상으로 지정된 유지 관리 기간에 자동화 작업을 등록합니다.  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-082dcd7649EXAMPLE" \
    --targets Key=InstanceIds,Values=i-1234520122EXAMPLE \
    --task-arn AWS-RestartEC2Instance \
    --service-role-arn arn:aws:iam::111222333444:role/SSM --task-type AUTOMATION \
    --task-invocation-parameters "{\"Automation\":{\"DocumentVersion\":\"\$LATEST\",\"Parameters\":{\"InstanceId\":[\"{{RESOURCE_ID}}\"]}}}" \
    --priority 0 \
    --max-concurrency 1 \
    --max-errors 1 \
    --name "AutomationExample" \
    --description "Restarting EC2 Instance for maintenance"
```
출력:  

```
{
    "WindowTaskId":"11144444-5555-6666-7777-88888888"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*[의 유지 관리 기간에 작업 등록(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)을 참조하세요.  
**예제 2: 유지 관리 기간에 Lambda 작업을 등록하는 방법**  
다음 `register-task-with-maintenance-window` 예제에서는 인스턴스에서 대상으로 지정된 유지 관리 기간에 Lambda 작업을 등록합니다.  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-082dcd7649dee04e4" \
    --targets Key=InstanceIds,Values=i-12344d305eEXAMPLE \
    --task-arn arn:aws:lambda:us-east-1:111222333444:function:SSMTestLAMBDA \
    --service-role-arn arn:aws:iam::111222333444:role/SSM \
    --task-type LAMBDA \
    --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}","Qualifier":"$LATEST"}}' \
    --priority 0 \
    --max-concurrency 10 \
    --max-errors 5 \
    --name "Lambda_Example" \
    --description "My Lambda Example"
```
출력:  

```
{
    "WindowTaskId":"22244444-5555-6666-7777-88888888"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*[의 유지 관리 기간에 작업 등록(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)을 참조하세요.  
**예제 3: 유지 관리 기간에 Run Command 작업을 등록하는 방법**  
다음 `register-task-with-maintenance-window` 예제에서는 인스턴스에서 대상으로 지정된 유지 관리 기간에 Run Command 작업을 등록합니다.  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-082dcd7649dee04e4" \
    --targets "Key=InstanceIds,Values=i-12344d305eEXAMPLE" \
    --service-role-arn "arn:aws:iam::111222333444:role/SSM" \
    --task-type "RUN_COMMAND" \
    --name "SSMInstallPowerShellModule" \
    --task-arn "AWS-InstallPowerShellModule" \
    --task-invocation-parameters "{\"RunCommand\":{\"Comment\":\"\",\"OutputS3BucketName\":\"runcommandlogs\",\"Parameters\":{\"commands\":[\"Get-Module -ListAvailable\"],\"executionTimeout\":[\"3600\"],\"source\":[\"https:\/\/gallery.technet.microsoft.com\/EZOut-33ae0fb7\/file\/110351\/1\/EZOut.zip\"],\"workingDirectory\":[\"\\\\\"]},\"TimeoutSeconds\":600}}" \
    --max-concurrency 1 \
    --max-errors 1 \
    --priority 10
```
출력:  

```
{
    "WindowTaskId":"33344444-5555-6666-7777-88888888"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*[의 유지 관리 기간에 작업 등록(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)을 참조하세요.  
**예제 4: 유지 관리 기간에 Step Functions 작업을 등록하는 방법**  
다음 `register-task-with-maintenance-window` 예제에서는 인스턴스에서 대상으로 지정된 유지 관리 기간에 Step Functions 작업을 등록합니다.  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-1234d787d6EXAMPLE" \
    --targets Key=WindowTargetIds,Values=12347414-69c3-49f8-95b8-ed2dcEXAMPLE \
    --task-arn arn:aws:states:us-east-1:111222333444:stateMachine:SSMTestStateMachine \
    --service-role-arn arn:aws:iam::111222333444:role/MaintenanceWindows \
    --task-type STEP_FUNCTIONS \
    --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}"}}' \
    --priority 0 \
    --max-concurrency 10 \
    --max-errors 5 \
    --name "Step_Functions_Example" \
    --description "My Step Functions Example"
```
출력:  

```
{
    "WindowTaskId":"44444444-5555-6666-7777-88888888"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*[의 유지 관리 기간에 작업 등록(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)을 참조하세요.  
**예제 5: 유지 관리 기간 대상 ID를 사용하여 작업을 등록하는 방법**  
다음 `register-task-with-maintenance-window` 예제에서는 유지 관리 기간 대상 ID를 사용하여 작업을 등록합니다. 유지 관리 기간 대상 ID는 `aws ssm register-target-with-maintenance-window` 명령 출력에 포함되어 있습니다. `aws ssm describe-maintenance-window-targets` 명령의 출력에서 검색할 수도 있습니다.  

```
aws ssm register-task-with-maintenance-window \
    --targets "Key=WindowTargetIds,Values=350d44e6-28cc-44e2-951f-4b2c9EXAMPLE" \
    --task-arn "AWS-RunShellScript" \
    --service-role-arn "arn:aws:iam::111222333444:role/MaintenanceWindowsRole" \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --task-type "RUN_COMMAND" \
    --task-parameters  "{\"commands\":{\"Values\":[\"df\"]}}" \
    --max-concurrency 1 \
    --max-errors 1 \
    --priority 10
```
출력:  

```
{
    "WindowTaskId":"33344444-5555-6666-7777-88888888"
}
```
자세한 내용은 *AWS Systems Manager 사용 설명서*[의 유지 관리 기간에 작업 등록(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [RegisterTaskWithMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-task-with-maintenance-window.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스 ID를 사용하여 유지 관리 기간에 작업을 등록합니다. 출력은 작업 ID입니다.**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

Register-SSMTaskWithMaintenanceWindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="InstanceIds";Values="i-0000293ffd8c57862" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**출력:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**예제 2: 이 예제에서는 대상 ID를 사용하여 유지 관리 기간에 작업을 등록합니다. 출력은 작업 ID입니다.**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

register-ssmtaskwithmaintenancewindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="WindowTargetIds";Values="350d44e6-28cc-44e2-951f-4b2c985838f6" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**출력:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**예제 3: 이 예제에서는 Run Command 문서 `AWS-RunPowerShellScript`에 대한 파라미터 객체를 생성하고 대상 ID를 사용하여 지정된 유지 관리 기간을 포함하는 작업을 생성합니다. 반환 출력은 작업 ID입니다.**  

```
$parameters = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$parameters.Add("commands",@("ipconfig","dir env:\computername"))
$parameters.Add("executionTimeout",@(3600))

$props = @{
    WindowId = "mw-0123e4cce56ff78ae"
    ServiceRoleArn = "arn:aws:iam::123456789012:role/MaintenanceWindowsRole"
    MaxConcurrency = 1
    MaxError = 1
    TaskType = "RUN_COMMAND"
    TaskArn = "AWS-RunPowerShellScript"
    Target = @{Key="WindowTargetIds";Values="fe1234ea-56d7-890b-12f3-456b789bee0f"}
    Priority = 1
    RunCommand_Parameter = $parameters
    Name = "set-via-cmdlet"
}

Register-SSMTaskWithMaintenanceWindow @props
```
**출력:**  

```
f1e2ef34-5678-12e3-456a-12334c5c6cbe
```
**예제 4:이 예제에서는 라는 문서를 사용하여 AWS Systems Manager 자동화 작업을 등록합니다`Create-Snapshots`.**  

```
$automationParameters = @{}
$automationParameters.Add( "instanceId", @("{{ TARGET_ID }}") )
$automationParameters.Add( "AutomationAssumeRole", @("{arn:aws:iam::111111111111:role/AutomationRole}") )
$automationParameters.Add( "SnapshotTimeout", @("PT20M") )
Register-SSMTaskWithMaintenanceWindow -WindowId mw-123EXAMPLE456`
    -ServiceRoleArn "arn:aws:iam::123456789012:role/MW-Role"`
    -MaxConcurrency 1 -MaxError 1 -TaskArn "CreateVolumeSnapshots"`
    -Target @{ Key="WindowTargetIds";Values="4b5acdf4-946c-4355-bd68-4329a43a5fd1" }`
    -TaskType "AUTOMATION"`
    -Priority 4`
    -Automation_DocumentVersion '$DEFAULT' -Automation_Parameter $automationParameters -Name "Create-Snapshots"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RegisterTaskWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스 ID를 사용하여 유지 관리 기간에 작업을 등록합니다. 출력은 작업 ID입니다.**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

Register-SSMTaskWithMaintenanceWindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="InstanceIds";Values="i-0000293ffd8c57862" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**출력:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**예제 2: 이 예제에서는 대상 ID를 사용하여 유지 관리 기간에 작업을 등록합니다. 출력은 작업 ID입니다.**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

register-ssmtaskwithmaintenancewindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="WindowTargetIds";Values="350d44e6-28cc-44e2-951f-4b2c985838f6" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**출력:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**예제 3: 이 예제에서는 Run Command 문서 `AWS-RunPowerShellScript`에 대한 파라미터 객체를 생성하고 대상 ID를 사용하여 지정된 유지 관리 기간을 포함하는 작업을 생성합니다. 반환 출력은 작업 ID입니다.**  

```
$parameters = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$parameters.Add("commands",@("ipconfig","dir env:\computername"))
$parameters.Add("executionTimeout",@(3600))

$props = @{
    WindowId = "mw-0123e4cce56ff78ae"
    ServiceRoleArn = "arn:aws:iam::123456789012:role/MaintenanceWindowsRole"
    MaxConcurrency = 1
    MaxError = 1
    TaskType = "RUN_COMMAND"
    TaskArn = "AWS-RunPowerShellScript"
    Target = @{Key="WindowTargetIds";Values="fe1234ea-56d7-890b-12f3-456b789bee0f"}
    Priority = 1
    RunCommand_Parameter = $parameters
    Name = "set-via-cmdlet"
}

Register-SSMTaskWithMaintenanceWindow @props
```
**출력:**  

```
f1e2ef34-5678-12e3-456a-12334c5c6cbe
```
**예제 4:이 예제에서는 라는 문서를 사용하여 AWS Systems Manager 자동화 작업을 등록합니다`Create-Snapshots`.**  

```
$automationParameters = @{}
$automationParameters.Add( "instanceId", @("{{ TARGET_ID }}") )
$automationParameters.Add( "AutomationAssumeRole", @("{arn:aws:iam::111111111111:role/AutomationRole}") )
$automationParameters.Add( "SnapshotTimeout", @("PT20M") )
Register-SSMTaskWithMaintenanceWindow -WindowId mw-123EXAMPLE456`
    -ServiceRoleArn "arn:aws:iam::123456789012:role/MW-Role"`
    -MaxConcurrency 1 -MaxError 1 -TaskArn "CreateVolumeSnapshots"`
    -Target @{ Key="WindowTargetIds";Values="4b5acdf4-946c-4355-bd68-4329a43a5fd1" }`
    -TaskType "AUTOMATION"`
    -Priority 4`
    -Automation_DocumentVersion '$DEFAULT' -Automation_Parameter $automationParameters -Name "Create-Snapshots"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RegisterTaskWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `RemoveTagsFromResource` 사용
<a name="ssm_example_ssm_RemoveTagsFromResource_section"></a>

다음 코드 예시는 `RemoveTagsFromResource`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**패치 기준에서 태그를 삭제하는 방법**  
다음 `remove-tags-from-resource` 예제에서는 패치 기준에서 태그를 제거합니다.  

```
aws ssm remove-tags-from-resource \
    --resource-type "PatchBaseline" \
    --resource-id "pb-0123456789abcdef0" \
    --tag-keys "Region"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS 일반* 참조의 [AWS 리소스 태그 지정](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RemoveTagsFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/remove-tags-from-resource.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간에서 태그를 제거합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -TagKey "Production"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간에서 태그를 제거합니다. 명령이 성공해도 출력은 없습니다.**  

```
Remove-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -TagKey "Production"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `SendCommand` 함께 사용
<a name="ssm_example_ssm_SendCommand_section"></a>

다음 코드 예시는 `SendCommand`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md) 

------
#### [ 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를 사용하여 명령 실행](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` 예제는 서로 다른 두 개의 태그 키와 값을 가진 인스턴스에서 명령을 실행합니다.  

```
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 Cmdlet 참조(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 API**  
 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)를 참조하세요.

------

# CLI로 `StartAutomationExecution` 사용
<a name="ssm_example_ssm_StartAutomationExecution_section"></a>

다음 코드 예시는 `StartAutomationExecution`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 자동화 문서를 실행하는 방법**  
다음 `start-automation-execution` 예제에서는 자동화 문서를 실행합니다.  

```
aws ssm start-automation-execution \
    --document-name "AWS-UpdateLinuxAmi" \
    --parameters "AutomationAssumeRole=arn:aws:iam::123456789012:role/SSMAutomationRole,SourceAmiId=ami-EXAMPLE,IamInstanceProfileName=EC2InstanceRole"
```
출력:  

```
{
  "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0a1b2EXAMPLE"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [수동으로 자동화 워크플로 실행](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing-manually.html)을 참조하세요.  
**예제 2: 공유 자동화 문서를 실행하는 방법**  
다음 `start-automation-execution` 예제에서는 공유 자동화 문서를 실행합니다.  

```
aws ssm start-automation-execution \
    --document-name "arn:aws:ssm:us-east-1:123456789012:document/ExampleDocument"
```
출력:  

```
{
  "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0a1b2EXAMPLE"
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [공유 SSM 문서 사용](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-using-shared.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [StartAutomationExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/start-automation-execution.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 자동화 역할, AMI 소스 ID 및 Amazon EC2 인스턴스 역할을 지정하는 문서를 실행합니다.**  

```
Start-SSMAutomationExecution -DocumentName AWS-UpdateLinuxAmi -Parameter @{'AutomationAssumeRole'='arn:aws:iam::123456789012:role/SSMAutomationRole';'SourceAmiId'='ami-f173cc91';'InstanceIamRole'='EC2InstanceRole'}
```
**출력:**  

```
3a532a4f-0382-11e7-9df7-6f11185f6dd1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [StartAutomationExecution](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 자동화 역할, AMI 소스 ID 및 Amazon EC2 인스턴스 역할을 지정하는 문서를 실행합니다.**  

```
Start-SSMAutomationExecution -DocumentName AWS-UpdateLinuxAmi -Parameter @{'AutomationAssumeRole'='arn:aws:iam::123456789012:role/SSMAutomationRole';'SourceAmiId'='ami-f173cc91';'InstanceIamRole'='EC2InstanceRole'}
```
**출력:**  

```
3a532a4f-0382-11e7-9df7-6f11185f6dd1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [StartAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `StartSession` 사용
<a name="ssm_example_ssm_StartSession_section"></a>

다음 코드 예시는 `StartSession`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예 1: Session Manager 세션 시작**  
이 `start-session` 예제는 Session Manager 세션을 위해 인스턴스에 대한 연결을 설정합니다. 참고로 이 대화형 명령을 사용하려면 호출을 수행하는 클라이언트 시스템에 Session Manager 플러그인을 설치해야 합니다.  

```
aws ssm start-session \
    --target "i-1234567890abcdef0"
```
출력:  

```
Starting session with SessionId: Jane-Roe-07a16060613c408b5
```
**예 2: SSH를 사용하는 Session Manager 세션 시작**  
이 `start-session` 예에서는 SSH를 사용하는 Session Manager 세션을 위해 인스턴스에 연결합니다. 참고로 이 대화형 명령을 사용하려면 호출을 수행하는 클라이언트 시스템에 Session Manager 플러그인을 설치해야 하며, 명령은 인스턴스의 기본 사용자(예: Linux용 EC2 인스턴스를 위한 `ec2-user`)가 필요합니다.  

```
ssh -i /path/my-key-pair.pem ec2-user@i-02573cafcfEXAMPLE
```
출력:  

```
Starting session with SessionId: ec2-user-07a16060613c408b5
```
자세한 내용은 Systems Manager 사용 설명서의 [세션 시작](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html) 및 CLI용 세션 관리자 플러그인 설치를 참조하세요. [AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) *AWS *   
+  API 세부 정보는 *AWS CLI 명령 참조*의 [StartSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/start-session.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예 1: 이 예제는 Session Manager 세션의 대상에 대한 연결을 시작하여 포트 전달을 활성화합니다.**  

```
Start-SSMSession -Target 'i-064578e5e7454488f' -DocumentName 'AWS-StartPortForwardingSession' -Parameter @{ localPortNumber = '8080'; portNumber = '80' }
```
**출력:**  

```
SessionId    StreamUrl
----------    ----------
random-id0    wss://ssmmessages.amazonaws.com/v1/data-channel/random-id
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [StartSession](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예 1: 이 예제는 Session Manager 세션의 대상에 대한 연결을 시작하여 포트 전달을 활성화합니다. 참고: AWSCredentials를 사용하여 아직 설정하지 않은 경우 Region 파라미터를 추가해야 합니다.**  

```
Start-SSMSession -Target 'i-064578e5e7454488f' -DocumentName 'AWS-StartPortForwardingSession' -Parameter @{ localPortNumber = '8080'; portNumber = '80' } -Region 'us-west-1'
```
**출력:**  

```
Starting session with SessionId: testUser-xi4glew849asyeryde34u4dfsdfy
Port 8080 opened for sessionId testUser-xi4glew849asyeryde34u4dfsdfy.
Waiting for connections...
```
**예제 2: 이 예제에서는 Session Manager 세션에 대해 지정된 인스턴스를 사용하여 대화형 세션을 생성합니다.**  

```
Start-SSMSession -Target 'i-1234567890abcdef0' -Region 'us-west-1'
```
**출력:**  

```
Starting session with SessionId : testUser-xi4glew849asyeryde34u4dfsdfy
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
                                                                                                                                                                                                
Install the latest PowerShell for new features and improvements!
                                                                                                                                                      
PS C:\Windows\system32> whoami
ec2amaz-fnsdrwv\ec2-test-user
PS C:\Windows\system32>
```
**예제 3: 이 예제에서는 세션에 연결하지 않고 세션을 생성하고 세션에 연결하는 데 필요한 SessionId, StreamUrl, TokenValue 속성을 반환합니다.**  

```
Start-SSMSession -Target 'i-1234567890abcdef0' -Region 'us-west-1' -DisablePluginInvocation
```
**출력:**  

```
SessionId        : testUser-xi4glew849asyeryde34u4dfsdfy
StreamUrl        : {StreamUrl value redacted}
TokenValue       : {Token value redacted}
ContentLength    : 1207
HttpStatusCode   : OK
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [StartSession](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `StopAutomationExecution` 사용
<a name="ssm_example_ssm_StopAutomationExecution_section"></a>

다음 코드 예시는 `StopAutomationExecution`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**자동화 실행을 중지하는 방법**  
다음 `stop-automation-execution` 예제에서는 자동화 문서를 중지합니다.  

```
aws ssm stop-automation-execution
    --automation-execution-id "4105a4fc-f944-11e6-9d32-0a1b2EXAMPLE"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [수동으로 자동화 워크플로 실행](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing-manually.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [StopAutomationExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/stop-automation-execution.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 자동화 실행을 중지합니다. 명령이 성공해도 출력은 없습니다.**  

```
Stop-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [StopAutomationExecution](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 자동화 실행을 중지합니다. 명령이 성공해도 출력은 없습니다.**  

```
Stop-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [StopAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `UpdateAssociation` 사용
<a name="ssm_example_ssm_UpdateAssociation_section"></a>

다음 코드 예시는 `UpdateAssociation`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 문서 연결을 업데이트하는 방법**  
다음 `update-association` 예제에서는 새 문서 버전과의 연결을 업데이트합니다.  

```
aws ssm update-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --document-version "\$LATEST"
```
출력:  

```
{
    "AssociationDescription": {
        "Name": "AWS-UpdateSSMAgent",
        "AssociationVersion": "2",
        "Date": 1550508093.293,
        "LastUpdateAssociationDate": 1550508106.596,
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "DocumentVersion": "$LATEST",
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "tag:Name",
                "Values": [
                    "Linux"
                ]
            }
        ],
        "LastExecutionDate": 1550508094.879,
        "LastSuccessfulExecutionDate": 1550508094.879
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [새 연결 버전 편집 및 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)을 참조하세요.  
**예제 2: 연결의 일정 표현식을 업데이트하는 방법**  
다음 `update-association` 예제에서는 지정된 연결의 일정 표현식을 업데이트합니다.  

```
aws ssm update-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --schedule-expression "cron(0 0 0/4 1/1 * ? *)"
```
출력:  

```
{
    "AssociationDescription": {
        "Name": "AWS-HelloWorld",
        "AssociationVersion": "2",
        "Date": "2021-02-08T13:54:19.203000-08:00",
        "LastUpdateAssociationDate": "2021-06-29T11:51:07.933000-07:00",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "DocumentVersion": "$DEFAULT",
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "aws:NoOpAutomationTag",
                "Values": [
                    "AWS-NoOpAutomationTarget-Value"
                ]
            }
        ],
        "ScheduleExpression": "cron(0 0 0/4 1/1 * ? *)",
        "LastExecutionDate": "2021-06-26T19:00:48.110000-07:00",
        "ApplyOnlyAtCronInterval": false
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [새 연결 버전 편집 및 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-association.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 연결을 새 문서 버전으로 업데이트합니다.**  

```
Update-SSMAssociation -AssociationId "93285663-92df-44cb-9f26-2292d4ecc439" -DocumentVersion "1"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdateAssociation](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 연결을 새 문서 버전으로 업데이트합니다.**  

```
Update-SSMAssociation -AssociationId "93285663-92df-44cb-9f26-2292d4ecc439" -DocumentVersion "1"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `UpdateAssociationStatus` 사용
<a name="ssm_example_ssm_UpdateAssociationStatus_section"></a>

다음 코드 예시는 `UpdateAssociationStatus`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**연결 상태를 업데이트하는 방법**  
다음 `update-association-status` 예제에서는 인스턴스와 문서 간 연결의 연결 상태를 업데이트합니다.  

```
aws ssm update-association-status \
    --name "AWS-UpdateSSMAgent" \
    --instance-id "i-1234567890abcdef0" \
    --association-status "Date=1424421071.939,Name=Pending,Message=temp_status_change,AdditionalInfo=Additional-Config-Needed"
```
출력:  

```
{
    "AssociationDescription": {
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-1234567890abcdef0",
        "AssociationVersion": "1",
        "Date": 1550507529.604,
        "LastUpdateAssociationDate": 1550507806.974,
        "Status": {
            "Date": 1424421071.0,
            "Name": "Pending",
            "Message": "temp_status_change",
            "AdditionalInfo": "Additional-Config-Needed"
        },
        "Overview": {
            "Status": "Success",
            "AssociationStatusAggregatedCount": {
                "Success": 1
            }
        },
        "DocumentVersion": "$DEFAULT",
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "InstanceIds",
                "Values": [
                    "i-1234567890abcdef0"
                ]
            }
        ],
        "LastExecutionDate": 1550507808.0,
        "LastSuccessfulExecutionDate": 1550507808.0
    }
}
```
자세한 내용은 *AWS * Systems Manager 사용 설명서의 [Systems Manager에서 연결 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateAssociationStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-association-status.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 인스턴스 및 구성 문서 간 연결 상태를 업데이트합니다.**  

```
Update-SSMAssociationStatus -Name "AWS-UpdateSSMAgent" -InstanceId "i-0000293ffd8c57862" -AssociationStatus_Date "2015-02-20T08:31:11Z" -AssociationStatus_Name "Pending" -AssociationStatus_Message "temporary_status_change" -AssociationStatus_AdditionalInfo "Additional-Config-Needed"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temporary_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdateAssociationStatus](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 인스턴스 및 구성 문서 간 연결 상태를 업데이트합니다.**  

```
Update-SSMAssociationStatus -Name "AWS-UpdateSSMAgent" -InstanceId "i-0000293ffd8c57862" -AssociationStatus_Date "2015-02-20T08:31:11Z" -AssociationStatus_Name "Pending" -AssociationStatus_Message "temporary_status_change" -AssociationStatus_AdditionalInfo "Additional-Config-Needed"
```
**출력:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temporary_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateAssociationStatus](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `UpdateDocument` 사용
<a name="ssm_example_ssm_UpdateDocument_section"></a>

다음 코드 예시는 `UpdateDocument`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서의 새 버전을 생성하는 방법**  
다음 `update-document` 예제에서는 Windows 컴퓨터에서 실행 시 문서의 새 버전을 생성합니다. `--document`에서 지정한 문서는 JSON 형식이어야 합니다. 콘텐츠 파일 경로 앞에서 `file://`을 참조해야 합니다. `--document-version` 파라미터의 시작 위치에 `$`이 있으므로 Windows에서는 값을 큰따옴표로 묶어야 합니다. Linux, MacOS 또는 PowerShell 프롬프트에서는 값을 작은따옴표로 묶어야 합니다.  
**Windows 버전**:  

```
aws ssm update-document \
    --name "RunShellScript" \
    --content "file://RunShellScript.json" \
    --document-version "$LATEST"
```
**Linux 및 Mac 버전**:  

```
aws ssm update-document \
    --name "RunShellScript" \
    --content "file://RunShellScript.json" \
    --document-version '$LATEST'
```
출력:  

```
{
  "DocumentDescription": {
      "Status": "Updating",
      "Hash": "f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b",
      "Name": "RunShellScript",
      "Parameters": [
          {
              "Type": "StringList",
              "Name": "commands",
              "Description": "(Required) Specify a shell script or a command to run."
          }
      ],
      "DocumentType": "Command",
      "PlatformTypes": [
          "Linux"
      ],
      "DocumentVersion": "2",
      "HashType": "Sha256",
      "CreatedDate": 1487899655.152,
      "Owner": "809632081692",
      "SchemaVersion": "2.0",
      "DefaultVersion": "1",
      "LatestVersion": "2",
      "Description": "Run an updated script"
  }
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-document.html) 섹션을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 지정한 json 파일의 업데이트된 콘텐츠를 포함하는 문서의 새 버전을 생성합니다. 문서는 JSON 형식이어야 합니다. 'Get-SSMDocumentVersionList' cmdlet을 사용하여 문서 버전을 얻을 수 있습니다.**  

```
Update-SSMDocument -Name RunShellScript -DocumentVersion "1" -Content (Get-Content -Raw "c:\temp\RunShellScript.json")
```
**출력:**  

```
CreatedDate     : 3/1/2017 2:59:17 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 2
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 2
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Updating
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdateDocument](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 지정한 json 파일의 업데이트된 콘텐츠를 포함하는 문서의 새 버전을 생성합니다. 문서는 JSON 형식이어야 합니다. 'Get-SSMDocumentVersionList' cmdlet을 사용하여 문서 버전을 얻을 수 있습니다.**  

```
Update-SSMDocument -Name RunShellScript -DocumentVersion "1" -Content (Get-Content -Raw "c:\temp\RunShellScript.json")
```
**출력:**  

```
CreatedDate     : 3/1/2017 2:59:17 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 2
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 2
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Updating
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateDocument](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `UpdateDocumentDefaultVersion` 사용
<a name="ssm_example_ssm_UpdateDocumentDefaultVersion_section"></a>

다음 코드 예시는 `UpdateDocumentDefaultVersion`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**문서의 기본 버전을 업데이트하는 방법**  
다음 `update-document-default-version` 예제에서는 Systems Manager 문서의 기본 버전을 업데이트합니다.  

```
aws ssm update-document-default-version \
    --name "Example" \
    --document-version "2"
```
출력:  

```
{
    "Description": {
        "Name": "Example",
        "DefaultVersion": "2"
    }
}
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [SSM 문서 콘텐츠 작성](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html#writing-ssm-doc-content)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateDocumentDefaultVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-document-default-version.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 여기에서는 문서의 기본 버전을 업데이트합니다. 'Get-SSMDocumentVersionList' cmdlet을 사용하여 사용 가능한 문서 버전을 얻을 수 있습니다.**  

```
Update-SSMDocumentDefaultVersion -Name "RunShellScript" -DocumentVersion "2"
```
**출력:**  

```
DefaultVersion Name
-------------- ----
2              RunShellScript
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdateDocumentDefaultVersion](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 여기에서는 문서의 기본 버전을 업데이트합니다. 'Get-SSMDocumentVersionList' cmdlet을 사용하여 사용 가능한 문서 버전을 얻을 수 있습니다.**  

```
Update-SSMDocumentDefaultVersion -Name "RunShellScript" -DocumentVersion "2"
```
**출력:**  

```
DefaultVersion Name
-------------- ----
2              RunShellScript
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateDocumentDefaultVersion](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# AWS SDK 또는 CLI와 `UpdateMaintenanceWindow` 함께 사용
<a name="ssm_example_ssm_UpdateMaintenanceWindow_section"></a>

다음 코드 예시는 `UpdateMaintenanceWindow`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 유지 관리 기간을 업데이트하는 방법**  
다음 `update-maintenance-window` 예제에서는 유지 관리 기간의 이름을 업데이트합니다.  

```
aws ssm update-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9" \
    --name "My-Renamed-MW"
```
출력:  

```
{
    "Cutoff": 1,
    "Name": "My-Renamed-MW",
    "Schedule": "cron(0 16 ? * TUE *)",
    "Enabled": true,
    "AllowUnassociatedTargets": true,
    "WindowId": "mw-1a2b3c4d5e6f7g8h9",
    "Duration": 4
}
```
**예제 2: 유지 관리 기간을 비활성화하는 방법**  
다음 `update-maintenance-window` 예제에서는 유지 관리 기간을 비활성화합니다.  

```
aws ssm update-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9" \
    --no-enabled
```
**예제 3: 유지 관리 기간을 활성화하는 방법**  
다음 `update-maintenance-window` 예제에서는 유지 관리 기간을 활성화합니다.  

```
aws ssm update-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9" \
    --enabled
```
자세한 내용은 *AWS Systems Manager 사용 설명서*의 [유지 관리 기간 업데이트(AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-update.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-maintenance-window.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Updates an SSM maintenance window asynchronously.
     *
     * @param id The ID of the maintenance window to update.
     * @param name The new name for the maintenance window.
     * <p>
     * This method initiates an asynchronous request to update an SSM maintenance window.
     * If the request is successful, it prints a success message.
     * If an exception occurs, it handles the error appropriately.
     */
    public void updateSSMMaintenanceWindow(String id, String name) throws SsmException {
        UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder()
                .windowId(id)
                .allowUnassociatedTargets(true)
                .duration(24)
                .enabled(true)
                .name(name)
                .schedule("cron(0 0 ? * MON *)")
                .build();

        CompletableFuture<UpdateMaintenanceWindowResponse> future = getAsyncClient().updateMaintenanceWindow(updateRequest);
        future.whenComplete((response, ex) -> {
            if (response != null) {
                System.out.println("The SSM maintenance window was successfully updated");
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();
    }
```
+  API 세부 정보는 **AWS SDK for Java 2.x API 참조의 [UpdateMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/UpdateMaintenanceWindow)를 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { UpdateMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Update an SSM maintenance window.
 * @param {{ windowId: string, allowUnassociatedTargets?: boolean, duration?: number, enabled?: boolean, name?: string, schedule?: string }}
 */
export const main = async ({
  windowId,
  allowUnassociatedTargets = undefined, //Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
  duration = undefined, //The duration of the maintenance window in hours.
  enabled = undefined,
  name = undefined,
  schedule = undefined, //The schedule of the maintenance window in the form of a cron or rate expression.
}) => {
  const client = new SSMClient({});
  try {
    const { opsItemArn, opsItemId } = await client.send(
      new UpdateMaintenanceWindowCommand({
        WindowId: windowId,
        AllowUnassociatedTargets: allowUnassociatedTargets,
        Duration: duration,
        Enabled: enabled,
        Name: name,
        Schedule: schedule,
      }),
    );
    console.log("Maintenance window updated.");
    return { OpsItemArn: opsItemArn, OpsItemId: opsItemId };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ValidationError") {
      console.warn(`${caught.message}. Are these values correct?`);
    } else {
      throw caught;
    }
  }
};
```
+  API 세부 정보는 **AWS SDK for JavaScript API 참조의 [UpdateMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/UpdateMaintenanceWindowCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 유지 관리 기간의 이름을 업데이트합니다.**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Name "My-Renamed-MW"
```
**출력:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**예제 2: 이 예제에서는 유지 관리 기간을 활성화합니다.**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $true
```
**출력:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**예제 3: 이 예제에서는 유지 관리 기간을 비활성화합니다.**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $false
```
**출력:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : False
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 유지 관리 기간의 이름을 업데이트합니다.**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Name "My-Renamed-MW"
```
**출력:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**예제 2: 이 예제에서는 유지 관리 기간을 활성화합니다.**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $true
```
**출력:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**예제 3: 이 예제에서는 유지 관리 기간을 비활성화합니다.**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $false
```
**출력:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : False
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateMaintenanceWindow](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 MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def update(
        self, name, enabled, schedule, duration, cutoff, allow_unassociated_targets
    ):
        """
        Update an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param enabled: Whether the maintenance window is enabled to run on managed nodes.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            self.ssm_client.update_maintenance_window(
                WindowId=self.window_id,
                Name=name,
                Enabled=enabled,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.name = name
            logger.info("Updated maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to update maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't update maintenance window %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [UpdateMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/UpdateMaintenanceWindow)를 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ssm->updatemaintenancewindow(
            iv_windowid = iv_window_id
            iv_name = iv_name
            iv_enabled = iv_enabled
            iv_schedule = iv_schedule
            iv_duration = iv_duration
            iv_cutoff = iv_cutoff
            iv_allowunassociatedtargets = iv_allow_unassociated_targets ).
        MESSAGE 'Maintenance window updated.' TYPE 'I'.
      CATCH /aws1/cx_ssmdoesnotexistex.
        MESSAGE 'Maintenance window does not exist.' TYPE 'I'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [UpdateMaintenanceWindow](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `UpdateManagedInstanceRole` 사용
<a name="ssm_example_ssm_UpdateManagedInstanceRole_section"></a>

다음 코드 예시는 `UpdateManagedInstanceRole`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**관리형 인스턴스의 IAM 역할을 업데이트하는 방법**  
다음 `update-managed-instance-role` 예제에서는 관리형 인스턴스의 IAM 인스턴스 프로파일을 업데이트합니다.  

```
aws ssm update-managed-instance-role \
    --instance-id "mi-08ab247cdfEXAMPLE" \
    --iam-role "ExampleRole"
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS Systems Manager 사용 설명서의 [4단계: Systems Manager에 대한 IAM 인스턴스 프로파일 생성](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateManagedInstanceRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-managed-instance-role.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 관리형 인스턴스의 역할을 업데이트합니다. 명령이 성공해도 출력은 없습니다.**  

```
Update-SSMManagedInstanceRole -InstanceId "mi-08ab247cdf1046573" -IamRole "AutomationRole"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdateManagedInstanceRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 관리형 인스턴스의 역할을 업데이트합니다. 명령이 성공해도 출력은 없습니다.**  

```
Update-SSMManagedInstanceRole -InstanceId "mi-08ab247cdf1046573" -IamRole "AutomationRole"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateManagedInstanceRole](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# AWS SDK 또는 CLI와 `UpdateOpsItem` 함께 사용
<a name="ssm_example_ssm_UpdateOpsItem_section"></a>

다음 코드 예시는 `UpdateOpsItem`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](ssm_example_ssm_Scenario_section.md) 

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

**AWS CLI**  
**OpsItem을 업데이트하는 방법**  
다음 `update-ops-item` 예시에서는 OpsItem의 설명, 우선순위 및 범주를 업데이트합니다. 또한 이 명령은 이 OpsItem을 편집하거나 변경할 때 알림이 전송되는 SNS 주제를 지정합니다.  

```
aws ssm update-ops-item \
    --ops-item-id "oi-287b5EXAMPLE" \
    --description "Primary OpsItem for failover event 2020-01-01-fh398yf" \
    --priority 2 \
    --category "Security" \
    --notifications "Arn=arn:aws:sns:us-east-2:111222333444:my-us-east-2-topic"
```
출력:  

```
This command produces no output.
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 [OpsItems 작업](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateOpsItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-ops-item.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)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    /**
     * Resolves an AWS SSM OpsItem asynchronously.
     *
     * @param opsID The ID of the OpsItem to resolve.
     * <p>
     * This method initiates an asynchronous request to resolve an SSM OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void resolveOpsItem(String opsID) {
        UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder()
                .opsItemId(opsID)
                .status(OpsItemStatus.RESOLVED)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().updateOpsItem(opsItemRequest)
                    .thenAccept(response -> {
                        System.out.println("OpsItem resolved successfully.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API에 대한 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [UpdateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/UpdateOpsItem)을 참조하세요.

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { UpdateOpsItemCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Update an SSM OpsItem.
 * @param {{ opsItemId: string, status?: OpsItemStatus }}
 */
export const main = async ({
  opsItemId,
  status = undefined, // The OpsItem status. Status can be Open, In Progress, or Resolved
}) => {
  const client = new SSMClient({});
  try {
    await client.send(
      new UpdateOpsItemCommand({
        OpsItemId: opsItemId,
        Status: status,
      }),
    );
    console.log("Ops item updated.");
    return { Success: true };
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "OpsItemLimitExceededException"
    ) {
      console.warn(
        `Couldn't create ops item because you have exceeded your open OpsItem limit. ${caught.message}.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API에 대한 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UpdateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/UpdateOpsItemCommand)을 참조하세요.

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

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def update(self, title=None, description=None, status=None):
        """
        Update an OpsItem.

        :param title: The new OpsItem title.
        :param description: The new OpsItem description.
        :param status: The new OpsItem status.
        :return:
        """
        args = dict(OpsItemId=self.id)
        if title is not None:
            args["Title"] = title
        if description is not None:
            args["Description"] = description
        if status is not None:
            args["Status"] = status
        try:
            self.ssm_client.update_ops_item(**args)
        except ClientError as err:
            logger.error(
                "Couldn't update ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [UpdateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/UpdateOpsItem)을 참조하세요.

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

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_ssm->updateopsitem(
            iv_opsitemid = iv_ops_item_id
            iv_title = iv_title
            iv_description = iv_description
            iv_status = iv_status ).
        MESSAGE 'OpsItem updated.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsitemnotfoundex.
        MESSAGE 'OpsItem not found.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsiteminvparamex.
        MESSAGE 'Invalid OpsItem parameter.' TYPE 'I'.
    ENDTRY.
```
+  API 세부 정보는 [AWS SDK for SAP ABAP API 참조](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)의 *UpdateOpsItem*을 참조하세요.

------

# CLI로 `UpdatePatchBaseline` 사용
<a name="ssm_example_ssm_UpdatePatchBaseline_section"></a>

다음 코드 예시는 `UpdatePatchBaseline`의 사용 방법을 보여 줍니다.

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

**AWS CLI**  
**예제 1: 패치 기준을 업데이트하는 방법**  
다음 `update-patch-baseline` 예제에서는 지정된 두 개의 패치를 거부된 패치로 추가하고 하나의 패치를 기존 패치 기준에 승인된 패치로 추가합니다.  

```
aws ssm update-patch-baseline \
        --baseline-id "pb-0123456789abcdef0" \
        --rejected-patches "KB2032276" "MS10-048" \
        --approved-patches "KB2124261"
```
출력:  

```
{
    "BaselineId": "pb-0123456789abcdef0",
    "Name": "WindowsPatching",
    "OperatingSystem": "WINDOWS",
    "GlobalFilters": {
        "PatchFilters": []
    },
    "ApprovalRules": {
        "PatchRules": [
            {
                "PatchFilterGroup": {
                    "PatchFilters": [
                        {
                            "Key": "PRODUCT",
                            "Values": [
                                "WindowsServer2016"
                            ]
                        }
                    ]
                },
                "ComplianceLevel": "CRITICAL",
                "ApproveAfterDays": 0,
                "EnableNonSecurity": false
            }
        ]
    },
    "ApprovedPatches": [
        "KB2124261"
    ],
    "ApprovedPatchesComplianceLevel": "UNSPECIFIED",
    "ApprovedPatchesEnableNonSecurity": false,
    "RejectedPatches": [
        "KB2032276",
        "MS10-048"
    ],
    "RejectedPatchesAction": "ALLOW_AS_DEPENDENCY",
    "CreatedDate": 1550244180.465,
    "ModifiedDate": 1550244180.465,
    "Description": "Patches for Windows Servers",
    "Sources": []
}
```
**예제 2: 패치 기준의 이름을 바꾸는 방법**  
다음 `update-patch-baseline` 예제에서는 지정된 패치 기준의 이름을 바꿉니다.  

```
aws ssm update-patch-baseline \
    --baseline-id "pb-0713accee01234567" \
    --name "Windows-Server-2012-R2-Important-and-Critical-Security-Updates"
```
자세한 내용은 **AWS Systems Manager 사용 설명서의 패치 기준 업데이트 또는 삭제(<https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-baseline-update-or-delete.html>`\$1\$1)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdatePatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-patch-baseline.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 기존 패치 기준에 두 개의 패치를 거부된 패치로 추가하고 한 개의 패치를 승인된 패치로 추가합니다.**  

```
Update-SSMPatchBaseline -BaselineId "pb-03da896ca3b68b639" -RejectedPatch "KB2032276","MS10-048" -ApprovedPatch "KB2124261"
```
**출력:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {KB2124261}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:22:10 PM
Name            : Production-Baseline
RejectedPatches : {KB2032276, MS10-048}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [UpdatePatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 기존 패치 기준에 두 개의 패치를 거부된 패치로 추가하고 한 개의 패치를 승인된 패치로 추가합니다.**  

```
Update-SSMPatchBaseline -BaselineId "pb-03da896ca3b68b639" -RejectedPatch "KB2032276","MS10-048" -ApprovedPatch "KB2124261"
```
**출력:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {KB2124261}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:22:10 PM
Name            : Production-Baseline
RejectedPatches : {KB2032276, MS10-048}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------