

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

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

# AWS SDKs 사용한 IAM의 기본 예제
<a name="iam_code_examples_basics"></a>

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

**Contents**
+ [Hello IAM](iam_example_iam_Hello_section.md)
+ [기본 사항 알아보기](iam_example_iam_Scenario_CreateUserAssumeRole_section.md)
+ [작업](iam_code_examples_actions.md)
  + [`AddClientIdToOpenIdConnectProvider`](iam_example_iam_AddClientIdToOpenIdConnectProvider_section.md)
  + [`AddRoleToInstanceProfile`](iam_example_iam_AddRoleToInstanceProfile_section.md)
  + [`AddUserToGroup`](iam_example_iam_AddUserToGroup_section.md)
  + [`AttachGroupPolicy`](iam_example_iam_AttachGroupPolicy_section.md)
  + [`AttachRolePolicy`](iam_example_iam_AttachRolePolicy_section.md)
  + [`AttachUserPolicy`](iam_example_iam_AttachUserPolicy_section.md)
  + [`ChangePassword`](iam_example_iam_ChangePassword_section.md)
  + [`CreateAccessKey`](iam_example_iam_CreateAccessKey_section.md)
  + [`CreateAccountAlias`](iam_example_iam_CreateAccountAlias_section.md)
  + [`CreateGroup`](iam_example_iam_CreateGroup_section.md)
  + [`CreateInstanceProfile`](iam_example_iam_CreateInstanceProfile_section.md)
  + [`CreateLoginProfile`](iam_example_iam_CreateLoginProfile_section.md)
  + [`CreateOpenIdConnectProvider`](iam_example_iam_CreateOpenIdConnectProvider_section.md)
  + [`CreatePolicy`](iam_example_iam_CreatePolicy_section.md)
  + [`CreatePolicyVersion`](iam_example_iam_CreatePolicyVersion_section.md)
  + [`CreateRole`](iam_example_iam_CreateRole_section.md)
  + [`CreateSAMLProvider`](iam_example_iam_CreateSAMLProvider_section.md)
  + [`CreateServiceLinkedRole`](iam_example_iam_CreateServiceLinkedRole_section.md)
  + [`CreateUser`](iam_example_iam_CreateUser_section.md)
  + [`CreateVirtualMfaDevice`](iam_example_iam_CreateVirtualMfaDevice_section.md)
  + [`DeactivateMfaDevice`](iam_example_iam_DeactivateMfaDevice_section.md)
  + [`DeleteAccessKey`](iam_example_iam_DeleteAccessKey_section.md)
  + [`DeleteAccountAlias`](iam_example_iam_DeleteAccountAlias_section.md)
  + [`DeleteAccountPasswordPolicy`](iam_example_iam_DeleteAccountPasswordPolicy_section.md)
  + [`DeleteGroup`](iam_example_iam_DeleteGroup_section.md)
  + [`DeleteGroupPolicy`](iam_example_iam_DeleteGroupPolicy_section.md)
  + [`DeleteInstanceProfile`](iam_example_iam_DeleteInstanceProfile_section.md)
  + [`DeleteLoginProfile`](iam_example_iam_DeleteLoginProfile_section.md)
  + [`DeleteOpenIdConnectProvider`](iam_example_iam_DeleteOpenIdConnectProvider_section.md)
  + [`DeletePolicy`](iam_example_iam_DeletePolicy_section.md)
  + [`DeletePolicyVersion`](iam_example_iam_DeletePolicyVersion_section.md)
  + [`DeleteRole`](iam_example_iam_DeleteRole_section.md)
  + [`DeleteRolePermissionsBoundary`](iam_example_iam_DeleteRolePermissionsBoundary_section.md)
  + [`DeleteRolePolicy`](iam_example_iam_DeleteRolePolicy_section.md)
  + [`DeleteSAMLProvider`](iam_example_iam_DeleteSAMLProvider_section.md)
  + [`DeleteServerCertificate`](iam_example_iam_DeleteServerCertificate_section.md)
  + [`DeleteServiceLinkedRole`](iam_example_iam_DeleteServiceLinkedRole_section.md)
  + [`DeleteSigningCertificate`](iam_example_iam_DeleteSigningCertificate_section.md)
  + [`DeleteUser`](iam_example_iam_DeleteUser_section.md)
  + [`DeleteUserPermissionsBoundary`](iam_example_iam_DeleteUserPermissionsBoundary_section.md)
  + [`DeleteUserPolicy`](iam_example_iam_DeleteUserPolicy_section.md)
  + [`DeleteVirtualMfaDevice`](iam_example_iam_DeleteVirtualMfaDevice_section.md)
  + [`DetachGroupPolicy`](iam_example_iam_DetachGroupPolicy_section.md)
  + [`DetachRolePolicy`](iam_example_iam_DetachRolePolicy_section.md)
  + [`DetachUserPolicy`](iam_example_iam_DetachUserPolicy_section.md)
  + [`EnableMfaDevice`](iam_example_iam_EnableMfaDevice_section.md)
  + [`GenerateCredentialReport`](iam_example_iam_GenerateCredentialReport_section.md)
  + [`GenerateServiceLastAccessedDetails`](iam_example_iam_GenerateServiceLastAccessedDetails_section.md)
  + [`GetAccessKeyLastUsed`](iam_example_iam_GetAccessKeyLastUsed_section.md)
  + [`GetAccountAuthorizationDetails`](iam_example_iam_GetAccountAuthorizationDetails_section.md)
  + [`GetAccountPasswordPolicy`](iam_example_iam_GetAccountPasswordPolicy_section.md)
  + [`GetAccountSummary`](iam_example_iam_GetAccountSummary_section.md)
  + [`GetContextKeysForCustomPolicy`](iam_example_iam_GetContextKeysForCustomPolicy_section.md)
  + [`GetContextKeysForPrincipalPolicy`](iam_example_iam_GetContextKeysForPrincipalPolicy_section.md)
  + [`GetCredentialReport`](iam_example_iam_GetCredentialReport_section.md)
  + [`GetGroup`](iam_example_iam_GetGroup_section.md)
  + [`GetGroupPolicy`](iam_example_iam_GetGroupPolicy_section.md)
  + [`GetInstanceProfile`](iam_example_iam_GetInstanceProfile_section.md)
  + [`GetLoginProfile`](iam_example_iam_GetLoginProfile_section.md)
  + [`GetOpenIdConnectProvider`](iam_example_iam_GetOpenIdConnectProvider_section.md)
  + [`GetPolicy`](iam_example_iam_GetPolicy_section.md)
  + [`GetPolicyVersion`](iam_example_iam_GetPolicyVersion_section.md)
  + [`GetRole`](iam_example_iam_GetRole_section.md)
  + [`GetRolePolicy`](iam_example_iam_GetRolePolicy_section.md)
  + [`GetSamlProvider`](iam_example_iam_GetSamlProvider_section.md)
  + [`GetServerCertificate`](iam_example_iam_GetServerCertificate_section.md)
  + [`GetServiceLastAccessedDetails`](iam_example_iam_GetServiceLastAccessedDetails_section.md)
  + [`GetServiceLastAccessedDetailsWithEntities`](iam_example_iam_GetServiceLastAccessedDetailsWithEntities_section.md)
  + [`GetServiceLinkedRoleDeletionStatus`](iam_example_iam_GetServiceLinkedRoleDeletionStatus_section.md)
  + [`GetUser`](iam_example_iam_GetUser_section.md)
  + [`GetUserPolicy`](iam_example_iam_GetUserPolicy_section.md)
  + [`ListAccessKeys`](iam_example_iam_ListAccessKeys_section.md)
  + [`ListAccountAliases`](iam_example_iam_ListAccountAliases_section.md)
  + [`ListAttachedGroupPolicies`](iam_example_iam_ListAttachedGroupPolicies_section.md)
  + [`ListAttachedRolePolicies`](iam_example_iam_ListAttachedRolePolicies_section.md)
  + [`ListAttachedUserPolicies`](iam_example_iam_ListAttachedUserPolicies_section.md)
  + [`ListEntitiesForPolicy`](iam_example_iam_ListEntitiesForPolicy_section.md)
  + [`ListGroupPolicies`](iam_example_iam_ListGroupPolicies_section.md)
  + [`ListGroups`](iam_example_iam_ListGroups_section.md)
  + [`ListGroupsForUser`](iam_example_iam_ListGroupsForUser_section.md)
  + [`ListInstanceProfiles`](iam_example_iam_ListInstanceProfiles_section.md)
  + [`ListInstanceProfilesForRole`](iam_example_iam_ListInstanceProfilesForRole_section.md)
  + [`ListMfaDevices`](iam_example_iam_ListMfaDevices_section.md)
  + [`ListOpenIdConnectProviders`](iam_example_iam_ListOpenIdConnectProviders_section.md)
  + [`ListPolicies`](iam_example_iam_ListPolicies_section.md)
  + [`ListPolicyVersions`](iam_example_iam_ListPolicyVersions_section.md)
  + [`ListRolePolicies`](iam_example_iam_ListRolePolicies_section.md)
  + [`ListRoleTags`](iam_example_iam_ListRoleTags_section.md)
  + [`ListRoles`](iam_example_iam_ListRoles_section.md)
  + [`ListSAMLProviders`](iam_example_iam_ListSAMLProviders_section.md)
  + [`ListServerCertificates`](iam_example_iam_ListServerCertificates_section.md)
  + [`ListSigningCertificates`](iam_example_iam_ListSigningCertificates_section.md)
  + [`ListUserPolicies`](iam_example_iam_ListUserPolicies_section.md)
  + [`ListUserTags`](iam_example_iam_ListUserTags_section.md)
  + [`ListUsers`](iam_example_iam_ListUsers_section.md)
  + [`ListVirtualMfaDevices`](iam_example_iam_ListVirtualMfaDevices_section.md)
  + [`PutGroupPolicy`](iam_example_iam_PutGroupPolicy_section.md)
  + [`PutRolePermissionsBoundary`](iam_example_iam_PutRolePermissionsBoundary_section.md)
  + [`PutRolePolicy`](iam_example_iam_PutRolePolicy_section.md)
  + [`PutUserPermissionsBoundary`](iam_example_iam_PutUserPermissionsBoundary_section.md)
  + [`PutUserPolicy`](iam_example_iam_PutUserPolicy_section.md)
  + [`RemoveClientIdFromOpenIdConnectProvider`](iam_example_iam_RemoveClientIdFromOpenIdConnectProvider_section.md)
  + [`RemoveRoleFromInstanceProfile`](iam_example_iam_RemoveRoleFromInstanceProfile_section.md)
  + [`RemoveUserFromGroup`](iam_example_iam_RemoveUserFromGroup_section.md)
  + [`ResyncMfaDevice`](iam_example_iam_ResyncMfaDevice_section.md)
  + [`SetDefaultPolicyVersion`](iam_example_iam_SetDefaultPolicyVersion_section.md)
  + [`TagRole`](iam_example_iam_TagRole_section.md)
  + [`TagUser`](iam_example_iam_TagUser_section.md)
  + [`UntagRole`](iam_example_iam_UntagRole_section.md)
  + [`UntagUser`](iam_example_iam_UntagUser_section.md)
  + [`UpdateAccessKey`](iam_example_iam_UpdateAccessKey_section.md)
  + [`UpdateAccountPasswordPolicy`](iam_example_iam_UpdateAccountPasswordPolicy_section.md)
  + [`UpdateAssumeRolePolicy`](iam_example_iam_UpdateAssumeRolePolicy_section.md)
  + [`UpdateGroup`](iam_example_iam_UpdateGroup_section.md)
  + [`UpdateLoginProfile`](iam_example_iam_UpdateLoginProfile_section.md)
  + [`UpdateOpenIdConnectProviderThumbprint`](iam_example_iam_UpdateOpenIdConnectProviderThumbprint_section.md)
  + [`UpdateRole`](iam_example_iam_UpdateRole_section.md)
  + [`UpdateRoleDescription`](iam_example_iam_UpdateRoleDescription_section.md)
  + [`UpdateSamlProvider`](iam_example_iam_UpdateSamlProvider_section.md)
  + [`UpdateServerCertificate`](iam_example_iam_UpdateServerCertificate_section.md)
  + [`UpdateSigningCertificate`](iam_example_iam_UpdateSigningCertificate_section.md)
  + [`UpdateUser`](iam_example_iam_UpdateUser_section.md)
  + [`UploadServerCertificate`](iam_example_iam_UploadServerCertificate_section.md)
  + [`UploadSigningCertificate`](iam_example_iam_UploadSigningCertificate_section.md)

# Hello IAM
<a name="iam_example_iam_Hello_section"></a>

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

------
#### [ .NET ]

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

```
namespace IAMActions;

public class HelloIAM
{
    static async Task Main(string[] args)
    {
        // Getting started with AWS Identity and Access Management (IAM). List
        // the policies for the account.
        var iamClient = new AmazonIdentityManagementServiceClient();

        var listPoliciesPaginator = iamClient.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        Console.WriteLine("Here are the policies defined for your account:\n");
        policies.ForEach(policy =>
        {
            Console.WriteLine($"Created: {policy.CreateDate}\t{policy.PolicyName}\t{policy.Description}");
        });
    }
}
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListPolicies)를 참조하십시오.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam/hello_iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
CMakeLists.txt CMake 파일의 코드입니다.  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS iam)

# Set this project's name.
project("hello_iam")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
    # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

    # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this
    # and set the proper subdirectory to the executables' location.

    AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_iam.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
iam.cpp 소스 파일의 코드입니다.  

```
#include <aws/core/Aws.h>
#include <aws/iam/IAMClient.h>
#include <aws/iam/model/ListPoliciesRequest.h>
#include <iostream>
#include <iomanip>

/*
 *  A "Hello IAM" starter application which initializes an AWS Identity and Access Management (IAM) client
 *  and lists the IAM policies.
 *
 *  main function
 *
 *  Usage: 'hello_iam'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        const Aws::String DATE_FORMAT("%Y-%m-%d");
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::IAM::IAMClient iamClient(clientConfig);
        Aws::IAM::Model::ListPoliciesRequest request;

        bool done = false;
        bool header = false;
        while (!done) {
            auto outcome = iamClient.ListPolicies(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Failed to list iam policies: " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = 1;
                break;
            }

            if (!header) {
                std::cout << std::left << std::setw(55) << "Name" <<
                          std::setw(30) << "ID" << std::setw(80) << "Arn" <<
                          std::setw(64) << "Description" << std::setw(12) <<
                          "CreateDate" << std::endl;
                header = true;
            }

            const auto &policies = outcome.GetResult().GetPolicies();
            for (const auto &policy: policies) {
                std::cout << std::left << std::setw(55) <<
                          policy.GetPolicyName() << std::setw(30) <<
                          policy.GetPolicyId() << std::setw(80) << policy.GetArn() <<
                          std::setw(64) << policy.GetDescription() << std::setw(12) <<
                          policy.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) <<
                          std::endl;
            }

            if (outcome.GetResult().GetIsTruncated()) {
                request.SetMarker(outcome.GetResult().GetMarker());
            } else {
                done = true;
            }
        }
    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListPolicies)를 참조하십시오.

------
#### [ Go ]

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

```
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/iam"
)

// main uses the AWS SDK for Go (v2) to create an AWS Identity and Access Management (IAM)
// client and list up to 10 policies in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	iamClient := iam.NewFromConfig(sdkConfig)
	const maxPols = 10
	fmt.Printf("Let's list up to %v policies for your account.\n", maxPols)
	result, err := iamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPols),
	})
	if err != nil {
		fmt.Printf("Couldn't list policies for your account. Here's why: %v\n", err)
		return
	}
	if len(result.Policies) == 0 {
		fmt.Println("You don't have any policies!")
	} else {
		for _, policy := range result.Policies {
			fmt.Printf("\t%v\n", *policy.PolicyName)
		}
	}
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListPolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListPolicies)를 참조하세요.

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

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

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.ListPoliciesResponse;
import software.amazon.awssdk.services.iam.model.Policy;
import java.util.List;

/**
 * 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 HelloIAM {
    public static void main(String[] args) {
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listPolicies(iam);
    }

    public static void listPolicies(IamClient iam) {
        ListPoliciesResponse response = iam.listPolicies();
        List<Policy> polList = response.policies();
        polList.forEach(policy -> {
            System.out.println("Policy Name: " + policy.policyName());
        });
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListPolicies)를 참조하십시오.

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

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

```
import { IAMClient, paginateListPolicies } from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const listLocalPolicies = async () => {
  /**
   * In v3, the clients expose paginateOperationName APIs that are written using async generators so that you can use async iterators in a for await..of loop.
   * https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators
   */
  const paginator = paginateListPolicies(
    { client, pageSize: 10 },
    // List only customer managed policies.
    { Scope: "Local" },
  );

  console.log("IAM policies defined in your account:");
  let policyCount = 0;
  for await (const page of paginator) {
    if (page.Policies) {
      for (const policy of page.Policies) {
        console.log(`${policy.PolicyName}`);
        policyCount++;
      }
    }
  }
  console.log(`Found ${policyCount} policies.`);
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListPolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListPoliciesCommand)를 참조하십시오.

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

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

```
import boto3


def main():
    """
    Lists the managed policies in your AWS account using the AWS SDK for Python (Boto3).
    """
    iam = boto3.client("iam")

    try:
        # Get a paginator for the list_policies operation
        paginator = iam.get_paginator("list_policies")

        # Iterate through the pages of results
        for page in paginator.paginate(Scope="All", OnlyAttached=False):
            for policy in page["Policies"]:
                print(f"Policy name: {policy['PolicyName']}")
                print(f"  Policy ARN: {policy['Arn']}")
    except boto3.exceptions.BotoCoreError as e:
        print(f"Encountered an error while listing policies: {e}")


if __name__ == "__main__":
    main()
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListPolicies)를 참조하십시오.

------
#### [ Ruby ]

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

```
require 'aws-sdk-iam'
require 'logger'

# IAMManager is a class responsible for managing IAM operations
# such as listing all IAM policies in the current AWS account.
class IAMManager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all IAM policies in the current AWS account.
  def list_policies
    @logger.info('Here are the IAM policies in your account:')

    paginator = @client.list_policies
    policies = []

    paginator.each_page do |page|
      policies.concat(page.policies)
    end

    if policies.empty?
      @logger.info("You don't have any IAM policies.")
    else
      policies.each do |policy|
        @logger.info("- #{policy.policy_name}")
      end
    end
  end
end

if $PROGRAM_NAME == __FILE__
  iam_client = Aws::IAM::Client.new
  manager = IAMManager.new(iam_client)
  manager.list_policies
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListPolicies)를 참조하십시오.

------
#### [ Rust ]

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

```
use aws_sdk_iam::error::SdkError;
use aws_sdk_iam::operation::list_policies::ListPoliciesError;
use clap::Parser;

const PATH_PREFIX_HELP: &str = "The path prefix for filtering the results.";

#[derive(Debug, clap::Parser)]
#[command(about)]
struct HelloScenarioArgs {
    #[arg(long, default_value="/", help=PATH_PREFIX_HELP)]
    pub path_prefix: String,
}

#[tokio::main]
async fn main() -> Result<(), SdkError<ListPoliciesError>> {
    let sdk_config = aws_config::load_from_env().await;
    let client = aws_sdk_iam::Client::new(&sdk_config);

    let args = HelloScenarioArgs::parse();

    iam_service::list_policies(client, args.path_prefix).await?;

    Ok(())
}
```
src/iam-service-lib.rs에서  

```
pub async fn list_policies(
    client: iamClient,
    path_prefix: String,
) -> Result<Vec<String>, SdkError<ListPoliciesError>> {
    let list_policies = client
        .list_policies()
        .path_prefix(path_prefix)
        .scope(PolicyScopeType::Local)
        .into_paginator()
        .items()
        .send()
        .try_collect()
        .await?;

    let policy_names = list_policies
        .into_iter()
        .map(|p| {
            let name = p
                .policy_name
                .unwrap_or_else(|| "Missing Policy Name".to_string());
            println!("{}", name);
            name
        })
        .collect();

    Ok(policy_names)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListPolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_policies)을 참조하세요.

------

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

다음 코드 예제에서는 사용자를 생성하고 역할을 수임하는 방법을 보여줍니다.

**주의**  
보안 위험을 방지하려면 목적별 소프트웨어를 개발하거나 실제 데이터로 작업할 때 IAM 사용자를 인증에 사용하지 마세요. 대신 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)과 같은 보안 인증 공급자를 통한 페더레이션을 사용하십시오.
+ 권한이 없는 사용자를 생성합니다.
+ 계정에 대한 Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 역할을 생성합니다.
+ 사용자가 역할을 수임할 수 있도록 정책을 추가합니다.
+ 역할을 수임하고 임시 자격 증명 정보를 사용하여 S3 버킷을 나열한 후 리소스를 정리합니다.

------
#### [ .NET ]

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

```
global using Amazon.IdentityManagement;
global using Amazon.S3;
global using Amazon.SecurityToken;
global using IAMActions;
global using IamScenariosCommon;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;


namespace IAMActions;

public class IAMWrapper
{
    private readonly IAmazonIdentityManagementService _IAMService;

    /// <summary>
    /// Constructor for the IAMWrapper class.
    /// </summary>
    /// <param name="IAMService">An IAM client object.</param>
    public IAMWrapper(IAmazonIdentityManagementService IAMService)
    {
        _IAMService = IAMService;
    }

    /// <summary>
    /// Attach an IAM policy to a role.
    /// </summary>
    /// <param name="policyArn">The policy to attach.</param>
    /// <param name="roleName">The role that the policy will be attached to.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AttachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.AttachRolePolicyAsync(new AttachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Create an IAM access key for a user.
    /// </summary>
    /// <param name="userName">The username for which to create the IAM access
    /// key.</param>
    /// <returns>The AccessKey.</returns>
    public async Task<AccessKey> CreateAccessKeyAsync(string userName)
    {
        var response = await _IAMService.CreateAccessKeyAsync(new CreateAccessKeyRequest
        {
            UserName = userName,
        });

        return response.AccessKey;

    }


    /// <summary>
    /// Create an IAM policy.
    /// </summary>
    /// <param name="policyName">The name to give the new IAM policy.</param>
    /// <param name="policyDocument">The policy document for the new policy.</param>
    /// <returns>The new IAM policy object.</returns>
    public async Task<ManagedPolicy> CreatePolicyAsync(string policyName, string policyDocument)
    {
        var response = await _IAMService.CreatePolicyAsync(new CreatePolicyRequest
        {
            PolicyDocument = policyDocument,
            PolicyName = policyName,
        });

        return response.Policy;
    }


    /// <summary>
    /// Create a new IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="rolePolicyDocument">The name of the IAM policy document
    /// for the new role.</param>
    /// <returns>The Amazon Resource Name (ARN) of the role.</returns>
    public async Task<string> CreateRoleAsync(string roleName, string rolePolicyDocument)
    {
        var request = new CreateRoleRequest
        {
            RoleName = roleName,
            AssumeRolePolicyDocument = rolePolicyDocument,
        };

        var response = await _IAMService.CreateRoleAsync(request);
        return response.Role.Arn;
    }


    /// <summary>
    /// Create an IAM service-linked role.
    /// </summary>
    /// <param name="serviceName">The name of the AWS Service.</param>
    /// <param name="description">A description of the IAM service-linked role.</param>
    /// <returns>The IAM role that was created.</returns>
    public async Task<Role> CreateServiceLinkedRoleAsync(string serviceName, string description)
    {
        var request = new CreateServiceLinkedRoleRequest
        {
            AWSServiceName = serviceName,
            Description = description
        };

        var response = await _IAMService.CreateServiceLinkedRoleAsync(request);
        return response.Role;
    }


    /// <summary>
    /// Create an IAM user.
    /// </summary>
    /// <param name="userName">The username for the new IAM user.</param>
    /// <returns>The IAM user that was created.</returns>
    public async Task<User> CreateUserAsync(string userName)
    {
        var response = await _IAMService.CreateUserAsync(new CreateUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// Delete an IAM user's access key.
    /// </summary>
    /// <param name="accessKeyId">The Id for the IAM access key.</param>
    /// <param name="userName">The username of the user that owns the IAM
    /// access key.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAccessKeyAsync(string accessKeyId, string userName)
    {
        var response = await _IAMService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest
        {
            AccessKeyId = accessKeyId,
            UserName = userName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM policy.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the policy to
    /// delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeletePolicyAsync(string policyArn)
    {
        var response = await _IAMService.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRoleAsync(string roleName)
    {
        var response = await _IAMService.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role policy.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="policyName">The name of the IAM role policy to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRolePolicyAsync(string roleName, string policyName)
    {
        var response = await _IAMService.DeleteRolePolicyAsync(new DeleteRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user.
    /// </summary>
    /// <param name="userName">The username of the IAM user to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserAsync(string userName)
    {
        var response = await _IAMService.DeleteUserAsync(new DeleteUserRequest { UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user policy.
    /// </summary>
    /// <param name="policyName">The name of the IAM policy to delete.</param>
    /// <param name="userName">The username of the IAM user.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserPolicyAsync(string policyName, string userName)
    {
        var response = await _IAMService.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policyName, UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Detach an IAM policy from an IAM role.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DetachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.DetachRolePolicyAsync(new DetachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Gets the IAM password policy for an AWS account.
    /// </summary>
    /// <returns>The PasswordPolicy for the AWS account.</returns>
    public async Task<PasswordPolicy> GetAccountPasswordPolicyAsync()
    {
        var response = await _IAMService.GetAccountPasswordPolicyAsync(new GetAccountPasswordPolicyRequest());
        return response.PasswordPolicy;
    }


    /// <summary>
    /// Get information about an IAM policy.
    /// </summary>
    /// <param name="policyArn">The IAM policy to retrieve information for.</param>
    /// <returns>The IAM policy.</returns>
    public async Task<ManagedPolicy> GetPolicyAsync(string policyArn)
    {

        var response = await _IAMService.GetPolicyAsync(new GetPolicyRequest { PolicyArn = policyArn });
        return response.Policy;
    }


    /// <summary>
    /// Get information about an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to retrieve information
    /// for.</param>
    /// <returns>The IAM role that was retrieved.</returns>
    public async Task<Role> GetRoleAsync(string roleName)
    {
        var response = await _IAMService.GetRoleAsync(new GetRoleRequest
        {
            RoleName = roleName,
        });

        return response.Role;
    }


    /// <summary>
    /// Get information about an IAM user.
    /// </summary>
    /// <param name="userName">The username of the user.</param>
    /// <returns>An IAM user object.</returns>
    public async Task<User> GetUserAsync(string userName)
    {
        var response = await _IAMService.GetUserAsync(new GetUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// List the IAM role policies that are attached to an IAM role.
    /// </summary>
    /// <param name="roleName">The IAM role to list IAM policies for.</param>
    /// <returns>A list of the IAM policies attached to the IAM role.</returns>
    public async Task<List<AttachedPolicyType>> ListAttachedRolePoliciesAsync(string roleName)
    {
        var attachedPolicies = new List<AttachedPolicyType>();
        var attachedRolePoliciesPaginator = _IAMService.Paginators.ListAttachedRolePolicies(new ListAttachedRolePoliciesRequest { RoleName = roleName });

        await foreach (var response in attachedRolePoliciesPaginator.Responses)
        {
            attachedPolicies.AddRange(response.AttachedPolicies);
        }

        return attachedPolicies;
    }


    /// <summary>
    /// List IAM groups.
    /// </summary>
    /// <returns>A list of IAM groups.</returns>
    public async Task<List<Group>> ListGroupsAsync()
    {
        var groupsPaginator = _IAMService.Paginators.ListGroups(new ListGroupsRequest());
        var groups = new List<Group>();

        await foreach (var response in groupsPaginator.Responses)
        {
            groups.AddRange(response.Groups);
        }

        return groups;
    }


    /// <summary>
    /// List IAM policies.
    /// </summary>
    /// <returns>A list of the IAM policies.</returns>
    public async Task<List<ManagedPolicy>> ListPoliciesAsync()
    {
        var listPoliciesPaginator = _IAMService.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        return policies;
    }


    /// <summary>
    /// List IAM role policies.
    /// </summary>
    /// <param name="roleName">The IAM role for which to list IAM policies.</param>
    /// <returns>A list of IAM policy names.</returns>
    public async Task<List<string>> ListRolePoliciesAsync(string roleName)
    {
        var listRolePoliciesPaginator = _IAMService.Paginators.ListRolePolicies(new ListRolePoliciesRequest { RoleName = roleName });
        var policyNames = new List<string>();

        await foreach (var response in listRolePoliciesPaginator.Responses)
        {
            policyNames.AddRange(response.PolicyNames);
        }

        return policyNames;
    }


    /// <summary>
    /// List IAM roles.
    /// </summary>
    /// <returns>A list of IAM roles.</returns>
    public async Task<List<Role>> ListRolesAsync()
    {
        var listRolesPaginator = _IAMService.Paginators.ListRoles(new ListRolesRequest());
        var roles = new List<Role>();

        await foreach (var response in listRolesPaginator.Responses)
        {
            roles.AddRange(response.Roles);
        }

        return roles;
    }


    /// <summary>
    /// List SAML authentication providers.
    /// </summary>
    /// <returns>A list of SAML providers.</returns>
    public async Task<List<SAMLProviderListEntry>> ListSAMLProvidersAsync()
    {
        var response = await _IAMService.ListSAMLProvidersAsync(new ListSAMLProvidersRequest());
        return response.SAMLProviderList;
    }


    /// <summary>
    /// List IAM users.
    /// </summary>
    /// <returns>A list of IAM users.</returns>
    public async Task<List<User>> ListUsersAsync()
    {
        var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest());
        var users = new List<User>();

        await foreach (var response in listUsersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }


    /// <summary>
    /// Update the inline policy document embedded in a role.
    /// </summary>
    /// <param name="policyName">The name of the policy to embed.</param>
    /// <param name="roleName">The name of the role to update.</param>
    /// <param name="policyDocument">The policy document that defines the role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutRolePolicyAsync(string policyName, string roleName, string policyDocument)
    {
        var request = new PutRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutRolePolicyAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Add or update an inline policy document that is embedded in an IAM user.
    /// </summary>
    /// <param name="userName">The name of the IAM user.</param>
    /// <param name="policyName">The name of the IAM policy.</param>
    /// <param name="policyDocument">The policy document defining the IAM policy.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutUserPolicyAsync(string userName, string policyName, string policyDocument)
    {
        var request = new PutUserPolicyRequest
        {
            UserName = userName,
            PolicyName = policyName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutUserPolicyAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    /// <summary>
    /// Wait for a new access key to be ready to use.
    /// </summary>
    /// <param name="accessKeyId">The Id of the access key.</param>
    /// <returns>A boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitUntilAccessKeyIsReady(string accessKeyId)
    {
        var keyReady = false;

        do
        {
            try
            {
                var response = await _IAMService.GetAccessKeyLastUsedAsync(
                    new GetAccessKeyLastUsedRequest { AccessKeyId = accessKeyId });
                if (response.UserName is not null)
                {
                    keyReady = true;
                }
            }
            catch (NoSuchEntityException)
            {
                keyReady = false;
            }
        } while (!keyReady);

        return keyReady;
    }
}



using Microsoft.Extensions.Configuration;

namespace IAMBasics;

public class IAMBasics
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the AWS service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonIdentityManagementService>()
            .AddTransient<IAMWrapper>()
            .AddTransient<UIWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<IAMBasics>();


        IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        // Values needed for user, role, and policies.
        string userName = configuration["UserName"]!;
        string s3PolicyName = configuration["S3PolicyName"]!;
        string roleName = configuration["RoleName"]!;


        var iamWrapper = host.Services.GetRequiredService<IAMWrapper>();
        var uiWrapper = host.Services.GetRequiredService<UIWrapper>();

        uiWrapper.DisplayBasicsOverview();
        uiWrapper.PressEnter();

        // First create a user. By default, the new user has
        // no permissions.
        uiWrapper.DisplayTitle("Create User");
        Console.WriteLine($"Creating a new user with user name: {userName}.");
        var user = await iamWrapper.CreateUserAsync(userName);
        var userArn = user.Arn;

        Console.WriteLine($"Successfully created user: {userName} with ARN: {userArn}.");
        uiWrapper.WaitABit(15, "Now let's wait for the user to be ready for use.");

        // Define a role policy document that allows the new user
        // to assume the role.
        string assumeRolePolicyDocument = "{" +
          "\"Version\": \"2012-10-17\"," +
          "\"Statement\": [{" +
              "\"Effect\": \"Allow\"," +
              "\"Principal\": {" +
              $"	\"AWS\": \"{userArn}\"" +
              "}," +
              "\"Action\": \"sts:AssumeRole\"" +
          "}]" +
        "}";

        // Permissions to list all buckets.
        string policyDocument = "{" +
            "\"Version\": \"2012-10-17\"," +
            "	\"Statement\" : [{" +
                "	\"Action\" : [\"s3:ListAllMyBuckets\"]," +
                "	\"Effect\" : \"Allow\"," +
                "	\"Resource\" : \"*\"" +
            "}]" +
        "}";

        // Create an AccessKey for the user.
        uiWrapper.DisplayTitle("Create access key");
        Console.WriteLine("Now let's create an access key for the new user.");
        var accessKey = await iamWrapper.CreateAccessKeyAsync(userName);

        var accessKeyId = accessKey.AccessKeyId;
        var secretAccessKey = accessKey.SecretAccessKey;

        Console.WriteLine($"We have created the access key with Access key id: {accessKeyId}.");

        Console.WriteLine("Now let's wait until the IAM access key is ready to use.");
        var keyReady = await iamWrapper.WaitUntilAccessKeyIsReady(accessKeyId);

        // Now try listing the Amazon Simple Storage Service (Amazon S3)
        // buckets. This should fail at this point because the user doesn't
        // have permissions to perform this task.
        uiWrapper.DisplayTitle("Try to display Amazon S3 buckets");
        Console.WriteLine("Now let's try to display a list of the user's Amazon S3 buckets.");
        var s3Client1 = new AmazonS3Client(accessKeyId, secretAccessKey);
        var stsClient1 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        var s3Wrapper = new S3Wrapper(s3Client1, stsClient1);
        var buckets = await s3Wrapper.ListMyBucketsAsync();

        Console.WriteLine(buckets is null
            ? "As expected, the call to list the buckets has returned a null list."
            : "Something went wrong. This shouldn't have worked.");

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Create IAM role");
        Console.WriteLine($"Creating the role: {roleName}");

        // Creating an IAM role to allow listing the S3 buckets. A role name
        // is not case sensitive and must be unique to the account for which it
        // is created.
        var roleArn = await iamWrapper.CreateRoleAsync(roleName, assumeRolePolicyDocument);

        uiWrapper.PressEnter();

        // Create a policy with permissions to list S3 buckets.
        uiWrapper.DisplayTitle("Create IAM policy");
        Console.WriteLine($"Creating the policy: {s3PolicyName}");
        Console.WriteLine("with permissions to list the Amazon S3 buckets for the account.");
        var policy = await iamWrapper.CreatePolicyAsync(s3PolicyName, policyDocument);

        // Wait 15 seconds for the IAM policy to be available.
        uiWrapper.WaitABit(15, "Waiting for the policy to be available.");

        // Attach the policy to the role you created earlier.
        uiWrapper.DisplayTitle("Attach new IAM policy");
        Console.WriteLine("Now let's attach the policy to the role.");
        await iamWrapper.AttachRolePolicyAsync(policy.Arn, roleName);

        // Wait 15 seconds for the role to be updated.
        Console.WriteLine();
        uiWrapper.WaitABit(15, "Waiting for the policy to be attached.");

        // Use the AWS Security Token Service (AWS STS) to have the user
        // assume the role we created.
        var stsClient2 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        // Wait for the new credentials to become valid.
        uiWrapper.WaitABit(10, "Waiting for the credentials to be valid.");

        var assumedRoleCredentials = await s3Wrapper.AssumeS3RoleAsync("temporary-session", roleArn);

        // Try again to list the buckets using the client created with
        // the new user's credentials. This time, it should work.
        var s3Client2 = new AmazonS3Client(assumedRoleCredentials);

        s3Wrapper.UpdateClients(s3Client2, stsClient2);

        buckets = await s3Wrapper.ListMyBucketsAsync();

        uiWrapper.DisplayTitle("List Amazon S3 buckets");
        Console.WriteLine("This time we should have buckets to list.");
        if (buckets is not null)
        {
            buckets.ForEach(bucket =>
            {
                Console.WriteLine($"{bucket.BucketName} created: {bucket.CreationDate}");
            });
        }

        uiWrapper.PressEnter();

        // Now clean up all the resources used in the example.
        uiWrapper.DisplayTitle("Clean up resources");
        Console.WriteLine("Thank you for watching. The IAM Basics demo is complete.");
        Console.WriteLine("Please wait while we clean up the resources we created.");

        await iamWrapper.DetachRolePolicyAsync(policy.Arn, roleName);

        await iamWrapper.DeletePolicyAsync(policy.Arn);

        await iamWrapper.DeleteRoleAsync(roleName);

        await iamWrapper.DeleteAccessKeyAsync(accessKeyId, userName);

        await iamWrapper.DeleteUserAsync(userName);

        uiWrapper.PressEnter();

        Console.WriteLine("All done cleaning up our resources. Thank you for your patience.");
    }
}


namespace IamScenariosCommon;

using System.Net;

/// <summary>
/// A class to perform Amazon Simple Storage Service (Amazon S3) actions for
/// the IAM Basics scenario.
/// </summary>
public class S3Wrapper
{
    private IAmazonS3 _s3Service;
    private IAmazonSecurityTokenService _stsService;

    /// <summary>
    /// Constructor for the S3Wrapper class.
    /// </summary>
    /// <param name="s3Service">An Amazon S3 client object.</param>
    /// <param name="stsService">An AWS Security Token Service (AWS STS)
    /// client object.</param>
    public S3Wrapper(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }

    /// <summary>
    /// Assumes an AWS Identity and Access Management (IAM) role that allows
    /// Amazon S3 access for the current session.
    /// </summary>
    /// <param name="roleSession">A string representing the current session.</param>
    /// <param name="roleToAssume">The name of the IAM role to assume.</param>
    /// <returns>Credentials for the newly assumed IAM role.</returns>
    public async Task<Credentials> AssumeS3RoleAsync(string roleSession, string roleToAssume)
    {
        // Create the request to use with the AssumeRoleAsync call.
        var request = new AssumeRoleRequest()
        {
            RoleSessionName = roleSession,
            RoleArn = roleToAssume,
        };

        var response = await _stsService.AssumeRoleAsync(request);

        return response.Credentials;
    }


    /// <summary>
    /// Delete an S3 bucket.
    /// </summary>
    /// <param name="bucketName">Name of the S3 bucket to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteBucketAsync(string bucketName)
    {
        var result = await _s3Service.DeleteBucketAsync(new DeleteBucketRequest { BucketName = bucketName });
        return result.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// List the buckets that are owned by the user's account.
    /// </summary>
    /// <returns>Async Task.</returns>
    public async Task<List<S3Bucket>?> ListMyBucketsAsync()
    {
        try
        {
            // Get the list of buckets accessible by the new user.
            var response = await _s3Service.ListBucketsAsync();

            return response.Buckets;
        }
        catch (AmazonS3Exception ex)
        {
            // Something else went wrong. Display the error message.
            Console.WriteLine($"Error: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Create a new S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name for the new bucket.</param>
    /// <returns>A Boolean value indicating whether the action completed
    /// successfully.</returns>
    public async Task<bool> PutBucketAsync(string bucketName)
    {
        var response = await _s3Service.PutBucketAsync(new PutBucketRequest { BucketName = bucketName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Update the client objects with new client objects. This is available
    /// because the scenario uses the methods of this class without and then
    /// with the proper permissions to list S3 buckets.
    /// </summary>
    /// <param name="s3Service">The Amazon S3 client object.</param>
    /// <param name="stsService">The AWS STS client object.</param>
    public void UpdateClients(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }
}


namespace IamScenariosCommon;

public class UIWrapper
{
    public readonly string SepBar = new('-', Console.WindowWidth);

    /// <summary>
    /// Show information about the IAM Groups scenario.
    /// </summary>
    public void DisplayGroupsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to the IAM Groups Demo");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates an Amazon Identity and Access Management (IAM) group.");
        Console.WriteLine("\t2. Adds an IAM policy to the IAM group giving it full access to Amazon S3.");
        Console.WriteLine("\t3. Creates a new IAM user.");
        Console.WriteLine("\t4. Creates an IAM access key for the user.");
        Console.WriteLine("\t5. Adds the user to the IAM group.");
        Console.WriteLine("\t6. Lists the buckets on the account.");
        Console.WriteLine("\t7. Proves that the user has full Amazon S3 access by creating a bucket.");
        Console.WriteLine("\t8. List the buckets again to show the new bucket.");
        Console.WriteLine("\t9. Cleans up all the resources created.");
    }

    /// <summary>
    /// Show information about the IAM Basics scenario.
    /// </summary>
    public void DisplayBasicsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to IAM Basics");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates a user with no permissions.");
        Console.WriteLine("\t2. Creates a role and policy that grant s3:ListAllMyBuckets permission.");
        Console.WriteLine("\t3. Grants the user permission to assume the role.");
        Console.WriteLine("\t4. Creates an S3 client object as the user and tries to list buckets (this will fail).");
        Console.WriteLine("\t5. Gets temporary credentials by assuming the role.");
        Console.WriteLine("\t6. Creates a new S3 client object with the temporary credentials and lists the buckets (this will succeed).");
        Console.WriteLine("\t7. Deletes all the resources.");
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPress <Enter> to continue. ");
        _ = Console.ReadLine();
        Console.WriteLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter">The string to be centered.</param>
    /// <returns>The padded string.</returns>
    public string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title, and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(SepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(SepBar);
    }

    /// <summary>
    /// Display a countdown and wait for a number of seconds.
    /// </summary>
    /// <param name="numSeconds">The number of seconds to wait.</param>
    public void WaitABit(int numSeconds, string msg)
    {
        Console.WriteLine(msg);

        // Wait for the requested number of seconds.
        for (int i = numSeconds; i > 0; i--)
        {
            System.Threading.Thread.Sleep(1000);
            Console.Write($"{i}...");
        }

        PressEnter();
    }
}
```
+ API 세부 정보는 *AWS SDK for .NET API 참조*의 다음 주제를 참조하십시오.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function iam_create_user_assume_role
#
# Scenario to create an IAM user, create an IAM role, and apply the role to the user.
#
#     "IAM access" permissions are needed to run this code.
#     "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
#           create a custom policy).
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function iam_create_user_assume_role() {
  {
    if [ "$IAM_OPERATIONS_SOURCED" != "True" ]; then

      source ./iam_operations.sh
    fi
  }

  echo_repeat "*" 88
  echo "Welcome to the IAM create user and assume role demo."
  echo
  echo "This demo will create an IAM user, create an IAM role, and apply the role to the user."
  echo_repeat "*" 88
  echo

  echo -n "Enter a name for a new IAM user: "
  get_input
  user_name=$get_input_result

  local user_arn
  user_arn=$(iam_create_user -u "$user_name")

  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created demo IAM user named $user_name"
  else
    errecho "$user_arn"
    errecho "The user failed to create. This demo will exit."
    return 1
  fi

  local access_key_response
  access_key_response=$(iam_create_user_access_key -u "$user_name")
  # shellcheck disable=SC2181
  if [[ ${?} != 0 ]]; then
    errecho "The access key failed to create. This demo will exit."
    clean_up "$user_name"
    return 1
  fi

  IFS=$'\t ' read -r -a access_key_values <<<"$access_key_response"
  local key_name=${access_key_values[0]}
  local key_secret=${access_key_values[1]}

  echo "Created access key named $key_name"

  echo "Wait 10 seconds for the user to be ready."
  sleep 10
  echo_repeat "*" 88
  echo

  local iam_role_name
  iam_role_name=$(generate_random_name "test-role")
  echo "Creating a role named $iam_role_name with user $user_name as the principal."

  local assume_role_policy_document="{
    \"Version\": \"2012-10-17\",
    \"Statement\": [{
        \"Effect\": \"Allow\",
        \"Principal\": {\"AWS\": \"$user_arn\"},
        \"Action\": \"sts:AssumeRole\"
        }]
    }"

  local role_arn
  role_arn=$(iam_create_role -n "$iam_role_name" -p "$assume_role_policy_document")

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created IAM role named $iam_role_name"
  else
    errecho "The role failed to create. This demo will exit."
    clean_up "$user_name" "$key_name"
    return 1
  fi

  local policy_name
  policy_name=$(generate_random_name "test-policy")
  local policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]}"

  local policy_arn
  policy_arn=$(iam_create_policy -n "$policy_name" -p "$policy_document")
  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created  IAM policy named $policy_name"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name"
    return 1
  fi

  if (iam_attach_role_policy -n "$iam_role_name" -p "$policy_arn"); then
    echo "Attached policy $policy_arn to role $iam_role_name"
  else
    errecho "The policy failed to attach."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn"
    return 1
  fi

  local assume_role_policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"$role_arn\"}]}"

  local assume_role_policy_name
  assume_role_policy_name=$(generate_random_name "test-assume-role-")

  # shellcheck disable=SC2181
  local assume_role_policy_arn
  assume_role_policy_arn=$(iam_create_policy -n "$assume_role_policy_name" -p "$assume_role_policy_document")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created  IAM policy named $assume_role_policy_name for sts assume role"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn"
    return 1
  fi

  echo "Wait 10 seconds to give AWS time to propagate these new resources and connections."
  sleep 10
  echo_repeat "*" 88
  echo

  echo "Try to list buckets without the new user assuming the role."
  echo_repeat "*" 88
  echo

  # Set the environment variables for the created user.
  # bashsupport disable=BP2001
  export AWS_ACCESS_KEY_ID=$key_name
  # bashsupport disable=BP2001
  export AWS_SECRET_ACCESS_KEY=$key_secret

  local buckets
  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. This should not have happened."
  else
    errecho "Because the role with permissions has not been assumed, listing buckets failed."
  fi

  echo
  echo_repeat "*" 88
  echo "Now assume the role $iam_role_name and list the buckets."
  echo_repeat "*" 88
  echo

  local credentials

  credentials=$(sts_assume_role -r "$role_arn" -n "AssumeRoleDemoSession")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Assumed role $iam_role_name"
  else
    errecho "Failed to assume role."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  IFS=$'\t ' read -r -a credentials <<<"$credentials"

  export AWS_ACCESS_KEY_ID=${credentials[0]}
  export AWS_SECRET_ACCESS_KEY=${credentials[1]}
  # bashsupport disable=BP2001
  export AWS_SESSION_TOKEN=${credentials[2]}

  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. Listing buckets succeeded because of "
    echo "the assumed role."
  else
    errecho "Failed to list buckets. This should not happen."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    export AWS_SESSION_TOKEN=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  local result=0
  export AWS_ACCESS_KEY_ID=""
  export AWS_SECRET_ACCESS_KEY=""

  echo
  echo_repeat "*" 88
  echo "The created resources will now be deleted."
  echo_repeat "*" 88
  echo

  clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    result=1
  fi

  return $result
}
```
이 시나리오에 사용된 IAM 함수입니다.  

```
###############################################################################
# function iam_user_exists
#
# This function checks to see if the specified AWS Identity and Access Management (IAM) user already exists.
#
# Parameters:
#       $1 - The name of the IAM user to check.
#
# Returns:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_user_exists() {
  local user_name
  user_name=$1

  # Check whether the IAM user already exists.
  # We suppress all output - we're interested only in the return code.

  local errors
  errors=$(aws iam get-user \
    --user-name "$user_name" 2>&1 >/dev/null)

  local error_code=${?}

  if [[ $error_code -eq 0 ]]; then
    return 0 # 0 in Bash script means true.
  else
    if [[ $errors != *"error"*"(NoSuchEntity)"* ]]; then
      aws_cli_error_log $error_code
      errecho "Error calling iam get-user $errors"
    fi

    return 1 # 1 in Bash script means false.
  fi
}

###############################################################################
# function iam_create_user
#
# This function creates the specified IAM user, unless
# it already exists.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       The ARN of the user.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user"
    echo "Creates an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user. It must be unique within the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user already exists, we don't want to try to create it.
  if (iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name already exists in the account."
    return 1
  fi

  response=$(aws iam create-user --user-name "$user_name" \
    --output text \
    --query 'User.Arn')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-user operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_create_user_access_key
#
# This function creates an IAM access key for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#       [-f file_name] -- The optional file name for the access key output.
#
# Returns:
#       [access_key_id access_key_secret]
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user_access_key() {
  local user_name file_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) key pair."
    echo "  -u user_name   The name of the IAM user."
    echo "  [-f file_name]   Optional file name for the access key output."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:f:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      f) file_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam create-access-key \
    --user-name "$user_name" \
    --output text)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  fi

  if [[ -n "$file_name" ]]; then
    echo "$response" >"$file_name"
  fi

  local key_id key_secret
  # shellcheck disable=SC2086
  key_id=$(echo $response | cut -f 2 -d ' ')
  # shellcheck disable=SC2086
  key_secret=$(echo $response | cut -f 4 -d ' ')

  echo "$key_id $key_secret"

  return 0
}

###############################################################################
# function iam_create_role
#
# This function creates an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_json -- The assume role policy document.
#
# Returns:
#       The ARN of the role.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_role() {
  local role_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_json -- The assume role policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-role \
    --role-name "$role_name" \
    --assume-role-policy-document "$policy_document" \
    --output text \
    --query Role.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-role operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_create_policy
#
# This function creates an IAM policy.
#
# Parameters:
#       -n policy_name -- The name of the IAM policy.
#       -p policy_json -- The policy document.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_policy() {
  local policy_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_policy"
    echo "Creates an AWS Identity and Access Management (IAM) policy."
    echo "  -n policy_name   The name of the IAM policy."
    echo "  -p policy_json -- The policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) policy_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_name" ]]; then
    errecho "ERROR: You must provide a policy name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-policy \
    --policy-name "$policy_name" \
    --policy-document "$policy_document" \
    --output text \
    --query Policy.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"
}

###############################################################################
# function iam_attach_role_policy
#
# This function attaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_attach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_attach_role_policy"
    echo "Attaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam attach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports attach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_detach_role_policy
#
# This function detaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_detach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_detach_role_policy"
    echo "Detaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam detach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports detach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_delete_policy
#
# This function deletes an IAM policy.
#
# Parameters:
#       -n policy_arn -- The name of the IAM policy arn.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_policy() {
  local policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_policy"
    echo "Deletes an AWS Identity and Access Management (IAM) policy"
    echo "  -n policy_arn -- The name of the IAM policy arn."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy arn with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Policy arn:  $policy_arn"
  iecho ""

  response=$(aws iam delete-policy \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-policy operation failed.\n$response"
    return 1
  fi

  iecho "delete-policy response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_role
#
# This function deletes an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_role() {
  local role_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_role"
    echo "Deletes an AWS Identity and Access Management (IAM) role"
    echo "  -n role_name -- The name of the IAM role."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  echo "role_name:$role_name"
  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Role name:  $role_name"
  iecho ""

  response=$(aws iam delete-role \
    --role-name "$role_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-role operation failed.\n$response"
    return 1
  fi

  iecho "delete-role response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_access_key
#
# This function deletes an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to delete.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_access_key() {
  local user_name access_key response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_access_key"
    echo "Deletes an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:k:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      k) access_key="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  if [[ -z "$access_key" ]]; then
    errecho "ERROR: You must provide an access key with the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Username:   $user_name"
  iecho "    Access key:   $access_key"
  iecho ""

  response=$(aws iam delete-access-key \
    --user-name "$user_name" \
    --access-key-id "$access_key")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-access-key operation failed.\n$response"
    return 1
  fi

  iecho "delete-access-key response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_user
#
# This function deletes the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_user"
    echo "Deletes an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user does not exist, we don't want to try to delete it.
  if (! iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name does not exist in the account."
    return 1
  fi

  response=$(aws iam delete-user \
    --user-name "$user_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-user operation failed.$response"
    return 1
  fi

  iecho "delete-user response:$response"
  iecho

  return 0
}
```
+ API 세부 정보는 **AWS CLI 명령 참조의 다음 토픽을 참조하세요.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/PutUserPolicy)

------
#### [ C\$1\$1 ]

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

```
namespace AwsDoc {
    namespace IAM {
  
        //! Cleanup by deleting created entities.
        /*!
          \sa DeleteCreatedEntities
          \param client: IAM client.
          \param role: IAM role.
          \param user: IAM user.
          \param policy: IAM policy.
        */
        static bool DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                          const Aws::IAM::Model::Role &role,
                                          const Aws::IAM::Model::User &user,
                                          const Aws::IAM::Model::Policy &policy);
    }

    static const int LIST_BUCKETS_WAIT_SEC = 20;

    static const char ALLOCATION_TAG[] = "example_code";
}

//! Scenario to create an IAM user, create an IAM role, and apply the role to the user.
// "IAM access" permissions are needed to run this code.
// "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
//    create a custom policy).
/*!
  \sa iamCreateUserAssumeRoleScenario
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
*/
bool AwsDoc::IAM::iamCreateUserAssumeRoleScenario(
        const Aws::Client::ClientConfiguration &clientConfig) {

    Aws::IAM::IAMClient client(clientConfig);
    Aws::IAM::Model::User user;
    Aws::IAM::Model::Role role;
    Aws::IAM::Model::Policy policy;

    // 1. Create a user.
    {
        Aws::IAM::Model::CreateUserRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String userName = "iam-demo-user-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetUserName(userName);

        Aws::IAM::Model::CreateUserOutcome outcome = client.CreateUser(request);
        if (!outcome.IsSuccess()) {
            std::cout << "Error creating IAM user " << userName << ":" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
        else {
            std::cout << "Successfully created IAM user " << userName << std::endl;
        }

        user = outcome.GetResult().GetUser();
    }

    // 2. Create a role.
    {
        // Get the IAM user for the current client in order to access its ARN.
        Aws::String iamUserArn;
        {
            Aws::IAM::Model::GetUserRequest request;
            Aws::IAM::Model::GetUserOutcome outcome = client.GetUser(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error getting Iam user. " <<
                          outcome.GetError().GetMessage() << std::endl;

                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }
            else {
                std::cout << "Successfully retrieved Iam user "
                          << outcome.GetResult().GetUser().GetUserName()
                          << std::endl;
            }

            iamUserArn = outcome.GetResult().GetUser().GetArn();
        }

        Aws::IAM::Model::CreateRoleRequest request;

        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleName = "iam-demo-role-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleName(roleName);

        // Build policy document for role.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");

        Aws::Utils::Document jsonPrincipal;
        jsonPrincipal.WithString("AWS", iamUserArn);
        jsonStatement.WithObject("Principal", jsonPrincipal);
        jsonStatement.WithString("Action", "sts:AssumeRole");
        jsonStatement.WithObject("Condition", Aws::Utils::Document());

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Setting policy for role\n   "
                  << policyDocument.View().WriteCompact() << std::endl;

        // Set role policy document as JSON string.
        request.SetAssumeRolePolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating role. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a role with name " << roleName
                      << std::endl;
        }

        role = outcome.GetResult().GetRole();
    }

    // 3. Create an IAM policy.
    {
        Aws::IAM::Model::CreatePolicyRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String policyName = "iam-demo-policy-" +
                                 Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetPolicyName(policyName);

        // Build IAM policy document.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");
        jsonStatement.WithString("Action", "s3:ListAllMyBuckets");
        jsonStatement.WithString("Resource", "arn:aws:s3:::*");

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Creating a policy.\n   " << policyDocument.View().WriteCompact()
                  << std::endl;

        // Set IAM policy document as JSON string.
        request.SetPolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreatePolicyOutcome outcome = client.CreatePolicy(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a policy with name, " << policyName <<
                      "." << std::endl;
        }

        policy = outcome.GetResult().GetPolicy();
    }

    // 4. Assume the new role using the AWS Security Token Service (STS).
    Aws::STS::Model::Credentials credentials;
    {
        Aws::STS::STSClient stsClient(clientConfig);

        Aws::STS::Model::AssumeRoleRequest request;
        request.SetRoleArn(role.GetArn());
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleSessionName = "iam-demo-role-session-" +
                                      Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleSessionName(roleSessionName);

        Aws::STS::Model::AssumeRoleOutcome assumeRoleOutcome;

        // Repeatedly call AssumeRole, because there is often a delay
        // before the role is available to be assumed.
        // Repeat at most 20 times when access is denied.
        int count = 0;
        while (true) {
            assumeRoleOutcome = stsClient.AssumeRole(request);
            if (!assumeRoleOutcome.IsSuccess()) {
                if (count > 20 ||
                    assumeRoleOutcome.GetError().GetErrorType() !=
                    Aws::STS::STSErrors::ACCESS_DENIED) {
                    std::cerr << "Error assuming role after 20 tries. " <<
                              assumeRoleOutcome.GetError().GetMessage() << std::endl;

                    DeleteCreatedEntities(client, role, user, policy);
                    return false;
                }
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                std::cout << "Successfully assumed the role after " << count
                          << " seconds." << std::endl;
                break;
            }
            count++;
        }

        credentials = assumeRoleOutcome.GetResult().GetCredentials();
    }


    // 5. List objects in the bucket (This should fail).
    {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if (listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
            }
            else {
                std::cout
                        << "Access to list buckets denied because privileges have not been applied."
                        << std::endl;
            }
        }
        else {
            std::cerr
                    << "Successfully retrieved bucket lists when this should not happen."
                    << std::endl;
        }
    }

    // 6. Attach the policy to the role.
    {
        Aws::IAM::Model::AttachRolePolicyRequest request;
        request.SetRoleName(role.GetRoleName());
        request.WithPolicyArn(policy.GetArn());

        Aws::IAM::Model::AttachRolePolicyOutcome outcome = client.AttachRolePolicy(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully attached the policy with name, "
                      << policy.GetPolicyName() <<
                      ", to the role, " << role.GetRoleName() << "." << std::endl;
        }
    }

    int count = 0;
    // 7. List objects in the bucket (this should succeed).
    // Repeatedly call ListBuckets, because there is often a delay
    // before the policy with ListBucket permissions has been applied to the role.
    // Repeat at most LIST_BUCKETS_WAIT_SEC times when access is denied.
    while (true) {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if ((count > LIST_BUCKETS_WAIT_SEC) ||
                listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets after " << LIST_BUCKETS_WAIT_SEC << " seconds. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }

            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        else {

            std::cout << "Successfully retrieved bucket lists after " << count
                      << " seconds." << std::endl;
            break;
        }
        count++;
    }

    // 8. Delete all the created resources.
    return DeleteCreatedEntities(client, role, user, policy);
}

bool AwsDoc::IAM::DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                        const Aws::IAM::Model::Role &role,
                                        const Aws::IAM::Model::User &user,
                                        const Aws::IAM::Model::Policy &policy) {
    bool result = true;
    if (policy.ArnHasBeenSet()) {
        // Detach the policy from the role.
        {
            Aws::IAM::Model::DetachRolePolicyRequest request;
            request.SetPolicyArn(policy.GetArn());
            request.SetRoleName(role.GetRoleName());

            Aws::IAM::Model::DetachRolePolicyOutcome outcome = client.DetachRolePolicy(
                    request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error Detaching policy from roles. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully detached the policy with arn "
                          << policy.GetArn()
                          << " from role " << role.GetRoleName() << "." << std::endl;
            }
        }

        // Delete the policy.
        {
            Aws::IAM::Model::DeletePolicyRequest request;
            request.WithPolicyArn(policy.GetArn());

            Aws::IAM::Model::DeletePolicyOutcome outcome = client.DeletePolicy(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error deleting policy. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully deleted the policy with arn "
                          << policy.GetArn() << std::endl;
            }
        }

    }

    if (role.RoleIdHasBeenSet()) {
        // Delete the role.
        Aws::IAM::Model::DeleteRoleRequest request;
        request.SetRoleName(role.GetRoleName());

        Aws::IAM::Model::DeleteRoleOutcome outcome = client.DeleteRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting role. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the role with name "
                      << role.GetRoleName() << std::endl;
        }
    }

    if (user.ArnHasBeenSet()) {
        // Delete the user.
        Aws::IAM::Model::DeleteUserRequest request;
        request.WithUserName(user.GetUserName());

        Aws::IAM::Model::DeleteUserOutcome outcome = client.DeleteUser(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting user. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the user with name "
                      << user.GetUserName() << std::endl;
        }
    }

    return result;
}
```
+ API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 다음 주제를 참조하십시오.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/PutUserPolicy)

------
#### [ Go ]

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

```
import (
	"context"
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/sts"
	"github.com/aws/smithy-go"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/iam/actions"
)

// AssumeRoleScenario shows you how to use the AWS Identity and Access Management (IAM)
// service to perform the following actions:
//
//  1. Create a user who has no permissions.
//  2. Create a role that grants permission to list Amazon Simple Storage Service
//     (Amazon S3) buckets for the account.
//  3. Add a policy to let the user assume the role.
//  4. Try and fail to list buckets without permissions.
//  5. Assume the role and list S3 buckets using temporary credentials.
//  6. Delete the policy, role, and user.
type AssumeRoleScenario struct {
	sdkConfig      aws.Config
	accountWrapper actions.AccountWrapper
	policyWrapper  actions.PolicyWrapper
	roleWrapper    actions.RoleWrapper
	userWrapper    actions.UserWrapper
	questioner     demotools.IQuestioner
	helper         IScenarioHelper
	isTestRun      bool
}

// NewAssumeRoleScenario constructs an AssumeRoleScenario instance from a configuration.
// It uses the specified config to get an IAM client and create wrappers for the actions
// used in the scenario.
func NewAssumeRoleScenario(sdkConfig aws.Config, questioner demotools.IQuestioner,
	helper IScenarioHelper) AssumeRoleScenario {
	iamClient := iam.NewFromConfig(sdkConfig)
	return AssumeRoleScenario{
		sdkConfig:      sdkConfig,
		accountWrapper: actions.AccountWrapper{IamClient: iamClient},
		policyWrapper:  actions.PolicyWrapper{IamClient: iamClient},
		roleWrapper:    actions.RoleWrapper{IamClient: iamClient},
		userWrapper:    actions.UserWrapper{IamClient: iamClient},
		questioner:     questioner,
		helper:         helper,
	}
}

// addTestOptions appends the API options specified in the original configuration to
// another configuration. This is used to attach the middleware stubber to clients
// that are constructed during the scenario, which is needed for unit testing.
func (scenario AssumeRoleScenario) addTestOptions(scenarioConfig *aws.Config) {
	if scenario.isTestRun {
		scenarioConfig.APIOptions = append(scenarioConfig.APIOptions, scenario.sdkConfig.APIOptions...)
	}
}

// Run runs the interactive scenario.
func (scenario AssumeRoleScenario) Run(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong with the demo.\n")
			log.Println(r)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the AWS Identity and Access Management (IAM) assume role demo.")
	log.Println(strings.Repeat("-", 88))

	user := scenario.CreateUser(ctx)
	accessKey := scenario.CreateAccessKey(ctx, user)
	role := scenario.CreateRoleAndPolicies(ctx, user)
	noPermsConfig := scenario.ListBucketsWithoutPermissions(ctx, accessKey)
	scenario.ListBucketsWithAssumedRole(ctx, noPermsConfig, role)
	scenario.Cleanup(ctx, user, role)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}

// CreateUser creates a new IAM user. This user has no permissions.
func (scenario AssumeRoleScenario) CreateUser(ctx context.Context) *types.User {
	log.Println("Let's create an example user with no permissions.")
	userName := scenario.questioner.Ask("Enter a name for the example user:", demotools.NotEmpty{})
	user, err := scenario.userWrapper.GetUser(ctx, userName)
	if err != nil {
		panic(err)
	}
	if user == nil {
		user, err = scenario.userWrapper.CreateUser(ctx, userName)
		if err != nil {
			panic(err)
		}
		log.Printf("Created user %v.\n", *user.UserName)
	} else {
		log.Printf("User %v already exists.\n", *user.UserName)
	}
	log.Println(strings.Repeat("-", 88))
	return user
}

// CreateAccessKey creates an access key for the user.
func (scenario AssumeRoleScenario) CreateAccessKey(ctx context.Context, user *types.User) *types.AccessKey {
	accessKey, err := scenario.userWrapper.CreateAccessKeyPair(ctx, *user.UserName)
	if err != nil {
		panic(err)
	}
	log.Printf("Created access key %v for your user.", *accessKey.AccessKeyId)
	log.Println("Waiting a few seconds for your user to be ready...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return accessKey
}

// CreateRoleAndPolicies creates a policy that grants permission to list S3 buckets for
// the current account and attaches the policy to a newly created role. It also adds an
// inline policy to the specified user that grants the user permission to assume the role.
func (scenario AssumeRoleScenario) CreateRoleAndPolicies(ctx context.Context, user *types.User) *types.Role {
	log.Println("Let's create a role and policy that grant permission to list S3 buckets.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	listBucketsRole, err := scenario.roleWrapper.CreateRole(ctx, scenario.helper.GetName(), *user.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created role %v.\n", *listBucketsRole.RoleName)
	listBucketsPolicy, err := scenario.policyWrapper.CreatePolicy(
		ctx, scenario.helper.GetName(), []string{"s3:ListAllMyBuckets"}, "arn:aws:s3:::*")
	if err != nil {
		panic(err)
	}
	log.Printf("Created policy %v.\n", *listBucketsPolicy.PolicyName)
	err = scenario.roleWrapper.AttachRolePolicy(ctx, *listBucketsPolicy.Arn, *listBucketsRole.RoleName)
	if err != nil {
		panic(err)
	}
	log.Printf("Attached policy %v to role %v.\n", *listBucketsPolicy.PolicyName,
		*listBucketsRole.RoleName)
	err = scenario.userWrapper.CreateUserPolicy(ctx, *user.UserName, scenario.helper.GetName(),
		[]string{"sts:AssumeRole"}, *listBucketsRole.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created an inline policy for user %v that lets the user assume the role.\n",
		*user.UserName)
	log.Println("Let's give AWS a few seconds to propagate these new resources and connections...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return listBucketsRole
}

// ListBucketsWithoutPermissions creates an Amazon S3 client from the user's access key
// credentials and tries to list buckets for the account. Because the user does not have
// permission to perform this action, the action fails.
func (scenario AssumeRoleScenario) ListBucketsWithoutPermissions(ctx context.Context, accessKey *types.AccessKey) *aws.Config {
	log.Println("Let's try to list buckets without permissions. This should return an AccessDenied error.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	noPermsConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*accessKey.AccessKeyId, *accessKey.SecretAccessKey, ""),
		))
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&noPermsConfig)

	s3Client := s3.NewFromConfig(noPermsConfig)
	_, err = s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		// The SDK for Go does not model the AccessDenied error, so check ErrorCode directly.
		var ae smithy.APIError
		if errors.As(err, &ae) {
			switch ae.ErrorCode() {
			case "AccessDenied":
				log.Println("Got AccessDenied error, which is the expected result because\n" +
					"the ListBuckets call was made without permissions.")
			default:
				log.Println("Expected AccessDenied, got something else.")
				panic(err)
			}
		}
	} else {
		log.Println("Expected AccessDenied error when calling ListBuckets without permissions,\n" +
			"but the call succeeded. Continuing the example anyway...")
	}
	log.Println(strings.Repeat("-", 88))
	return &noPermsConfig
}

// ListBucketsWithAssumedRole performs the following actions:
//
//  1. Creates an AWS Security Token Service (AWS STS) client from the config created from
//     the user's access key credentials.
//  2. Gets temporary credentials by assuming the role that grants permission to list the
//     buckets.
//  3. Creates an Amazon S3 client from the temporary credentials.
//  4. Lists buckets for the account. Because the temporary credentials are generated by
//     assuming the role that grants permission, the action succeeds.
func (scenario AssumeRoleScenario) ListBucketsWithAssumedRole(ctx context.Context, noPermsConfig *aws.Config, role *types.Role) {
	log.Println("Let's assume the role that grants permission to list buckets and try again.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	stsClient := sts.NewFromConfig(*noPermsConfig)
	tempCredentials, err := stsClient.AssumeRole(ctx, &sts.AssumeRoleInput{
		RoleArn:         role.Arn,
		RoleSessionName: aws.String("AssumeRoleExampleSession"),
		DurationSeconds: aws.Int32(900),
	})
	if err != nil {
		log.Printf("Couldn't assume role %v.\n", *role.RoleName)
		panic(err)
	}
	log.Printf("Assumed role %v, got temporary credentials.\n", *role.RoleName)
	assumeRoleConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*tempCredentials.Credentials.AccessKeyId,
			*tempCredentials.Credentials.SecretAccessKey,
			*tempCredentials.Credentials.SessionToken),
		),
	)
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&assumeRoleConfig)

	s3Client := s3.NewFromConfig(assumeRoleConfig)
	result, err := s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		log.Println("Couldn't list buckets with assumed role credentials.")
		panic(err)
	}
	log.Println("Successfully called ListBuckets with assumed role credentials, \n" +
		"here are some of them:")
	for i := 0; i < len(result.Buckets) && i < 5; i++ {
		log.Printf("\t%v\n", *result.Buckets[i].Name)
	}
	log.Println(strings.Repeat("-", 88))
}

// Cleanup deletes all resources created for the scenario.
func (scenario AssumeRoleScenario) Cleanup(ctx context.Context, user *types.User, role *types.Role) {
	if scenario.questioner.AskBool(
		"Do you want to delete the resources created for this example? (y/n)", "y",
	) {
		policies, err := scenario.roleWrapper.ListAttachedRolePolicies(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		for _, policy := range policies {
			err = scenario.roleWrapper.DetachRolePolicy(ctx, *role.RoleName, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			err = scenario.policyWrapper.DeletePolicy(ctx, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			log.Printf("Detached policy %v from role %v and deleted the policy.\n",
				*policy.PolicyName, *role.RoleName)
		}
		err = scenario.roleWrapper.DeleteRole(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted role %v.\n", *role.RoleName)

		userPols, err := scenario.userWrapper.ListUserPolicies(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, userPol := range userPols {
			err = scenario.userWrapper.DeleteUserPolicy(ctx, *user.UserName, userPol)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted policy %v from user %v.\n", userPol, *user.UserName)
		}
		keys, err := scenario.userWrapper.ListAccessKeys(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, key := range keys {
			err = scenario.userWrapper.DeleteAccessKey(ctx, *user.UserName, *key.AccessKeyId)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted access key %v from user %v.\n", *key.AccessKeyId, *user.UserName)
		}
		err = scenario.userWrapper.DeleteUser(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted user %v.\n", *user.UserName)
		log.Println(strings.Repeat("-", 88))
	}

}

// IScenarioHelper abstracts input and wait functions from a scenario so that they
// can be mocked for unit testing.
type IScenarioHelper interface {
	GetName() string
	Pause(secs int)
}

const rMax = 100000

type ScenarioHelper struct {
	Prefix string
	Random *rand.Rand
}

// GetName returns a unique name formed of a prefix and a random number.
func (helper *ScenarioHelper) GetName() string {
	return fmt.Sprintf("%v%v", helper.Prefix, helper.Random.Intn(rMax))
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	time.Sleep(time.Duration(secs) * time.Second)
}
```
계정 작업을 래핑하는 구조체를 정의합니다.  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// GetAccountPasswordPolicy gets the account password policy for the current account.
// If no policy has been set, a NoSuchEntityException is error is returned.
func (wrapper AccountWrapper) GetAccountPasswordPolicy(ctx context.Context) (*types.PasswordPolicy, error) {
	var pwPolicy *types.PasswordPolicy
	result, err := wrapper.IamClient.GetAccountPasswordPolicy(ctx,
		&iam.GetAccountPasswordPolicyInput{})
	if err != nil {
		log.Printf("Couldn't get account password policy. Here's why: %v\n", err)
	} else {
		pwPolicy = result.PasswordPolicy
	}
	return pwPolicy, err
}



// ListSAMLProviders gets the SAML providers for the account.
func (wrapper AccountWrapper) ListSAMLProviders(ctx context.Context) ([]types.SAMLProviderListEntry, error) {
	var providers []types.SAMLProviderListEntry
	result, err := wrapper.IamClient.ListSAMLProviders(ctx, &iam.ListSAMLProvidersInput{})
	if err != nil {
		log.Printf("Couldn't list SAML providers. Here's why: %v\n", err)
	} else {
		providers = result.SAMLProviderList
	}
	return providers, err
}
```
정책 작업을 래핑하는 구조체를 정의합니다.  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// ListPolicies gets up to maxPolicies policies.
func (wrapper PolicyWrapper) ListPolicies(ctx context.Context, maxPolicies int32) ([]types.Policy, error) {
	var policies []types.Policy
	result, err := wrapper.IamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPolicies),
	})
	if err != nil {
		log.Printf("Couldn't list policies. Here's why: %v\n", err)
	} else {
		policies = result.Policies
	}
	return policies, err
}



// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    []string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
}

// CreatePolicy creates a policy that grants a list of actions to the specified resource.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper PolicyWrapper) CreatePolicy(ctx context.Context, policyName string, actions []string,
	resourceArn string) (*types.Policy, error) {
	var policy *types.Policy
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(resourceArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", resourceArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreatePolicy(ctx, &iam.CreatePolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
	})
	if err != nil {
		log.Printf("Couldn't create policy %v. Here's why: %v\n", policyName, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// GetPolicy gets data about a policy.
func (wrapper PolicyWrapper) GetPolicy(ctx context.Context, policyArn string) (*types.Policy, error) {
	var policy *types.Policy
	result, err := wrapper.IamClient.GetPolicy(ctx, &iam.GetPolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't get policy %v. Here's why: %v\n", policyArn, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// DeletePolicy deletes a policy.
func (wrapper PolicyWrapper) DeletePolicy(ctx context.Context, policyArn string) error {
	_, err := wrapper.IamClient.DeletePolicy(ctx, &iam.DeletePolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't delete policy %v. Here's why: %v\n", policyArn, err)
	}
	return err
}
```
역할 작업을 래핑하는 구조체를 정의합니다.  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// ListRoles gets up to maxRoles roles.
func (wrapper RoleWrapper) ListRoles(ctx context.Context, maxRoles int32) ([]types.Role, error) {
	var roles []types.Role
	result, err := wrapper.IamClient.ListRoles(ctx,
		&iam.ListRolesInput{MaxItems: aws.Int32(maxRoles)},
	)
	if err != nil {
		log.Printf("Couldn't list roles. Here's why: %v\n", err)
	} else {
		roles = result.Roles
	}
	return roles, err
}



// CreateRole creates a role that trusts a specified user. The trusted user can assume
// the role to acquire its permissions.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper RoleWrapper) CreateRole(ctx context.Context, roleName string, trustedUserArn string) (*types.Role, error) {
	var role *types.Role
	trustPolicy := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:    "Allow",
			Principal: map[string]string{"AWS": trustedUserArn},
			Action:    []string{"sts:AssumeRole"},
		}},
	}
	policyBytes, err := json.Marshal(trustPolicy)
	if err != nil {
		log.Printf("Couldn't create trust policy for %v. Here's why: %v\n", trustedUserArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreateRole(ctx, &iam.CreateRoleInput{
		AssumeRolePolicyDocument: aws.String(string(policyBytes)),
		RoleName:                 aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't create role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// GetRole gets data about a role.
func (wrapper RoleWrapper) GetRole(ctx context.Context, roleName string) (*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.GetRole(ctx,
		&iam.GetRoleInput{RoleName: aws.String(roleName)})
	if err != nil {
		log.Printf("Couldn't get role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// CreateServiceLinkedRole creates a service-linked role that is owned by the specified service.
func (wrapper RoleWrapper) CreateServiceLinkedRole(ctx context.Context, serviceName string, description string) (
	*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.CreateServiceLinkedRole(ctx, &iam.CreateServiceLinkedRoleInput{
		AWSServiceName: aws.String(serviceName),
		Description:    aws.String(description),
	})
	if err != nil {
		log.Printf("Couldn't create service-linked role %v. Here's why: %v\n", serviceName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// DeleteServiceLinkedRole deletes a service-linked role.
func (wrapper RoleWrapper) DeleteServiceLinkedRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteServiceLinkedRole(ctx, &iam.DeleteServiceLinkedRoleInput{
		RoleName: aws.String(roleName)},
	)
	if err != nil {
		log.Printf("Couldn't delete service-linked role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// AttachRolePolicy attaches a policy to a role.
func (wrapper RoleWrapper) AttachRolePolicy(ctx context.Context, policyArn string, roleName string) error {
	_, err := wrapper.IamClient.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't attach policy %v to role %v. Here's why: %v\n", policyArn, roleName, err)
	}
	return err
}



// ListAttachedRolePolicies lists the policies that are attached to the specified role.
func (wrapper RoleWrapper) ListAttachedRolePolicies(ctx context.Context, roleName string) ([]types.AttachedPolicy, error) {
	var policies []types.AttachedPolicy
	result, err := wrapper.IamClient.ListAttachedRolePolicies(ctx, &iam.ListAttachedRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list attached policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.AttachedPolicies
	}
	return policies, err
}



// DetachRolePolicy detaches a policy from a role.
func (wrapper RoleWrapper) DetachRolePolicy(ctx context.Context, roleName string, policyArn string) error {
	_, err := wrapper.IamClient.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't detach policy from role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// ListRolePolicies lists the inline policies for a role.
func (wrapper RoleWrapper) ListRolePolicies(ctx context.Context, roleName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListRolePolicies(ctx, &iam.ListRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteRole deletes a role. All attached policies must be detached before a
// role can be deleted.
func (wrapper RoleWrapper) DeleteRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteRole(ctx, &iam.DeleteRoleInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't delete role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
사용자 작업을 래핑하는 구조체를 정의합니다.  

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUsers gets up to maxUsers number of users.
func (wrapper UserWrapper) ListUsers(ctx context.Context, maxUsers int32) ([]types.User, error) {
	var users []types.User
	result, err := wrapper.IamClient.ListUsers(ctx, &iam.ListUsersInput{
		MaxItems: aws.Int32(maxUsers),
	})
	if err != nil {
		log.Printf("Couldn't list users. Here's why: %v\n", err)
	} else {
		users = result.Users
	}
	return users, err
}



// GetUser gets data about a user.
func (wrapper UserWrapper) GetUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.GetUser(ctx, &iam.GetUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NoSuchEntityException:
				log.Printf("User %v does not exist.\n", userName)
				err = nil
			default:
				log.Printf("Couldn't get user %v. Here's why: %v\n", userName, err)
			}
		}
	} else {
		user = result.User
	}
	return user, err
}



// CreateUser creates a new user with the specified name.
func (wrapper UserWrapper) CreateUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.CreateUser(ctx, &iam.CreateUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
	} else {
		user = result.User
	}
	return user, err
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// ListUserPolicies lists the inline policies for the specified user.
func (wrapper UserWrapper) ListUserPolicies(ctx context.Context, userName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListUserPolicies(ctx, &iam.ListUserPoliciesInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for user %v. Here's why: %v\n", userName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteUserPolicy deletes an inline policy from a user.
func (wrapper UserWrapper) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
	_, err := wrapper.IamClient.DeleteUserPolicy(ctx, &iam.DeleteUserPolicyInput{
		PolicyName: aws.String(policyName),
		UserName:   aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete policy from user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// DeleteUser deletes a user.
func (wrapper UserWrapper) DeleteUser(ctx context.Context, userName string) error {
	_, err := wrapper.IamClient.DeleteUser(ctx, &iam.DeleteUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// CreateAccessKeyPair creates an access key for a user. The returned access key contains
// the ID and secret credentials needed to use the key.
func (wrapper UserWrapper) CreateAccessKeyPair(ctx context.Context, userName string) (*types.AccessKey, error) {
	var key *types.AccessKey
	result, err := wrapper.IamClient.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{
		UserName: aws.String(userName)})
	if err != nil {
		log.Printf("Couldn't create access key pair for user %v. Here's why: %v\n", userName, err)
	} else {
		key = result.AccessKey
	}
	return key, err
}



// DeleteAccessKey deletes an access key from a user.
func (wrapper UserWrapper) DeleteAccessKey(ctx context.Context, userName string, keyId string) error {
	_, err := wrapper.IamClient.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{
		AccessKeyId: aws.String(keyId),
		UserName:    aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete access key %v. Here's why: %v\n", keyId, err)
	}
	return err
}



// ListAccessKeys lists the access keys for the specified user.
func (wrapper UserWrapper) ListAccessKeys(ctx context.Context, userName string) ([]types.AccessKeyMetadata, error) {
	var keys []types.AccessKeyMetadata
	result, err := wrapper.IamClient.ListAccessKeys(ctx, &iam.ListAccessKeysInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list access keys for user %v. Here's why: %v\n", userName, err)
	} else {
		keys = result.AccessKeyMetadata
	}
	return keys, err
}
```
+ API 세부 정보는 *AWS SDK for Go API 참조*의 다음 주제를 참조하십시오.
  + [AttachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.AttachRolePolicy)
  + [CreateAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateAccessKey)
  + [CreatePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreatePolicy)
  + [CreateRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)
  + [CreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateUser)
  + [DeleteAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteAccessKey)
  + [DeletePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeletePolicy)
  + [DeleteRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteRole)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUser)
  + [DeleteUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUserPolicy)
  + [DetachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DetachRolePolicy)
  + [PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)

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

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

```
/*
  To run this Java V2 code example, set up your development environment, including your credentials.

  For information, see this documentation topic:

  https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html

  This example performs these operations:

  1. Creates a user that has no permissions.
  2. Creates a role and policy that grants Amazon S3 permissions.
  3. Creates a role.
  4. Grants the user permissions.
  5. Gets temporary credentials by assuming the role.  Creates an Amazon S3 Service client object with the temporary credentials.
  6. Deletes the resources.
 */

public class IAMScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    public static final String PolicyDocument = "{" +
            "  \"Version\": \"2012-10-17\"," +
            "  \"Statement\": [" +
            "    {" +
            "        \"Effect\": \"Allow\"," +
            "        \"Action\": [" +
            "            \"s3:*\"" +
            "       ]," +
            "       \"Resource\": \"*\"" +
            "    }" +
            "   ]" +
            "}";

    public static String userArn;

    public static void main(String[] args) throws Exception {

        final String usage = """

                Usage:
                    <username> <policyName> <roleName> <roleSessionName> <bucketName>\s

                Where:
                    username - The name of the IAM user to create.\s
                    policyName - The name of the policy to create.\s
                    roleName - The name of the role to create.\s
                    roleSessionName - The name of the session required for the assumeRole operation.\s
                    bucketName - The name of the Amazon S3 bucket from which objects are read.\s
                """;

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

        String userName = args[0];
        String policyName = args[1];
        String roleName = args[2];
        String roleSessionName = args[3];
        String bucketName = args[4];

        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS IAM example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 1. Create the IAM user.");
        User createUser = createIAMUser(iam, userName);

        System.out.println(DASHES);
        userArn = createUser.arn();

        AccessKey myKey = createIAMAccessKey(iam, userName);
        String accessKey = myKey.accessKeyId();
        String secretKey = myKey.secretAccessKey();
        String assumeRolePolicyDocument = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "	\"AWS\": \"" + userArn + "\"" +
                "}," +
                "\"Action\": \"sts:AssumeRole\"" +
                "}]" +
                "}";

        System.out.println(assumeRolePolicyDocument);
        System.out.println(userName + " was successfully created.");
        System.out.println(DASHES);
        System.out.println("2. Creates a policy.");
        String polArn = createIAMPolicy(iam, policyName);
        System.out.println("The policy " + polArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Creates a role.");
        TimeUnit.SECONDS.sleep(30);
        String roleArn = createIAMRole(iam, roleName, assumeRolePolicyDocument);
        System.out.println(roleArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Grants the user permissions.");
        attachIAMRolePolicy(iam, roleName, polArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("*** Wait for 30 secs so the resource is available");
        TimeUnit.SECONDS.sleep(30);
        System.out.println("5. Gets temporary credentials by assuming the role.");
        System.out.println("Perform an Amazon S3 Service operation using the temporary credentials.");
        assumeRole(roleArn, roleSessionName, bucketName, accessKey, secretKey);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6 Getting ready to delete the AWS resources");
        deleteKey(iam, userName, accessKey);
        deleteRole(iam, roleName, polArn);
        deleteIAMUser(iam, userName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("This IAM Scenario has successfully completed");
        System.out.println(DASHES);
    }

    public static AccessKey createIAMAccessKey(IamClient iam, String user) {
        try {
            CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
                    .userName(user)
                    .build();

            CreateAccessKeyResponse response = iam.createAccessKey(request);
            return response.accessKey();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static User createIAMUser(IamClient iam, String username) {
        try {
            // Create an IamWaiter object
            IamWaiter iamWaiter = iam.waiter();
            CreateUserRequest request = CreateUserRequest.builder()
                    .userName(username)
                    .build();

            // Wait until the user is created.
            CreateUserResponse response = iam.createUser(request);
            GetUserRequest userRequest = GetUserRequest.builder()
                    .userName(response.user().userName())
                    .build();

            WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);
            waitUntilUserExists.matched().response().ifPresent(System.out::println);
            return response.user();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static String createIAMRole(IamClient iam, String rolename, String json) {

        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(rolename)
                    .assumeRolePolicyDocument(json)
                    .description("Created using the AWS SDK for Java")
                    .build();

            CreateRoleResponse response = iam.createRole(request);
            System.out.println("The ARN of the role is " + response.role().arn());
            return response.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static String createIAMPolicy(IamClient iam, String policyName) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();
            CreatePolicyRequest request = CreatePolicyRequest.builder()
                    .policyName(policyName)
                    .policyDocument(PolicyDocument).build();

            CreatePolicyResponse response = iam.createPolicy(request);
            GetPolicyRequest polRequest = GetPolicyRequest.builder()
                    .policyArn(response.policy().arn())
                    .build();

            WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
            waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
            return response.policy().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) {
        try {
            ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
                    .roleName(roleName)
                    .build();

            ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
            List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
            String polArn;
            for (AttachedPolicy policy : attachedPolicies) {
                polArn = policy.policyArn();
                if (polArn.compareTo(policyArn) == 0) {
                    System.out.println(roleName + " policy is already attached to this role.");
                    return;
                }
            }

            AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.attachRolePolicy(attachRequest);
            System.out.println("Successfully attached policy " + policyArn + " to role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Invoke an Amazon S3 operation using the Assumed Role.
    public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal,
            String keySecret) {

        // Use the creds of the new IAM user that was created in this code example.
        AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret);
        StsClient stsClient = StsClient.builder()
                .region(Region.US_EAST_1)
                .credentialsProvider(StaticCredentialsProvider.create(credentials))
                .build();

        try {
            AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                    .roleArn(roleArn)
                    .roleSessionName(roleSessionName)
                    .build();

            AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
            Credentials myCreds = roleResponse.credentials();
            String key = myCreds.accessKeyId();
            String secKey = myCreds.secretAccessKey();
            String secToken = myCreds.sessionToken();

            // List all objects in an Amazon S3 bucket using the temp creds retrieved by
            // invoking assumeRole.
            Region region = Region.US_EAST_1;
            S3Client s3 = S3Client.builder()
                    .credentialsProvider(
                            StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken)))
                    .region(region)
                    .build();

            System.out.println("Created a S3Client using temp credentials.");
            System.out.println("Listing objects in " + bucketName);
            ListObjectsRequest listObjects = ListObjectsRequest.builder()
                    .bucket(bucketName)
                    .build();

            ListObjectsResponse res = s3.listObjects(listObjects);
            List<S3Object> objects = res.contents();
            for (S3Object myValue : objects) {
                System.out.println("The name of the key is " + myValue.key());
                System.out.println("The owner is " + myValue.owner());
            }

        } catch (StsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void deleteRole(IamClient iam, String roleName, String polArn) {

        try {
            // First the policy needs to be detached.
            DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder()
                    .policyArn(polArn)
                    .roleName(roleName)
                    .build();

            iam.detachRolePolicy(rolePolicyRequest);

            // Delete the policy.
            DeletePolicyRequest request = DeletePolicyRequest.builder()
                    .policyArn(polArn)
                    .build();

            iam.deletePolicy(request);
            System.out.println("*** Successfully deleted " + polArn);

            // Delete the role.
            DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            iam.deleteRole(roleRequest);
            System.out.println("*** Successfully deleted " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteKey(IamClient iam, String username, String accessKey) {
        try {
            DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()
                    .accessKeyId(accessKey)
                    .userName(username)
                    .build();

            iam.deleteAccessKey(request);
            System.out.println("Successfully deleted access key " + accessKey +
                    " from user " + username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteIAMUser(IamClient iam, String userName) {
        try {
            DeleteUserRequest request = DeleteUserRequest.builder()
                    .userName(userName)
                    .build();

            iam.deleteUser(request);
            System.out.println("*** Successfully deleted " + userName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+ API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 다음 주제를 참조하십시오.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/PutUserPolicy)

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

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 역할과 IAM 사용자를 생성합니다. 사용자는 역할을 수임할 수 있는 권한만 있습니다. 역할을 수임한 후 임시 자격 증명을 사용하여 계정의 버킷을 나열합니다.  

```
import {
  CreateUserCommand,
  GetUserCommand,
  CreateAccessKeyCommand,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  DeleteAccessKeyCommand,
  DeleteUserCommand,
  DeleteRoleCommand,
  DeletePolicyCommand,
  DetachRolePolicyCommand,
  IAMClient,
} from "@aws-sdk/client-iam";
import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3";
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario/index.js";

// Set the parameters.
const iamClient = new IAMClient({});
const userName = "iam_basic_test_username";
const policyName = "iam_basic_test_policy";
const roleName = "iam_basic_test_role";

/**
 * Create a new IAM user. If the user already exists, give
 * the option to delete and re-create it.
 * @param {string} name
 */
export const createUser = async (name, confirmAll = false) => {
  try {
    const { User } = await iamClient.send(
      new GetUserCommand({ UserName: name }),
    );
    const input = new ScenarioInput(
      "deleteUser",
      "Do you want to delete and remake this user?",
      { type: "confirm" },
    );
    const deleteUser = await input.handle({}, { confirmAll });
    // If the user exists, and you want to delete it, delete the user
    // and then create it again.
    if (deleteUser) {
      await iamClient.send(new DeleteUserCommand({ UserName: User.UserName }));
      await iamClient.send(new CreateUserCommand({ UserName: name }));
    } else {
      console.warn(
        `${name} already exists. The scenario may not work as expected.`,
      );
      return User;
    }
  } catch (caught) {
    // If there is no user by that name, create one.
    if (caught instanceof Error && caught.name === "NoSuchEntityException") {
      const { User } = await iamClient.send(
        new CreateUserCommand({ UserName: name }),
      );
      return User;
    }
    throw caught;
  }
};

export const main = async (confirmAll = false) => {
  // Create a user. The user has no permissions by default.
  const User = await createUser(userName, confirmAll);

  if (!User) {
    throw new Error("User not created");
  }

  // Create an access key. This key is used to authenticate the new user to
  // Amazon Simple Storage Service (Amazon S3) and AWS Security Token Service (AWS STS).
  // It's not best practice to use access keys. For more information, see https://aws.amazon.com/iam/resources/best-practices/.
  const createAccessKeyResponse = await iamClient.send(
    new CreateAccessKeyCommand({ UserName: userName }),
  );

  if (
    !createAccessKeyResponse.AccessKey?.AccessKeyId ||
    !createAccessKeyResponse.AccessKey?.SecretAccessKey
  ) {
    throw new Error("Access key not created");
  }

  const {
    AccessKey: { AccessKeyId, SecretAccessKey },
  } = createAccessKeyResponse;

  let s3Client = new S3Client({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the list buckets operation until it succeeds. InvalidAccessKeyId is
  // thrown while the user and access keys are still stabilizing.
  await retry({ intervalInMs: 1000, maxRetries: 300 }, async () => {
    try {
      return await listBuckets(s3Client);
    } catch (err) {
      if (err instanceof Error && err.name === "InvalidAccessKeyId") {
        throw err;
      }
    }
  });

  // Retry the create role operation until it succeeds. A MalformedPolicyDocument error
  // is thrown while the user and access keys are still stabilizing.
  const { Role } = await retry(
    {
      intervalInMs: 2000,
      maxRetries: 60,
    },
    () =>
      iamClient.send(
        new CreateRoleCommand({
          AssumeRolePolicyDocument: JSON.stringify({
            Version: "2012-10-17",
            Statement: [
              {
                Effect: "Allow",
                Principal: {
                  // Allow the previously created user to assume this role.
                  AWS: User.Arn,
                },
                Action: "sts:AssumeRole",
              },
            ],
          }),
          RoleName: roleName,
        }),
      ),
  );

  if (!Role) {
    throw new Error("Role not created");
  }

  // Create a policy that allows the user to list S3 buckets.
  const { Policy: listBucketPolicy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Action: ["s3:ListAllMyBuckets"],
            Resource: "*",
          },
        ],
      }),
      PolicyName: policyName,
    }),
  );

  if (!listBucketPolicy) {
    throw new Error("Policy not created");
  }

  // Attach the policy granting the 's3:ListAllMyBuckets' action to the role.
  await iamClient.send(
    new AttachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  // Assume the role.
  const stsClient = new STSClient({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the assume role operation until it succeeds.
  const { Credentials } = await retry(
    { intervalInMs: 2000, maxRetries: 60 },
    () =>
      stsClient.send(
        new AssumeRoleCommand({
          RoleArn: Role.Arn,
          RoleSessionName: `iamBasicScenarioSession-${Math.floor(
            Math.random() * 1000000,
          )}`,
          DurationSeconds: 900,
        }),
      ),
  );

  if (!Credentials?.AccessKeyId || !Credentials?.SecretAccessKey) {
    throw new Error("Credentials not created");
  }

  s3Client = new S3Client({
    credentials: {
      accessKeyId: Credentials.AccessKeyId,
      secretAccessKey: Credentials.SecretAccessKey,
      sessionToken: Credentials.SessionToken,
    },
  });

  // List the S3 buckets again.
  // Retry the list buckets operation until it succeeds. AccessDenied might
  // be thrown while the role policy is still stabilizing.
  await retry({ intervalInMs: 2000, maxRetries: 120 }, () =>
    listBuckets(s3Client),
  );

  // Clean up.
  await iamClient.send(
    new DetachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeletePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
    }),
  );

  await iamClient.send(
    new DeleteRoleCommand({
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeleteAccessKeyCommand({
      UserName: userName,
      AccessKeyId,
    }),
  );

  await iamClient.send(
    new DeleteUserCommand({
      UserName: userName,
    }),
  );
};

/**
 *
 * @param {S3Client} s3Client
 */
const listBuckets = async (s3Client) => {
  const { Buckets } = await s3Client.send(new ListBucketsCommand({}));

  if (!Buckets) {
    throw new Error("Buckets not listed");
  }

  console.log(Buckets.map((bucket) => bucket.Name).join("\n"));
};
```
+ API 세부 정보는 *AWS SDK for JavaScript API 참조*의 다음 주제를 참조하십시오.
  + [AttachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/AttachRolePolicyCommand)
  + [CreateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccessKeyCommand)
  + [CreatePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreatePolicyCommand)
  + [CreateRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)
  + [CreateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateUserCommand)
  + [DeleteAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccessKeyCommand)
  + [DeletePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeletePolicyCommand)
  + [DeleteRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRoleCommand)
  + [DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserCommand)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserPolicyCommand)
  + [DetachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DetachRolePolicyCommand)
  + [PutUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/PutUserPolicyCommand)

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
IAM 사용자 작업을 래핑하는 함수를 생성합니다.  

```
suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <username> <policyName> <roleName> <roleSessionName> <fileLocation> <bucketName> 

    Where:
        username - The name of the IAM user to create. 
        policyName - The name of the policy to create. 
        roleName - The name of the role to create. 
        roleSessionName - The name of the session required for the assumeRole operation. 
        fileLocation - The file location to the JSON required to create the role (see Readme). 
        bucketName - The name of the Amazon S3 bucket from which objects are read. 
    """

    if (args.size != 6) {
        println(usage)
        exitProcess(1)
    }

    val userName = args[0]
    val policyName = args[1]
    val roleName = args[2]
    val roleSessionName = args[3]
    val fileLocation = args[4]
    val bucketName = args[5]

    createUser(userName)
    println("$userName was successfully created.")

    val polArn = createPolicy(policyName)
    println("The policy $polArn was successfully created.")

    val roleArn = createRole(roleName, fileLocation)
    println("$roleArn was successfully created.")
    attachRolePolicy(roleName, polArn)

    println("*** Wait for 1 MIN so the resource is available.")
    delay(60000)
    assumeGivenRole(roleArn, roleSessionName, bucketName)

    println("*** Getting ready to delete the AWS resources.")
    deleteRole(roleName, polArn)
    deleteUser(userName)
    println("This IAM Scenario has successfully completed.")
}

suspend fun createUser(usernameVal: String?): String? {
    val request =
        CreateUserRequest {
            userName = usernameVal
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createUser(request)
        return response.user?.userName
    }
}

suspend fun createPolicy(policyNameVal: String?): String {
    val policyDocumentValue = """
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "s3:*"
                ],
                "Resource": "*"
            }
        ]
    }
    """.trimIndent()

    val request =
        CreatePolicyRequest {
            policyName = policyNameVal
            policyDocument = policyDocumentValue
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createPolicy(request)
        return response.policy?.arn.toString()
    }
}

suspend fun createRole(
    rolenameVal: String?,
    fileLocation: String?,
): String? {
    val jsonObject = fileLocation?.let { readJsonSimpleDemo(it) } as JSONObject

    val request =
        CreateRoleRequest {
            roleName = rolenameVal
            assumeRolePolicyDocument = jsonObject.toJSONString()
            description = "Created using the AWS SDK for Kotlin"
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createRole(request)
        return response.role?.arn
    }
}

suspend fun attachRolePolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        ListAttachedRolePoliciesRequest {
            roleName = roleNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAttachedRolePolicies(request)
        val attachedPolicies = response.attachedPolicies

        // Ensure that the policy is not attached to this role.
        val checkStatus: Int
        if (attachedPolicies != null) {
            checkStatus = checkMyList(attachedPolicies, policyArnVal)
            if (checkStatus == -1) {
                return
            }
        }

        val policyRequest =
            AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policyArnVal
            }
        iamClient.attachRolePolicy(policyRequest)
        println("Successfully attached policy $policyArnVal to role $roleNameVal")
    }
}

fun checkMyList(
    attachedPolicies: List<AttachedPolicy>,
    policyArnVal: String,
): Int {
    for (policy in attachedPolicies) {
        val polArn = policy.policyArn.toString()

        if (polArn.compareTo(policyArnVal) == 0) {
            println("The policy is already attached to this role.")
            return -1
        }
    }
    return 0
}

suspend fun assumeGivenRole(
    roleArnVal: String?,
    roleSessionNameVal: String?,
    bucketName: String,
) {
    val stsClient = StsClient.fromEnvironment { region = "us-east-1" }
    val roleRequest =
        AssumeRoleRequest {
            roleArn = roleArnVal
            roleSessionName = roleSessionNameVal
        }

    val roleResponse = stsClient.assumeRole(roleRequest)
    val myCreds = roleResponse.credentials
    val key = myCreds?.accessKeyId
    val secKey = myCreds?.secretAccessKey
    val secToken = myCreds?.sessionToken

    val staticCredentials = StaticCredentialsProvider {
        accessKeyId = key
        secretAccessKey = secKey
        sessionToken = secToken
    }

    // List all objects in an Amazon S3 bucket using the temp creds.
    val s3 = S3Client.fromEnvironment {
        region = "us-east-1"
        credentialsProvider = staticCredentials
    }

    println("Created a S3Client using temp credentials.")
    println("Listing objects in $bucketName")

    val listObjects =
        ListObjectsRequest {
            bucket = bucketName
        }

    val response = s3.listObjects(listObjects)
    response.contents?.forEach { myObject ->
        println("The name of the key is ${myObject.key}")
        println("The owner is ${myObject.owner}")
    }
}

suspend fun deleteRole(
    roleNameVal: String,
    polArn: String,
) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }

    // First the policy needs to be detached.
    val rolePolicyRequest =
        DetachRolePolicyRequest {
            policyArn = polArn
            roleName = roleNameVal
        }

    iam.detachRolePolicy(rolePolicyRequest)

    // Delete the policy.
    val request =
        DeletePolicyRequest {
            policyArn = polArn
        }

    iam.deletePolicy(request)
    println("*** Successfully deleted $polArn")

    // Delete the role.
    val roleRequest =
        DeleteRoleRequest {
            roleName = roleNameVal
        }

    iam.deleteRole(roleRequest)
    println("*** Successfully deleted $roleNameVal")
}

suspend fun deleteUser(userNameVal: String) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }
    val request =
        DeleteUserRequest {
            userName = userNameVal
        }

    iam.deleteUser(request)
    println("*** Successfully deleted $userNameVal")
}

@Throws(java.lang.Exception::class)
fun readJsonSimpleDemo(filename: String): Any? {
    val reader = FileReader(filename)
    val jsonParser = JSONParser()
    return jsonParser.parse(reader)
}
```
+ API 세부 정보는 *AWS SDK for Kotlin API 참조*의 다음 주제를 참조하세요.
  + [AttachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreatePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeletePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DetachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

------
#### [ PHP ]

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

```
namespace Iam\Basics;

require 'vendor/autoload.php';

use Aws\Credentials\Credentials;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Aws\Sts\StsClient;
use Iam\IAMService;

echo("\n");
echo("--------------------------------------\n");
print("Welcome to the IAM getting started demo using PHP!\n");
echo("--------------------------------------\n");

$uuid = uniqid();
$service = new IAMService();

$user = $service->createUser("iam_demo_user_$uuid");
echo "Created user with the arn: {$user['Arn']}\n";

$key = $service->createAccessKey($user['UserName']);
$assumeRolePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{$user['Arn']}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }";
$assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument);
echo "Created role: {$assumeRoleRole['RoleName']}\n";

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

$service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);

$inlinePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{$assumeRoleRole['Arn']}\"}]
}";
$inlinePolicy = $service->createUserPolicy("iam_demo_inline_policy_$uuid", $inlinePolicyDocument, $user['UserName']);
//First, fail to list the buckets with the user
$credentials = new Credentials($key['AccessKeyId'], $key['SecretAccessKey']);
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
try {
    $s3Client->listBuckets([
    ]);
    echo "this should not run";
} catch (S3Exception $exception) {
    echo "successfully failed!\n";
}

$stsClient = new StsClient(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
sleep(10);
$assumedRole = $stsClient->assumeRole([
    'RoleArn' => $assumeRoleRole['Arn'],
    'RoleSessionName' => "DemoAssumeRoleSession_$uuid",
]);
$assumedCredentials = [
    'key' => $assumedRole['Credentials']['AccessKeyId'],
    'secret' => $assumedRole['Credentials']['SecretAccessKey'],
    'token' => $assumedRole['Credentials']['SessionToken'],
];
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $assumedCredentials]);
try {
    $s3Client->listBuckets([]);
    echo "this should now run!\n";
} catch (S3Exception $exception) {
    echo "this should now not fail\n";
}

$service->detachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);
$deletePolicy = $service->deletePolicy($listAllBucketsPolicy['Arn']);
echo "Delete policy: {$listAllBucketsPolicy['PolicyName']}\n";
$deletedRole = $service->deleteRole($assumeRoleRole['Arn']);
echo "Deleted role: {$assumeRoleRole['RoleName']}\n";
$deletedKey = $service->deleteAccessKey($key['AccessKeyId'], $user['UserName']);
$deletedUser = $service->deleteUser($user['UserName']);
echo "Delete user: {$user['UserName']}\n";
```
+ API 세부 정보는 *AWS SDK for PHP API 참조*의 다음 주제를 참조하십시오.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/PutUserPolicy)

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

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 역할과 IAM 사용자를 생성합니다. 사용자는 역할을 수임할 수 있는 권한만 있습니다. 역할을 수임한 후 임시 자격 증명을 사용하여 계정의 버킷을 나열합니다.  

```
import json
import sys
import time
from uuid import uuid4

import boto3
from botocore.exceptions import ClientError


def progress_bar(seconds):
    """Shows a simple progress bar in the command window."""
    for _ in range(seconds):
        time.sleep(1)
        print(".", end="")
        sys.stdout.flush()
    print()


def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates an access key pair for the user.
    Creates a role with a policy that lets the user assume the role.
    Creates a policy that allows listing Amazon S3 buckets.
    Attaches the policy to the role.
    Creates an inline policy for the user that lets the user assume the role.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource
                         that has permissions to create users, roles, and policies
                         in the account.
    :return: The newly created user, user key, and role.
    """
    try:
        user = iam_resource.create_user(UserName=f"demo-user-{uuid4()}")
        print(f"Created user {user.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a user for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user_key = user.create_access_key_pair()
        print(f"Created access key pair for user.")
    except ClientError as error:
        print(
            f"Couldn't create access keys for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    try:
        role = iam_resource.create_role(
            RoleName=f"demo-role-{uuid4()}",
            AssumeRolePolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {"AWS": user.arn},
                            "Action": "sts:AssumeRole",
                        }
                    ],
                }
            ),
        )
        print(f"Created role {role.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a role for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        policy = iam_resource.create_policy(
            PolicyName=f"demo-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "s3:ListAllMyBuckets",
                            "Resource": "arn:aws:s3:::*",
                        }
                    ],
                }
            ),
        )
        role.attach_policy(PolicyArn=policy.arn)
        print(f"Created policy {policy.policy_name} and attached it to the role.")
    except ClientError as error:
        print(
            f"Couldn't create a policy and attach it to role {role.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user.create_policy(
            PolicyName=f"demo-user-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "sts:AssumeRole",
                            "Resource": role.arn,
                        }
                    ],
                }
            ),
        )
        print(
            f"Created an inline policy for {user.name} that lets the user assume "
            f"the role."
        )
    except ClientError as error:
        print(
            f"Couldn't create an inline policy for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, role


def show_access_denied_without_role(user_key):
    """
    Shows that listing buckets without first assuming the role is not allowed.

    :param user_key: The key of the user created during setup. This user does not
                     have permission to list buckets in the account.
    """
    print(f"Try to list buckets without first assuming the role.")
    s3_denied_resource = boto3.resource(
        "s3", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        for bucket in s3_denied_resource.buckets.all():
            print(bucket.name)
        raise RuntimeError("Expected to get AccessDenied error when listing buckets!")
    except ClientError as error:
        if error.response["Error"]["Code"] == "AccessDenied":
            print("Attempt to list buckets with no permissions: AccessDenied.")
        else:
            raise


def list_buckets_from_assumed_role(user_key, assume_role_arn, session_name):
    """
    Assumes a role that grants permission to list the Amazon S3 buckets in the account.
    Uses the temporary credentials from the role to list the buckets that are owned
    by the assumed role's account.

    :param user_key: The access key of a user that has permission to assume the role.
    :param assume_role_arn: The Amazon Resource Name (ARN) of the role that
                            grants access to list the other account's buckets.
    :param session_name: The name of the STS session.
    """
    sts_client = boto3.client(
        "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        response = sts_client.assume_role(
            RoleArn=assume_role_arn, RoleSessionName=session_name
        )
        temp_credentials = response["Credentials"]
        print(f"Assumed role {assume_role_arn} and got temporary credentials.")
    except ClientError as error:
        print(
            f"Couldn't assume role {assume_role_arn}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    # Create an S3 resource that can access the account with the temporary credentials.
    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )
    print(f"Listing buckets for the assumed role's account:")
    try:
        for bucket in s3_resource.buckets.all():
            print(bucket.name)
    except ClientError as error:
        print(
            f"Couldn't list buckets for the account. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise




def teardown(user, role):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo role.
    """
    try:
        for attached in role.attached_policies.all():
            policy_name = attached.policy_name
            role.detach_policy(PolicyArn=attached.arn)
            attached.delete()
            print(f"Detached and deleted {policy_name}.")
        role.delete()
        print(f"Deleted {role.name}.")
    except ClientError as error:
        print(
            "Couldn't detach policy, delete policy, or delete role. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        for user_pol in user.policies.all():
            user_pol.delete()
            print("Deleted inline user policy.")
        for key in user.access_keys.all():
            key.delete()
            print("Deleted user's access key.")
        user.delete()
        print(f"Deleted {user.name}.")
    except ClientError as error:
        print(
            "Couldn't delete user policy or delete user. Here's why: "
            f"{error.response['Error']['Message']}"
        )


def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(f"Welcome to the IAM create user and assume role demo.")
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user = None
    role = None
    try:
        user, user_key, role = setup(iam_resource)
        print(f"Created {user.name} and {role.name}.")
        show_access_denied_without_role(user_key)
        list_buckets_from_assumed_role(user_key, role.arn, "AssumeRoleDemoSession")
    except Exception:
        print("Something went wrong!")
    finally:
        if user is not None and role is not None:
            teardown(user, role)
        print("Thanks for watching!")


if __name__ == "__main__":
    usage_demo()
```
+ API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 다음 주제를 참조하세요.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/PutUserPolicy)

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
Amazon S3 버킷을 나열할 수 있는 권한을 부여하는 역할과 IAM 사용자를 생성합니다. 사용자는 역할을 수임할 수 있는 권한만 있습니다. 역할을 수임한 후 임시 자격 증명을 사용하여 계정의 버킷을 나열합니다.  

```
# Wraps the scenario actions.
class ScenarioCreateUserAssumeRole
  attr_reader :iam_client

  # @param [Aws::IAM::Client] iam_client: The AWS IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Waits for the specified number of seconds.
  #
  # @param duration [Integer] The number of seconds to wait.
  def wait(duration)
    puts('Give AWS time to propagate resources...')
    sleep(duration)
  end

  # Creates a user.
  #
  # @param user_name [String] The name to give the user.
  # @return [Aws::IAM::User] The newly created user.
  def create_user(user_name)
    user = @iam_client.create_user(user_name: user_name).user
    @logger.info("Created demo user named #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info('Tried and failed to create demo user.')
    @logger.info("\t#{e.code}: #{e.message}")
    @logger.info("\nCan't continue the demo without a user!")
    raise
  else
    user
  end

  # Creates an access key for a user.
  #
  # @param user [Aws::IAM::User] The user that owns the key.
  # @return [Aws::IAM::AccessKeyPair] The newly created access key.
  def create_access_key_pair(user)
    user_key = @iam_client.create_access_key(user_name: user.user_name).access_key
    @logger.info("Created accesskey pair for user #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create access keys for user #{user.user_name}.")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    user_key
  end

  # Creates a role that can be assumed by a user.
  #
  # @param role_name [String] The name to give the role.
  # @param user [Aws::IAM::User] The user who is granted permission to assume the role.
  # @return [Aws::IAM::Role] The newly created role.
  def create_role(role_name, user)
    trust_policy = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Principal: { 'AWS': user.arn },
        Action: 'sts:AssumeRole'
      }]
    }.to_json
    role = @iam_client.create_role(
      role_name: role_name,
      assume_role_policy_document: trust_policy
    ).role
    @logger.info("Created role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a role for the demo. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    role
  end

  # Creates a policy that grants permission to list S3 buckets in the account, and
  # then attaches the policy to a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param role [Aws::IAM::Role] The role that the policy is attached to.
  # @return [Aws::IAM::Policy] The newly created policy.
  def create_and_attach_role_policy(policy_name, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 's3:ListAllMyBuckets',
        Resource: 'arn:aws:s3:::*'
      }]
    }.to_json
    policy = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document
    ).policy
    @iam_client.attach_role_policy(
      role_name: role.role_name,
      policy_arn: policy.arn
    )
    @logger.info("Created policy #{policy.policy_name} and attached it to role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a policy and attach it to role #{role.role_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an inline policy for a user that lets the user assume a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param user [Aws::IAM::User] The user that owns the policy.
  # @param role [Aws::IAM::Role] The role that can be assumed.
  # @return [Aws::IAM::UserPolicy] The newly created policy.
  def create_user_policy(policy_name, user, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 'sts:AssumeRole',
        Resource: role.arn
      }]
    }.to_json
    @iam_client.put_user_policy(
      user_name: user.user_name,
      policy_name: policy_name,
      policy_document: policy_document
    )
    puts("Created an inline policy for #{user.user_name} that lets the user assume role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create an inline policy for user #{user.user_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an Amazon S3 resource with specified credentials. This is separated into a
  # factory function so that it can be mocked for unit testing.
  #
  # @param credentials [Aws::Credentials] The credentials used by the Amazon S3 resource.
  def create_s3_resource(credentials)
    Aws::S3::Resource.new(client: Aws::S3::Client.new(credentials: credentials))
  end

  # Lists the S3 buckets for the account, using the specified Amazon S3 resource.
  # Because the resource uses credentials with limited access, it may not be able to
  # list the S3 buckets.
  #
  # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource.
  def list_buckets(s3_resource)
    count = 10
    s3_resource.buckets.each do |bucket|
      @logger.info "\t#{bucket.name}"
      count -= 1
      break if count.zero?
    end
  rescue Aws::Errors::ServiceError => e
    if e.code == 'AccessDenied'
      puts('Attempt to list buckets with no permissions: AccessDenied.')
    else
      @logger.info("Couldn't list buckets for the account. Here's why: ")
      @logger.info("\t#{e.code}: #{e.message}")
      raise
    end
  end

  # Creates an AWS Security Token Service (AWS STS) client with specified credentials.
  # This is separated into a factory function so that it can be mocked for unit testing.
  #
  # @param key_id [String] The ID of the access key used by the STS client.
  # @param key_secret [String] The secret part of the access key used by the STS client.
  def create_sts_client(key_id, key_secret)
    Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret)
  end

  # Gets temporary credentials that can be used to assume a role.
  #
  # @param role_arn [String] The ARN of the role that is assumed when these credentials
  #                          are used.
  # @param sts_client [AWS::STS::Client] An AWS STS client.
  # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role.
  def assume_role(role_arn, sts_client)
    credentials = Aws::AssumeRoleCredentials.new(
      client: sts_client,
      role_arn: role_arn,
      role_session_name: 'create-use-assume-role-scenario'
    )
    @logger.info("Assumed role '#{role_arn}', got temporary credentials.")
    credentials
  end

  # Deletes a role. If the role has policies attached, they are detached and
  # deleted before the role is deleted.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_role(role_name)
    @iam_client.list_attached_role_policies(role_name: role_name).attached_policies.each do |policy|
      @iam_client.detach_role_policy(role_name: role_name, policy_arn: policy.policy_arn)
      @iam_client.delete_policy(policy_arn: policy.policy_arn)
      @logger.info("Detached and deleted policy #{policy.policy_name}.")
    end
    @iam_client.delete_role({ role_name: role_name })
    @logger.info("Role deleted: #{role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't detach policies and delete role #{role.name}. Here's why:")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Deletes a user. If the user has inline policies or access keys, they are deleted
  # before the user is deleted.
  #
  # @param user [Aws::IAM::User] The user to delete.
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
end

# Runs the IAM create a user and assume a role scenario.
def run_scenario(scenario)
  puts('-' * 88)
  puts('Welcome to the IAM create a user and assume a role demo!')
  puts('-' * 88)
  user = scenario.create_user("doc-example-user-#{Random.uuid}")
  user_key = scenario.create_access_key_pair(user)
  scenario.wait(10)
  role = scenario.create_role("doc-example-role-#{Random.uuid}", user)
  scenario.create_and_attach_role_policy("doc-example-role-policy-#{Random.uuid}", role)
  scenario.create_user_policy("doc-example-user-policy-#{Random.uuid}", user, role)
  scenario.wait(10)
  puts('Try to list buckets with credentials for a user who has no permissions.')
  puts('Expect AccessDenied from this call.')
  scenario.list_buckets(
    scenario.create_s3_resource(Aws::Credentials.new(user_key.access_key_id, user_key.secret_access_key))
  )
  puts('Now, assume the role that grants permission.')
  temp_credentials = scenario.assume_role(
    role.arn, scenario.create_sts_client(user_key.access_key_id, user_key.secret_access_key)
  )
  puts('Here are your buckets:')
  scenario.list_buckets(scenario.create_s3_resource(temp_credentials))
  puts("Deleting role '#{role.role_name}' and attached policies.")
  scenario.delete_role(role.role_name)
  puts("Deleting user '#{user.user_name}', policies, and keys.")
  scenario.delete_user(user.user_name)
  puts('Thanks for watching!')
  puts('-' * 88)
rescue Aws::Errors::ServiceError => e
  puts('Something went wrong with the demo.')
  puts("\t#{e.code}: #{e.message}")
end

run_scenario(ScenarioCreateUserAssumeRole.new(Aws::IAM::Client.new)) if $PROGRAM_NAME == __FILE__
```
+ API 세부 정보는 *AWS SDK for Ruby API 참조*의 다음 주제를 참조하십시오.
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Rust ]

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

```
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iam::Error as iamError;
use aws_sdk_iam::{config::Credentials as iamCredentials, config::Region, Client as iamClient};
use aws_sdk_s3::Client as s3Client;
use aws_sdk_sts::Client as stsClient;
use tokio::time::{sleep, Duration};
use uuid::Uuid;

#[tokio::main]
async fn main() -> Result<(), iamError> {
    let (client, uuid, list_all_buckets_policy_document, inline_policy_document) =
        initialize_variables().await;

    if let Err(e) = run_iam_operations(
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
    .await
    {
        println!("{:?}", e);
    };

    Ok(())
}

async fn initialize_variables() -> (iamClient, String, String, String) {
    let region_provider = RegionProviderChain::first_try(Region::new("us-west-2"));

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = iamClient::new(&shared_config);
    let uuid = Uuid::new_v4().to_string();

    let list_all_buckets_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
    }"
    .to_string();
    let inline_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{}\"}]
    }"
    .to_string();

    (
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
}

async fn run_iam_operations(
    client: iamClient,
    uuid: String,
    list_all_buckets_policy_document: String,
    inline_policy_document: String,
) -> Result<(), iamError> {
    let user = iam_service::create_user(&client, &format!("{}{}", "iam_demo_user_", uuid)).await?;
    println!("Created the user with the name: {}", user.user_name());
    let key = iam_service::create_access_key(&client, user.user_name()).await?;

    let assume_role_policy_document = "{
        \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }"
    .to_string()
    .replace("{}", user.arn());

    let assume_role_role = iam_service::create_role(
        &client,
        &format!("{}{}", "iam_demo_role_", uuid),
        &assume_role_policy_document,
    )
    .await?;
    println!("Created the role with the ARN: {}", assume_role_role.arn());

    let list_all_buckets_policy = iam_service::create_policy(
        &client,
        &format!("{}{}", "iam_demo_policy_", uuid),
        &list_all_buckets_policy_document,
    )
    .await?;
    println!(
        "Created policy: {}",
        list_all_buckets_policy.policy_name.as_ref().unwrap()
    );

    let attach_role_policy_result =
        iam_service::attach_role_policy(&client, &assume_role_role, &list_all_buckets_policy)
            .await?;
    println!(
        "Attached the policy to the role: {:?}",
        attach_role_policy_result
    );

    let inline_policy_name = format!("{}{}", "iam_demo_inline_policy_", uuid);
    let inline_policy_document = inline_policy_document.replace("{}", assume_role_role.arn());
    iam_service::create_user_policy(&client, &user, &inline_policy_name, &inline_policy_document)
        .await?;
    println!("Created inline policy.");

    //First, fail to list the buckets with the user.
    let creds = iamCredentials::from_keys(key.access_key_id(), key.secret_access_key(), None);
    let fail_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    println!("Fail config: {:?}", fail_config);
    let fail_client: s3Client = s3Client::new(&fail_config);
    match fail_client.list_buckets().send().await {
        Ok(e) => {
            println!("This should not run. {:?}", e);
        }
        Err(e) => {
            println!("Successfully failed with error: {:?}", e)
        }
    }

    let sts_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    let sts_client: stsClient = stsClient::new(&sts_config);
    sleep(Duration::from_secs(10)).await;
    let assumed_role = sts_client
        .assume_role()
        .role_arn(assume_role_role.arn())
        .role_session_name(format!("iam_demo_assumerole_session_{uuid}"))
        .send()
        .await;
    println!("Assumed role: {:?}", assumed_role);
    sleep(Duration::from_secs(10)).await;

    let assumed_credentials = iamCredentials::from_keys(
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .access_key_id(),
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .secret_access_key(),
        Some(
            assumed_role
                .as_ref()
                .unwrap()
                .credentials
                .as_ref()
                .unwrap()
                .session_token
                .clone(),
        ),
    );

    let succeed_config = aws_config::from_env()
        .credentials_provider(assumed_credentials)
        .load()
        .await;
    println!("succeed config: {:?}", succeed_config);
    let succeed_client: s3Client = s3Client::new(&succeed_config);
    sleep(Duration::from_secs(10)).await;
    match succeed_client.list_buckets().send().await {
        Ok(_) => {
            println!("This should now run successfully.")
        }
        Err(e) => {
            println!("This should not run. {:?}", e);
            panic!()
        }
    }

    //Clean up.
    iam_service::detach_role_policy(
        &client,
        assume_role_role.role_name(),
        list_all_buckets_policy.arn().unwrap_or_default(),
    )
    .await?;
    iam_service::delete_policy(&client, list_all_buckets_policy).await?;
    iam_service::delete_role(&client, &assume_role_role).await?;
    println!("Deleted role {}", assume_role_role.role_name());
    iam_service::delete_access_key(&client, &user, &key).await?;
    println!("Deleted key for {}", key.user_name());
    iam_service::delete_user_policy(&client, &user, &inline_policy_name).await?;
    println!("Deleted inline user policy: {}", inline_policy_name);
    iam_service::delete_user(&client, &user).await?;
    println!("Deleted user {}", user.user_name());

    Ok(())
}
```
+ API 세부 정보는 *AWS  SDK for Rust API 참조*의 다음 주제를 참조하세요.
  + [AttachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_role_policy)
  + [CreateAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_access_key)
  + [CreatePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_policy)
  + [CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)
  + [CreateUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_user)
  + [DeleteAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_access_key)
  + [DeletePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_policy)
  + [DeleteRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_role)
  + [DeleteUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user)
  + [DeleteUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user_policy)
  + [DetachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_role_policy)
  + [PutUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.put_user_policy)

------

# AWS SDKs 사용하는 IAM에 대한 작업
<a name="iam_code_examples_actions"></a>

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

이들 발췌문은 IAM API를 호출하며, 컨텍스트에서 실행되어야 하는 더 큰 프로그램에서 발췌한 코드입니다. [AWS SDKs를 사용한 IAM 시나리오](iam_code_examples_scenarios.md)에서 컨텍스트에 맞는 작업을 볼 수 있습니다.

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

**Topics**
+ [`AddClientIdToOpenIdConnectProvider`](iam_example_iam_AddClientIdToOpenIdConnectProvider_section.md)
+ [`AddRoleToInstanceProfile`](iam_example_iam_AddRoleToInstanceProfile_section.md)
+ [`AddUserToGroup`](iam_example_iam_AddUserToGroup_section.md)
+ [`AttachGroupPolicy`](iam_example_iam_AttachGroupPolicy_section.md)
+ [`AttachRolePolicy`](iam_example_iam_AttachRolePolicy_section.md)
+ [`AttachUserPolicy`](iam_example_iam_AttachUserPolicy_section.md)
+ [`ChangePassword`](iam_example_iam_ChangePassword_section.md)
+ [`CreateAccessKey`](iam_example_iam_CreateAccessKey_section.md)
+ [`CreateAccountAlias`](iam_example_iam_CreateAccountAlias_section.md)
+ [`CreateGroup`](iam_example_iam_CreateGroup_section.md)
+ [`CreateInstanceProfile`](iam_example_iam_CreateInstanceProfile_section.md)
+ [`CreateLoginProfile`](iam_example_iam_CreateLoginProfile_section.md)
+ [`CreateOpenIdConnectProvider`](iam_example_iam_CreateOpenIdConnectProvider_section.md)
+ [`CreatePolicy`](iam_example_iam_CreatePolicy_section.md)
+ [`CreatePolicyVersion`](iam_example_iam_CreatePolicyVersion_section.md)
+ [`CreateRole`](iam_example_iam_CreateRole_section.md)
+ [`CreateSAMLProvider`](iam_example_iam_CreateSAMLProvider_section.md)
+ [`CreateServiceLinkedRole`](iam_example_iam_CreateServiceLinkedRole_section.md)
+ [`CreateUser`](iam_example_iam_CreateUser_section.md)
+ [`CreateVirtualMfaDevice`](iam_example_iam_CreateVirtualMfaDevice_section.md)
+ [`DeactivateMfaDevice`](iam_example_iam_DeactivateMfaDevice_section.md)
+ [`DeleteAccessKey`](iam_example_iam_DeleteAccessKey_section.md)
+ [`DeleteAccountAlias`](iam_example_iam_DeleteAccountAlias_section.md)
+ [`DeleteAccountPasswordPolicy`](iam_example_iam_DeleteAccountPasswordPolicy_section.md)
+ [`DeleteGroup`](iam_example_iam_DeleteGroup_section.md)
+ [`DeleteGroupPolicy`](iam_example_iam_DeleteGroupPolicy_section.md)
+ [`DeleteInstanceProfile`](iam_example_iam_DeleteInstanceProfile_section.md)
+ [`DeleteLoginProfile`](iam_example_iam_DeleteLoginProfile_section.md)
+ [`DeleteOpenIdConnectProvider`](iam_example_iam_DeleteOpenIdConnectProvider_section.md)
+ [`DeletePolicy`](iam_example_iam_DeletePolicy_section.md)
+ [`DeletePolicyVersion`](iam_example_iam_DeletePolicyVersion_section.md)
+ [`DeleteRole`](iam_example_iam_DeleteRole_section.md)
+ [`DeleteRolePermissionsBoundary`](iam_example_iam_DeleteRolePermissionsBoundary_section.md)
+ [`DeleteRolePolicy`](iam_example_iam_DeleteRolePolicy_section.md)
+ [`DeleteSAMLProvider`](iam_example_iam_DeleteSAMLProvider_section.md)
+ [`DeleteServerCertificate`](iam_example_iam_DeleteServerCertificate_section.md)
+ [`DeleteServiceLinkedRole`](iam_example_iam_DeleteServiceLinkedRole_section.md)
+ [`DeleteSigningCertificate`](iam_example_iam_DeleteSigningCertificate_section.md)
+ [`DeleteUser`](iam_example_iam_DeleteUser_section.md)
+ [`DeleteUserPermissionsBoundary`](iam_example_iam_DeleteUserPermissionsBoundary_section.md)
+ [`DeleteUserPolicy`](iam_example_iam_DeleteUserPolicy_section.md)
+ [`DeleteVirtualMfaDevice`](iam_example_iam_DeleteVirtualMfaDevice_section.md)
+ [`DetachGroupPolicy`](iam_example_iam_DetachGroupPolicy_section.md)
+ [`DetachRolePolicy`](iam_example_iam_DetachRolePolicy_section.md)
+ [`DetachUserPolicy`](iam_example_iam_DetachUserPolicy_section.md)
+ [`EnableMfaDevice`](iam_example_iam_EnableMfaDevice_section.md)
+ [`GenerateCredentialReport`](iam_example_iam_GenerateCredentialReport_section.md)
+ [`GenerateServiceLastAccessedDetails`](iam_example_iam_GenerateServiceLastAccessedDetails_section.md)
+ [`GetAccessKeyLastUsed`](iam_example_iam_GetAccessKeyLastUsed_section.md)
+ [`GetAccountAuthorizationDetails`](iam_example_iam_GetAccountAuthorizationDetails_section.md)
+ [`GetAccountPasswordPolicy`](iam_example_iam_GetAccountPasswordPolicy_section.md)
+ [`GetAccountSummary`](iam_example_iam_GetAccountSummary_section.md)
+ [`GetContextKeysForCustomPolicy`](iam_example_iam_GetContextKeysForCustomPolicy_section.md)
+ [`GetContextKeysForPrincipalPolicy`](iam_example_iam_GetContextKeysForPrincipalPolicy_section.md)
+ [`GetCredentialReport`](iam_example_iam_GetCredentialReport_section.md)
+ [`GetGroup`](iam_example_iam_GetGroup_section.md)
+ [`GetGroupPolicy`](iam_example_iam_GetGroupPolicy_section.md)
+ [`GetInstanceProfile`](iam_example_iam_GetInstanceProfile_section.md)
+ [`GetLoginProfile`](iam_example_iam_GetLoginProfile_section.md)
+ [`GetOpenIdConnectProvider`](iam_example_iam_GetOpenIdConnectProvider_section.md)
+ [`GetPolicy`](iam_example_iam_GetPolicy_section.md)
+ [`GetPolicyVersion`](iam_example_iam_GetPolicyVersion_section.md)
+ [`GetRole`](iam_example_iam_GetRole_section.md)
+ [`GetRolePolicy`](iam_example_iam_GetRolePolicy_section.md)
+ [`GetSamlProvider`](iam_example_iam_GetSamlProvider_section.md)
+ [`GetServerCertificate`](iam_example_iam_GetServerCertificate_section.md)
+ [`GetServiceLastAccessedDetails`](iam_example_iam_GetServiceLastAccessedDetails_section.md)
+ [`GetServiceLastAccessedDetailsWithEntities`](iam_example_iam_GetServiceLastAccessedDetailsWithEntities_section.md)
+ [`GetServiceLinkedRoleDeletionStatus`](iam_example_iam_GetServiceLinkedRoleDeletionStatus_section.md)
+ [`GetUser`](iam_example_iam_GetUser_section.md)
+ [`GetUserPolicy`](iam_example_iam_GetUserPolicy_section.md)
+ [`ListAccessKeys`](iam_example_iam_ListAccessKeys_section.md)
+ [`ListAccountAliases`](iam_example_iam_ListAccountAliases_section.md)
+ [`ListAttachedGroupPolicies`](iam_example_iam_ListAttachedGroupPolicies_section.md)
+ [`ListAttachedRolePolicies`](iam_example_iam_ListAttachedRolePolicies_section.md)
+ [`ListAttachedUserPolicies`](iam_example_iam_ListAttachedUserPolicies_section.md)
+ [`ListEntitiesForPolicy`](iam_example_iam_ListEntitiesForPolicy_section.md)
+ [`ListGroupPolicies`](iam_example_iam_ListGroupPolicies_section.md)
+ [`ListGroups`](iam_example_iam_ListGroups_section.md)
+ [`ListGroupsForUser`](iam_example_iam_ListGroupsForUser_section.md)
+ [`ListInstanceProfiles`](iam_example_iam_ListInstanceProfiles_section.md)
+ [`ListInstanceProfilesForRole`](iam_example_iam_ListInstanceProfilesForRole_section.md)
+ [`ListMfaDevices`](iam_example_iam_ListMfaDevices_section.md)
+ [`ListOpenIdConnectProviders`](iam_example_iam_ListOpenIdConnectProviders_section.md)
+ [`ListPolicies`](iam_example_iam_ListPolicies_section.md)
+ [`ListPolicyVersions`](iam_example_iam_ListPolicyVersions_section.md)
+ [`ListRolePolicies`](iam_example_iam_ListRolePolicies_section.md)
+ [`ListRoleTags`](iam_example_iam_ListRoleTags_section.md)
+ [`ListRoles`](iam_example_iam_ListRoles_section.md)
+ [`ListSAMLProviders`](iam_example_iam_ListSAMLProviders_section.md)
+ [`ListServerCertificates`](iam_example_iam_ListServerCertificates_section.md)
+ [`ListSigningCertificates`](iam_example_iam_ListSigningCertificates_section.md)
+ [`ListUserPolicies`](iam_example_iam_ListUserPolicies_section.md)
+ [`ListUserTags`](iam_example_iam_ListUserTags_section.md)
+ [`ListUsers`](iam_example_iam_ListUsers_section.md)
+ [`ListVirtualMfaDevices`](iam_example_iam_ListVirtualMfaDevices_section.md)
+ [`PutGroupPolicy`](iam_example_iam_PutGroupPolicy_section.md)
+ [`PutRolePermissionsBoundary`](iam_example_iam_PutRolePermissionsBoundary_section.md)
+ [`PutRolePolicy`](iam_example_iam_PutRolePolicy_section.md)
+ [`PutUserPermissionsBoundary`](iam_example_iam_PutUserPermissionsBoundary_section.md)
+ [`PutUserPolicy`](iam_example_iam_PutUserPolicy_section.md)
+ [`RemoveClientIdFromOpenIdConnectProvider`](iam_example_iam_RemoveClientIdFromOpenIdConnectProvider_section.md)
+ [`RemoveRoleFromInstanceProfile`](iam_example_iam_RemoveRoleFromInstanceProfile_section.md)
+ [`RemoveUserFromGroup`](iam_example_iam_RemoveUserFromGroup_section.md)
+ [`ResyncMfaDevice`](iam_example_iam_ResyncMfaDevice_section.md)
+ [`SetDefaultPolicyVersion`](iam_example_iam_SetDefaultPolicyVersion_section.md)
+ [`TagRole`](iam_example_iam_TagRole_section.md)
+ [`TagUser`](iam_example_iam_TagUser_section.md)
+ [`UntagRole`](iam_example_iam_UntagRole_section.md)
+ [`UntagUser`](iam_example_iam_UntagUser_section.md)
+ [`UpdateAccessKey`](iam_example_iam_UpdateAccessKey_section.md)
+ [`UpdateAccountPasswordPolicy`](iam_example_iam_UpdateAccountPasswordPolicy_section.md)
+ [`UpdateAssumeRolePolicy`](iam_example_iam_UpdateAssumeRolePolicy_section.md)
+ [`UpdateGroup`](iam_example_iam_UpdateGroup_section.md)
+ [`UpdateLoginProfile`](iam_example_iam_UpdateLoginProfile_section.md)
+ [`UpdateOpenIdConnectProviderThumbprint`](iam_example_iam_UpdateOpenIdConnectProviderThumbprint_section.md)
+ [`UpdateRole`](iam_example_iam_UpdateRole_section.md)
+ [`UpdateRoleDescription`](iam_example_iam_UpdateRoleDescription_section.md)
+ [`UpdateSamlProvider`](iam_example_iam_UpdateSamlProvider_section.md)
+ [`UpdateServerCertificate`](iam_example_iam_UpdateServerCertificate_section.md)
+ [`UpdateSigningCertificate`](iam_example_iam_UpdateSigningCertificate_section.md)
+ [`UpdateUser`](iam_example_iam_UpdateUser_section.md)
+ [`UploadServerCertificate`](iam_example_iam_UploadServerCertificate_section.md)
+ [`UploadSigningCertificate`](iam_example_iam_UploadSigningCertificate_section.md)

# CLI로 `AddClientIdToOpenIdConnectProvider` 사용
<a name="iam_example_iam_AddClientIdToOpenIdConnectProvider_section"></a>

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

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

**AWS CLI**  
**OIDC(Open-ID Connect) 제공업체에 클라이언트 ID(대상) 추가**  
다음 `add-client-id-to-open-id-connect-provider` 명령은 `server.example.com`이라는 OIDC 제공업체에게 클라이언트 ID `my-application-ID`를 추가합니다.  

```
aws iam add-client-id-to-open-id-connect-provider \
    --client-id my-application-ID \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/server.example.com
```
이 명령은 출력을 생성하지 않습니다.  
OIDC 제공업체를 생성하려면 `create-open-id-connect-provider` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM에서 OIDC(OpenID Connect) ID 제공업체 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [AddClientIdToOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/add-client-id-to-open-id-connect-provider.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 클라이언트 ID 또는 대상 `my-application-ID`를 `server.example.com`이라는 기존 OIDC 제공업체에 추가합니다.**  

```
Add-IAMClientIDToOpenIDConnectProvider -ClientID "my-application-ID" -OpenIDConnectProviderARN "arn:aws:iam::123456789012:oidc-provider/server.example.com"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [AddClientIdToOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 클라이언트 ID 또는 대상 `my-application-ID`를 `server.example.com`이라는 기존 OIDC 제공업체에 추가합니다.**  

```
Add-IAMClientIDToOpenIDConnectProvider -ClientID "my-application-ID" -OpenIDConnectProviderARN "arn:aws:iam::123456789012:oidc-provider/server.example.com"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AddClientIdToOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `AddRoleToInstanceProfile` 사용
<a name="iam_example_iam_AddRoleToInstanceProfile_section"></a>

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

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

**AWS CLI**  
**인스턴스 프로파일에 역할 추가**  
다음 `add-role-to-instance-profile` 명령은 이름이 `Webserver`인 인스턴스 프로파일에 이름이 `S3Access`인 역할을 추가합니다.  

```
aws iam add-role-to-instance-profile \
    --role-name S3Access \
    --instance-profile-name Webserver
```
이 명령은 출력을 생성하지 않습니다.  
인스턴스 프로파일을 생성하려면 `create-instance-profile` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 역할을 사용하여 Amazon EC2 인스턴스에서 실행되는 애플리케이션에 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [AddRoleToInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/add-role-to-instance-profile.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 `webserver`라는 기존 인스턴스 프로파일에 `S3Access`라는 역할을 추가합니다. 인스턴스 프로파일을 생성하려면 `New-IAMInstanceProfile` 명령을 사용합니다. 이 명령을 사용하여 인스턴스 프로파일을 생성하고 이를 역할과 연결한 후 EC2 인스턴스에 연결할 수 있습니다. 이를 수행하려면 `InstanceProfile_Arn` 또는 `InstanceProfile-Name` 파라미터와 함께 `New-EC2Instance` cmdlet을 사용하여 새 인스턴스를 시작합니다.**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [AddRoleToInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 `webserver`라는 기존 인스턴스 프로파일에 `S3Access`라는 역할을 추가합니다. 인스턴스 프로파일을 생성하려면 `New-IAMInstanceProfile` 명령을 사용합니다. 이 명령을 사용하여 인스턴스 프로파일을 생성하고 이를 역할과 연결한 후 EC2 인스턴스에 연결할 수 있습니다. 이를 수행하려면 `InstanceProfile_Arn` 또는 `InstanceProfile-Name` 파라미터와 함께 `New-EC2Instance` cmdlet을 사용하여 새 인스턴스를 시작합니다.**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AddRoleToInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `AddUserToGroup` 사용
<a name="iam_example_iam_AddUserToGroup_section"></a>

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

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

**AWS CLI**  
**IAM 그룹에 사용자 추가**  
다음 `add-user-to-group` 명령은 이름이 `Admins`인 IAM 그룹에 이름이 `Bob`인 IAM 사용자를 추가합니다.  

```
aws iam add-user-to-group \
    --user-name Bob \
    --group-name Admins
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자 그룹에서 사용자 추가 및 제거](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_add-remove-users.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [AddUserToGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/add-user-to-group.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 `Bob`이라는 사용자를 `Admins`라는 그룹에 추가합니다.**  

```
Add-IAMUserToGroup -UserName "Bob" -GroupName "Admins"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [AddUserToGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 `Bob`이라는 사용자를 `Admins`라는 그룹에 추가합니다.**  

```
Add-IAMUserToGroup -UserName "Bob" -GroupName "Admins"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AddUserToGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `AttachGroupPolicy` 사용
<a name="iam_example_iam_AttachGroupPolicy_section"></a>

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

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

**AWS CLI**  
**IAM 그룹에 관리형 정책 연결**  
다음 `attach-group-policy` 명령은 라는 AWS 관리형 정책을 라는 `ReadOnlyAccess` IAM 그룹에 연결합니다`Finance`.  

```
aws iam attach-group-policy \
    --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess \
    --group-name Finance
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [관리형 정책과 인라인 정책](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI  명령 참조의 [AttachGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-group-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `TesterPolicy`라는 고객 관리형 정책을 IAM 그룹 `Testers`에 연결합니다. 해당 그룹의 사용자는 해당 정책의 기본 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**예제 2:이 예제에서는 라는 AWS 관리형 정책을 IAM 그룹 `AdministratorAccess`에 연결합니다`Admins`. 해당 그룹의 사용자는 해당 정책의 최신 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMGroupPolicy -GroupName Admins -PolicyArn arn:aws:iam::aws:policy/AdministratorAccess
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [AttachGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `TesterPolicy`라는 고객 관리형 정책을 IAM 그룹 `Testers`에 연결합니다. 해당 그룹의 사용자는 해당 정책의 기본 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**예제 2:이 예제에서는 라는 AWS 관리형 정책을 IAM 그룹 `AdministratorAccess`에 연결합니다`Admins`. 해당 그룹의 사용자는 해당 정책의 최신 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMGroupPolicy -GroupName Admins -PolicyArn arn:aws:iam::aws:policy/AdministratorAccess
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AttachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Attach an IAM policy to a role.
    /// </summary>
    /// <param name="policyArn">The policy to attach.</param>
    /// <param name="roleName">The role that the policy will be attached to.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AttachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.AttachRolePolicyAsync(new AttachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/AttachRolePolicy)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_attach_role_policy
#
# This function attaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_attach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_attach_role_policy"
    echo "Attaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam attach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports attach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API 세부 정보는 **AWS CLI  명령 참조의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::attachRolePolicy(const Aws::String &roleName,
                                   const Aws::String &policyArn,
                                   const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::ListAttachedRolePoliciesRequest list_request;
    list_request.SetRoleName(roleName);

    bool done = false;
    while (!done) {
        auto list_outcome = iam.ListAttachedRolePolicies(list_request);
        if (!list_outcome.IsSuccess()) {
            std::cerr << "Failed to list attached policies of role " <<
                      roleName << ": " << list_outcome.GetError().GetMessage() <<
                      std::endl;
            return false;
        }

        const auto &policies = list_outcome.GetResult().GetAttachedPolicies();
        if (std::any_of(policies.cbegin(), policies.cend(),
                        [=](const Aws::IAM::Model::AttachedPolicy &policy) {
                                return policy.GetPolicyArn() == policyArn;
                        })) {
            std::cout << "Policy " << policyArn <<
                      " is already attached to role " << roleName << std::endl;
            return true;
        }

        done = !list_outcome.GetResult().GetIsTruncated();
        list_request.SetMarker(list_outcome.GetResult().GetMarker());
    }

    Aws::IAM::Model::AttachRolePolicyRequest request;
    request.SetRoleName(roleName);
    request.SetPolicyArn(policyArn);

    Aws::IAM::Model::AttachRolePolicyOutcome outcome = iam.AttachRolePolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to attach policy " << policyArn << " to role " <<
                  roleName << ": " << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully attached policy " << policyArn << " to role " <<
                  roleName << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/AttachRolePolicy)를 참조하세요.

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

**AWS CLI**  
**IAM 역할에 관리형 정책 연결**  
다음 `attach-role-policy` 명령은 라는 AWS 관리형 정책을 라는 `ReadOnlyAccess` IAM 역할에 연결합니다`ReadOnlyRole`.  

```
aws iam attach-role-policy \
    --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess \
    --role-name ReadOnlyRole
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [관리형 정책과 인라인 정책](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI  명령 참조의 [AttachRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-role-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// AttachRolePolicy attaches a policy to a role.
func (wrapper RoleWrapper) AttachRolePolicy(ctx context.Context, policyArn string, roleName string) error {
	_, err := wrapper.IamClient.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't attach policy %v to role %v. Here's why: %v\n", policyArn, roleName, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [AttachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.AttachRolePolicy)를 참조하십시오.

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

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

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.AttachedPolicy;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;
import java.util.List;

/**
 * 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 AttachRolePolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <roleName> <policyArn>\s

                Where:
                    roleName - A role name that you can obtain from the AWS Management Console.\s
                    policyArn - A policy ARN that you can obtain from the AWS Management Console.\s
                """;

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

        String roleName = args[0];
        String policyArn = args[1];

        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        attachIAMRolePolicy(iam, roleName, policyArn);
        iam.close();
    }

    public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) {
        try {
            ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
                    .roleName(roleName)
                    .build();

            ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
            List<AttachedPolicy> attachedPolicies = response.attachedPolicies();

            // Ensure that the policy is not attached to this role
            String polArn = "";
            for (AttachedPolicy policy : attachedPolicies) {
                polArn = policy.policyArn();
                if (polArn.compareTo(policyArn) == 0) {
                    System.out.println(roleName + " policy is already attached to this role.");
                    return;
                }
            }

            AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.attachRolePolicy(attachRequest);

            System.out.println("Successfully attached policy " + policyArn +
                    " to role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/AttachRolePolicy)를 참조하십시오.

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

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

```
import { AttachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 * @param {string} roleName
 */
export const attachRolePolicy = (policyArn, roleName) => {
  const command = new AttachRolePolicyCommand({
    PolicyArn: policyArn,
    RoleName: roleName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-attaching-role-policy)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/AttachRolePolicyCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var paramsRoleList = {
  RoleName: process.argv[2],
};

iam.listAttachedRolePolicies(paramsRoleList, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var myRolePolicies = data.AttachedPolicies;
    myRolePolicies.forEach(function (val, index, array) {
      if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") {
        console.log(
          "AmazonDynamoDBFullAccess is already attached to this role."
        );
        process.exit();
      }
    });
    var params = {
      PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",
      RoleName: process.argv[2],
    };
    iam.attachRolePolicy(params, function (err, data) {
      if (err) {
        console.log("Unable to attach policy to role", err);
      } else {
        console.log("Role attached successfully");
      }
    });
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-attaching-role-policy)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/AttachRolePolicy)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun attachIAMRolePolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        ListAttachedRolePoliciesRequest {
            roleName = roleNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAttachedRolePolicies(request)
        val attachedPolicies = response.attachedPolicies

        // Ensure that the policy is not attached to this role.
        val checkStatus: Int
        if (attachedPolicies != null) {
            checkStatus = checkList(attachedPolicies, policyArnVal)
            if (checkStatus == -1) {
                return
            }
        }

        val policyRequest =
            AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policyArnVal
            }
        iamClient.attachRolePolicy(policyRequest)
        println("Successfully attached policy $policyArnVal to role $roleNameVal")
    }
}

fun checkList(
    attachedPolicies: List<AttachedPolicy>,
    policyArnVal: String,
): Int {
    for (policy in attachedPolicies) {
        val polArn = policy.policyArn.toString()

        if (polArn.compareTo(policyArnVal) == 0) {
            println("The policy is already attached to this role.")
            return -1
        }
    }
    return 0
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [AttachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

$assumeRolePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{$user['Arn']}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }";
$assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument);
echo "Created role: {$assumeRoleRole['RoleName']}\n";

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

$service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);

    public function attachRolePolicy($roleName, $policyArn)
    {
        return $this->customWaiter(function () use ($roleName, $policyArn) {
            $this->iamClient->attachRolePolicy([
                'PolicyArn' => $policyArn,
                'RoleName' => $roleName,
            ]);
        });
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/AttachRolePolicy)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제에서는 라는 AWS 관리형 정책을 IAM 역할 `SecurityAudit`에 연결합니다`CoSecurityAuditors`. 해당 역할을 수임하는 사용자는 해당 정책의 최신 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMRolePolicy -RoleName CoSecurityAuditors -PolicyArn arn:aws:iam::aws:policy/SecurityAudit
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [AttachRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제에서는 라는 AWS 관리형 정책을 IAM 역할 `SecurityAudit`에 연결합니다`CoSecurityAuditors`. 해당 역할을 수임하는 사용자는 해당 정책의 최신 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMRolePolicy -RoleName CoSecurityAuditors -PolicyArn arn:aws:iam::aws:policy/SecurityAudit
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AttachRolePolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
Boto3 정책 객체를 사용하여 역할에 정책을 연결합니다.  

```
def attach_to_role(role_name, policy_arn):
    """
    Attaches a policy to a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Policy(policy_arn).attach_role(RoleName=role_name)
        logger.info("Attached policy %s to role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name)
        raise
```
Boto3 역할 객체를 사용하여 역할에 정책을 연결합니다.  

```
def attach_policy(role_name, policy_arn):
    """
    Attaches a policy to a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Role(role_name).attach_policy(PolicyArn=policy_arn)
        logger.info("Attached policy %s to role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachRolePolicy)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 역할 정책을 나열, 생성, 연결 및 분리합니다.  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachRolePolicy)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn attach_role_policy(
    client: &iamClient,
    role: &Role,
    policy: &Policy,
) -> Result<AttachRolePolicyOutput, SdkError<AttachRolePolicyError>> {
    client
        .attach_role_policy()
        .role_name(role.role_name())
        .policy_arn(policy.arn().unwrap_or_default())
        .send()
        .await
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [AttachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_role_policy)을 참조하세요.

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

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

```
    TRY.
        lo_iam->attachrolepolicy(
          iv_rolename = iv_role_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy attached to role successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role or policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy attachment limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 [AWS SDK for SAP ABAP API 참조](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)의 *AttachRolePolicy*를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func attachRolePolicy(role: String, policyArn: String) async throws {
        let input = AttachRolePolicyInput(
            policyArn: policyArn,
            roleName: role
        )
        do {
            _ = try await client.attachRolePolicy(input: input)
        } catch {
            print("ERROR: Attaching a role policy:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [AttachRolePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/attachrolepolicy(input:))를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 

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

**AWS CLI**  
**IAM 사용자에게 관리형 정책 연결**  
다음 `attach-user-policy` 명령은 라는 AWS 관리형 정책을 라는 `AdministratorAccess` IAM 사용자에게 연결합니다`Alice`.  

```
aws iam attach-user-policy \
    --policy-arn arn:aws:iam::aws:policy/AdministratorAccess \
    --user-name Alice
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [관리형 정책과 인라인 정책](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI  명령 참조의 [AttachUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-user-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제에서는 라는 AWS 관리형 정책을 IAM 사용자 `AmazonCognitoPowerUser`에 연결합니다`Bob`. 사용자는 해당 정책의 최신 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [AttachUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제에서는 라는 AWS 관리형 정책을 IAM 사용자 `AmazonCognitoPowerUser`에 연결합니다`Bob`. 사용자는 해당 정책의 최신 버전에 정의된 권한의 영향을 즉시 받습니다.**  

```
Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [AttachUserPolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def attach_policy(user_name, policy_arn):
    """
    Attaches a policy to a user.

    :param user_name: The name of the user.
    :param policy_arn: The Amazon Resource Name (ARN) of the policy.
    """
    try:
        iam.User(user_name).attach_policy(PolicyArn=policy_arn)
        logger.info("Attached policy %s to user %s.", policy_arn, user_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to user %s.", policy_arn, user_name)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [AttachUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachUserPolicy)를 참조하세요.

------
#### [ Ruby ]

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

```
  # Attaches a policy to a user
  #
  # @param user_name [String] The name of the user
  # @param policy_arn [String] The Amazon Resource Name (ARN) of the policy
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_user(user_name, policy_arn)
    @iam_client.attach_user_policy(
      user_name: user_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to user: #{e.message}")
    false
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [AttachUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachUserPolicy)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn attach_user_policy(
    client: &iamClient,
    user_name: &str,
    policy_arn: &str,
) -> Result<(), iamError> {
    client
        .attach_user_policy()
        .user_name(user_name)
        .policy_arn(policy_arn)
        .send()
        .await?;

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [AttachUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_user_policy)을 참조하세요.

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

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

```
    TRY.
        lo_iam->attachuserpolicy(
          iv_username = iv_user_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy attached to user successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User or policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy attachment limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 [AWS SDK for SAP ABAP API 참조](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)의 *AttachUserPolicy*를 참조하세요.

------

# CLI로 `ChangePassword` 사용
<a name="iam_example_iam_ChangePassword_section"></a>

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

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

**AWS CLI**  
**IAM 사용자의 암호 변경**  
IAM 사용자의 암호를 변경하려면 `--cli-input-json` 파라미터를 사용하여 기존 암호와 새 암호가 포함된 JSON 파일을 전달하는 것이 좋습니다. 이 방법을 사용하면 영숫자가 아닌 문자가 포함된 강력한 암호를 사용할 수 있습니다. 명령줄 파라미터로 전달할 때 영숫자가 아닌 문자가 포함된 암호는 사용하기 어려울 수 있습니다. `--cli-input-json` 파라미터를 사용하려면 다음 예와 같이 `--generate-cli-skeleton` 파라미터와 함께 `change-password` 명령을 사용하는 것으로 시작합니다.  

```
aws iam change-password \
    --generate-cli-skeleton > change-password.json
```
이전 명령은 이전 암호와 새 암호를 입력하는 데 사용할 수 있는 change-password.json이라는 JSON 파일을 생성합니다. 예를 들어 파일은 다음과 같을 수 있습니다.  

```
{
    "OldPassword": "3s0K_;xh4~8XXI",
    "NewPassword": "]35d/{pB9Fo9wJ"
}
```
다음으로 암호를 변경하려면 `change-password` 명령을 다시 사용하되 이번에는 `--cli-input-json` 파라미터를 전달하여 JSON 파일을 지정합니다. 다음 `change-password` 명령은 change-password.json이라는 JSON 파일과 함께 `--cli-input-json` 파라미터를 사용합니다.  

```
aws iam change-password \
    --cli-input-json file://change-password.json
```
이 명령은 출력을 생성하지 않습니다.  
이 명령은 IAM 사용자만 호출할 수 있습니다. AWS 계정(루트) 자격 증명을 사용하여이 명령을 호출하면 명령이 `InvalidUserType` 오류를 반환합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자가 자신의 암호를 변경하는 방법](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_user-change-own.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ChangePassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/change-password.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 명령을 실행하는 사용자의 암호를 변경합니다. 이 명령은 IAM 사용자만 호출할 수 있습니다. AWS 계정(루트) 자격 증명으로 로그인할 때이 명령이 호출되면 명령이 `InvalidUserType` 오류를 반환합니다.**  

```
Edit-IAMPassword -OldPassword "MyOldP@ssw0rd" -NewPassword "MyNewP@ssw0rd"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ChangePassword](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 명령을 실행하는 사용자의 암호를 변경합니다. 이 명령은 IAM 사용자만 호출할 수 있습니다. AWS 계정(루트) 자격 증명으로 로그인할 때이 명령이 호출되면 명령이 `InvalidUserType` 오류를 반환합니다.**  

```
Edit-IAMPassword -OldPassword "MyOldP@ssw0rd" -NewPassword "MyNewP@ssw0rd"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ChangePassword](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](iam_example_iam_Scenario_CreateUserAssumeRole_section.md) 
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 
+  [ 액세스 키 관리](iam_example_iam_Scenario_ManageAccessKeys_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// Create an IAM access key for a user.
    /// </summary>
    /// <param name="userName">The username for which to create the IAM access
    /// key.</param>
    /// <returns>The AccessKey.</returns>
    public async Task<AccessKey> CreateAccessKeyAsync(string userName)
    {
        var response = await _IAMService.CreateAccessKeyAsync(new CreateAccessKeyRequest
        {
            UserName = userName,
        });

        return response.AccessKey;

    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateAccessKey)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_create_user_access_key
#
# This function creates an IAM access key for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#       [-f file_name] -- The optional file name for the access key output.
#
# Returns:
#       [access_key_id access_key_secret]
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user_access_key() {
  local user_name file_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) key pair."
    echo "  -u user_name   The name of the IAM user."
    echo "  [-f file_name]   Optional file name for the access key output."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:f:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      f) file_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam create-access-key \
    --user-name "$user_name" \
    --output text)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  fi

  if [[ -n "$file_name" ]]; then
    echo "$response" >"$file_name"
  fi

  local key_id key_secret
  # shellcheck disable=SC2086
  key_id=$(echo $response | cut -f 2 -d ' ')
  # shellcheck disable=SC2086
  key_secret=$(echo $response | cut -f 4 -d ' ')

  echo "$key_id $key_secret"

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateAccessKey)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
Aws::String AwsDoc::IAM::createAccessKey(const Aws::String &userName,
                                         const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::CreateAccessKeyRequest request;
    request.SetUserName(userName);

    Aws::String result;
    Aws::IAM::Model::CreateAccessKeyOutcome outcome = iam.CreateAccessKey(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error creating access key for IAM user " << userName
                  << ":" << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        const auto &accessKey = outcome.GetResult().GetAccessKey();
        std::cout << "Successfully created access key for IAM user " <<
                  userName << std::endl << "  aws_access_key_id = " <<
                  accessKey.GetAccessKeyId() << std::endl <<
                  " aws_secret_access_key = " << accessKey.GetSecretAccessKey() <<
                  std::endl;
        result = accessKey.GetAccessKeyId();
    }

    return result;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccessKey)를 참조하세요.

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

**AWS CLI**  
**IAM 사용자의 액세스 키 생성**  
다음 `create-access-key` 명령은 이름이 `Bob`인 IAM 사용자의 액세스 키(액세스 키 ID 및 시크릿 액세스 키)를 생성합니다.  

```
aws iam create-access-key \
    --user-name Bob
```
출력:  

```
{
    "AccessKey": {
        "UserName": "Bob",
        "Status": "Active",
        "CreateDate": "2015-03-09T18:39:23.411Z",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY",
        "AccessKeyId": "AKIAIOSFODNN7EXAMPLE"
    }
}
```
시크릿 액세스 키를 안전한 위치에 저장합니다. 손실된 경우 복구할 수 없으며, 새로운 액세스 키를 생성해야 합니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자의 액세스 키 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateAccessKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-access-key.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// CreateAccessKeyPair creates an access key for a user. The returned access key contains
// the ID and secret credentials needed to use the key.
func (wrapper UserWrapper) CreateAccessKeyPair(ctx context.Context, userName string) (*types.AccessKey, error) {
	var key *types.AccessKey
	result, err := wrapper.IamClient.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{
		UserName: aws.String(userName)})
	if err != nil {
		log.Printf("Couldn't create access key pair for user %v. Here's why: %v\n", userName, err)
	} else {
		key = result.AccessKey
	}
	return key, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [CreateAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateAccessKey)를 참조하십시오.

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

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

```
import software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest;
import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 CreateAccessKey {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                   <user>\s

                Where:
                   user - An AWS IAM user that you can obtain from the AWS Management Console.
                """;

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

        String user = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        String keyId = createIAMAccessKey(iam, user);
        System.out.println("The Key Id is " + keyId);
        iam.close();
    }

    public static String createIAMAccessKey(IamClient iam, String user) {
        try {
            CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
                    .userName(user)
                    .build();

            CreateAccessKeyResponse response = iam.createAccessKey(request);
            return response.accessKey().accessKeyId();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccessKey)를 참조하십시오.

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

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

```
import { CreateAccessKeyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} userName
 */
export const createAccessKey = (userName) => {
  const command = new CreateAccessKeyCommand({ UserName: userName });
  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-creating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccessKeyCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.createAccessKey({ UserName: "IAM_USER_NAME" }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.AccessKey);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-creating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreateAccessKey)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun createIAMAccessKey(user: String?): String {
    val request =
        CreateAccessKeyRequest {
            userName = user
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createAccessKey(request)
        return response.accessKey?.accessKeyId.toString()
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 새 액세스 키와 시크릿 액세스 키 페어를 생성하여 사용자 `David`에게 할당합니다. 이때만 `SecretAccessKey`를 얻을 수 있으므로 `AccessKeyId` 및 `SecretAccessKey` 값을 파일에 저장해야 합니다. 나중에 검색할 수 없습니다. 보안 키를 잃어버린 경우 새로운 액세스 키 페어를 생성해야 합니다.**  

```
New-IAMAccessKey -UserName David
```
**출력:**  

```
AccessKeyId     : AKIAIOSFODNN7EXAMPLE
CreateDate      : 4/13/2015 1:00:42 PM
SecretAccessKey : wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Status          : Active
UserName        : David
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateAccessKey](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 새 액세스 키와 시크릿 액세스 키 페어를 생성하여 사용자 `David`에게 할당합니다. 이때만 `SecretAccessKey`를 얻을 수 있으므로 `AccessKeyId` 및 `SecretAccessKey` 값을 파일에 저장해야 합니다. 나중에 검색할 수 없습니다. 보안 키를 잃어버린 경우 새로운 액세스 키 페어를 생성해야 합니다.**  

```
New-IAMAccessKey -UserName David
```
**출력:**  

```
AccessKeyId     : AKIAIOSFODNN7EXAMPLE
CreateDate      : 4/13/2015 1:00:42 PM
SecretAccessKey : wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Status          : Active
UserName        : David
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateAccessKey](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def create_key(user_name):
    """
    Creates an access key for the specified user. Each user can have a
    maximum of two keys.

    :param user_name: The name of the user.
    :return: The created access key.
    """
    try:
        key_pair = iam.User(user_name).create_access_key_pair()
        logger.info(
            "Created access key pair for %s. Key ID is %s.",
            key_pair.user_name,
            key_pair.id,
        )
    except ClientError:
        logger.exception("Couldn't create access key pair for %s.", user_name)
        raise
    else:
        return key_pair
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 액세스 키를 나열, 생성, 비활성화 및 삭제합니다.  

```
# Manages access keys for IAM users
class AccessKeyManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'AccessKeyManager'
  end

  # Lists access keys for a user
  #
  # @param user_name [String] The name of the user.
  def list_access_keys(user_name)
    response = @iam_client.list_access_keys(user_name: user_name)
    if response.access_key_metadata.empty?
      @logger.info("No access keys found for user '#{user_name}'.")
    else
      response.access_key_metadata.map(&:access_key_id)
    end
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Error listing access keys: cannot find user '#{user_name}'.")
    []
  rescue StandardError => e
    @logger.error("Error listing access keys: #{e.message}")
    []
  end

  # Creates an access key for a user
  #
  # @param user_name [String] The name of the user.
  # @return [Boolean]
  def create_access_key(user_name)
    response = @iam_client.create_access_key(user_name: user_name)
    access_key = response.access_key
    @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}")
    access_key
  rescue Aws::IAM::Errors::LimitExceeded
    @logger.error('Error creating access key: limit exceeded. Cannot create more.')
    nil
  rescue StandardError => e
    @logger.error("Error creating access key: #{e.message}")
    nil
  end

  # Deactivates an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def deactivate_access_key(user_name, access_key_id)
    @iam_client.update_access_key(
      user_name: user_name,
      access_key_id: access_key_id,
      status: 'Inactive'
    )
    true
  rescue StandardError => e
    @logger.error("Error deactivating access key: #{e.message}")
    false
  end

  # Deletes an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def delete_access_key(user_name, access_key_id)
    @iam_client.delete_access_key(
      user_name: user_name,
      access_key_id: access_key_id
    )
    true
  rescue StandardError => e
    @logger.error("Error deleting access key: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccessKey)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn create_access_key(client: &iamClient, user_name: &str) -> Result<AccessKey, iamError> {
    let mut tries: i32 = 0;
    let max_tries: i32 = 10;

    let response: Result<CreateAccessKeyOutput, SdkError<CreateAccessKeyError>> = loop {
        match client.create_access_key().user_name(user_name).send().await {
            Ok(inner_response) => {
                break Ok(inner_response);
            }
            Err(e) => {
                tries += 1;
                if tries > max_tries {
                    break Err(e);
                }
                sleep(Duration::from_secs(2)).await;
            }
        }
    };

    Ok(response.unwrap().access_key.unwrap())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_access_key)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->createaccesskey(
          iv_username = iv_user_name ).
        MESSAGE 'Access key created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Maximum number of access keys reached.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateAccessKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func createAccessKey(userName: String) async throws -> IAMClientTypes.AccessKey {
        let input = CreateAccessKeyInput(
            userName: userName
        )
        do {
            let output = try await iamClient.createAccessKey(input: input)
            guard let accessKey = output.accessKey else {
                throw ServiceHandlerError.keyError
            }
            return accessKey
        } catch {
            print("ERROR: createAccessKey:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreateAccessKey](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createaccesskey(input:))를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [계정 관리](iam_example_iam_Scenario_AccountManagement_section.md) 

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::createAccountAlias(const Aws::String &aliasName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::CreateAccountAliasRequest request;
    request.SetAccountAlias(aliasName);

    Aws::IAM::Model::CreateAccountAliasOutcome outcome = iam.CreateAccountAlias(
            request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error creating account alias " << aliasName << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully created account alias " << aliasName <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccountAlias)를 참조하세요.

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

**AWS CLI**  
**계정 별칭 생성**  
다음 `create-account-alias` 명령은 AWS 계정의 별칭`examplecorp`을 생성합니다.  

```
aws iam create-account-alias \
    --account-alias examplecorp
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [AWS 계정 ID 및 별칭](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateAccountAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-account-alias.html)를 참조하세요.

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

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

```
import software.amazon.awssdk.services.iam.model.CreateAccountAliasRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 CreateAccountAlias {
    public static void main(String[] args) {
        final String usage = """
                Usage:
                    <alias>\s

                Where:
                    alias - The account alias to create (for example, myawsaccount).\s
                """;

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

        String alias = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        createIAMAccountAlias(iam, alias);
        iam.close();
        System.out.println("Done");
    }

    public static void createIAMAccountAlias(IamClient iam, String alias) {
        try {
            CreateAccountAliasRequest request = CreateAccountAliasRequest.builder()
                    .accountAlias(alias)
                    .build();

            iam.createAccountAlias(request);
            System.out.println("Successfully created account alias: " + alias);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccountAlias)를 참조하십시오.

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

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

```
import { CreateAccountAliasCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} alias - A unique name for the account alias.
 * @returns
 */
export const createAccountAlias = (alias) => {
  const command = new CreateAccountAliasCommand({
    AccountAlias: alias,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-creating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccountAliasCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.createAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-creating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreateAccountAlias)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun createIAMAccountAlias(alias: String) {
    val request =
        CreateAccountAliasRequest {
            accountAlias = alias
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.createAccountAlias(request)
        println("Successfully created account alias named $alias")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateAccountAlias](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제에서는 계정의 AWS 계정 별칭을 로 변경합니다`mycompanyaws`. 사용자 로그온 페이지의 주소가 https://mycompanyaws.signin.aws.amazon.com/console로 변경됩니다. 별칭 대신 계정 ID 번호를 사용하는 원래 URL(https://<accountidnumber>.signin.aws.amazon.com/console)은 계속 작동합니다. 하지만 이전에 정의된 별칭 기반 URL은 모두 작동이 중지됩니다.**  

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

**Tools for PowerShell V5**  
**예제 1:이 예제에서는 계정의 AWS 계정 별칭을 로 변경합니다`mycompanyaws`. 사용자 로그온 페이지의 주소가 https://mycompanyaws.signin.aws.amazon.com/console로 변경됩니다. 별칭 대신 계정 ID 번호를 사용하는 원래 URL(https://<accountidnumber>.signin.aws.amazon.com/console)은 계속 작동합니다. 하지만 이전에 정의된 별칭 기반 URL은 모두 작동이 중지됩니다.**  

```
New-IAMAccountAlias -AccountAlias mycompanyaws
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateAccountAlias](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def create_alias(alias):
    """
    Creates an alias for the current account. The alias can be used in place of the
    account ID in the sign-in URL. An account can have only one alias. When a new
    alias is created, it replaces any existing alias.

    :param alias: The alias to assign to the account.
    """

    try:
        iam.create_account_alias(AccountAlias=alias)
        logger.info("Created an alias '%s' for your account.", alias)
    except ClientError:
        logger.exception("Couldn't create alias '%s' for your account.", alias)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccountAlias)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
계정 별칭을 나열하고, 생성하고, 삭제합니다.  

```
class IAMAliasManager
  # Initializes the IAM client and logger
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists available AWS account aliases.
  def list_aliases
    response = @iam_client.list_account_aliases

    if response.account_aliases.count.positive?
      @logger.info('Account aliases are:')
      response.account_aliases.each { |account_alias| @logger.info("  #{account_alias}") }
    else
      @logger.info('No account aliases found.')
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing account aliases: #{e.message}")
  end

  # Creates an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to create.
  # @return [Boolean] true if the account alias was created; otherwise, false.
  def create_account_alias(account_alias)
    @iam_client.create_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating account alias: #{e.message}")
    false
  end

  # Deletes an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to delete.
  # @return [Boolean] true if the account alias was deleted; otherwise, false.
  def delete_account_alias(account_alias)
    @iam_client.delete_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting account alias: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccountAlias)를 참조하세요.

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

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

```
    TRY.
        lo_iam->createaccountalias(
          iv_accountalias = iv_account_alias ).
        MESSAGE 'Account alias created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'Account alias already exists.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Account alias limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateAccountAlias](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

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

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

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

**AWS CLI**  
**IAM 그룹을 생성하려면**  
다음 `create-group` 명령은 이름이 `Admins`인 IAM 그룹을 생성합니다.  

```
aws iam create-group \
    --group-name Admins
```
출력:  

```
{
    "Group": {
        "Path": "/",
        "CreateDate": "2015-03-09T20:30:24.940Z",
        "GroupId": "AIDGPMS9RO4H3FEXAMPLE",
        "Arn": "arn:aws:iam::123456789012:group/Admins",
        "GroupName": "Admins"
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자 그룹 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_create.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-group.html)을 참조하세요.

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

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

```
import { CreateGroupCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} groupName
 */
export const createGroup = async (groupName) => {
  const command = new CreateGroupCommand({ GroupName: groupName });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateGroupCommand)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Developers`라는 새 IAM 그룹을 생성합니다.**  

```
New-IAMGroup -GroupName Developers
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 4/14/2015 11:21:31 AM
GroupId    : QNEJ5PM4NFSQCEXAMPLE1
GroupName  : Developers
Path       : /
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Developers`라는 새 IAM 그룹을 생성합니다.**  

```
New-IAMGroup -GroupName Developers
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 4/14/2015 11:21:31 AM
GroupId    : QNEJ5PM4NFSQCEXAMPLE1
GroupName  : Developers
Path       : /
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](iam_example_cross_ResilientService_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// Create a policy, role, and profile that is associated with instances with a specified name.
    /// An instance's associated profile defines a role that is assumed by the
    /// instance.The role has attached policies that specify the AWS permissions granted to
    /// clients that run on the instance.
    /// </summary>
    /// <param name="policyName">Name to use for the policy.</param>
    /// <param name="roleName">Name to use for the role.</param>
    /// <param name="profileName">Name to use for the profile.</param>
    /// <param name="ssmOnlyPolicyFile">Path to a policy file for SSM.</param>
    /// <param name="awsManagedPolicies">AWS Managed policies to be attached to the role.</param>
    /// <returns>The Arn of the profile.</returns>
    public async Task<string> CreateInstanceProfileWithName(
        string policyName,
        string roleName,
        string profileName,
        string ssmOnlyPolicyFile,
        List<string>? awsManagedPolicies = null)
    {

        var assumeRoleDoc = "{" +
                                   "\"Version\": \"2012-10-17\"," +
                                   "\"Statement\": [{" +
                                        "\"Effect\": \"Allow\"," +
                                        "\"Principal\": {" +
                                        "\"Service\": [" +
                                            "\"ec2.amazonaws.com\"" +
                                        "]" +
                                        "}," +
                                   "\"Action\": \"sts:AssumeRole\"" +
                                   "}]" +
                               "}";

        var policyDocument = await File.ReadAllTextAsync(ssmOnlyPolicyFile);

        var policyArn = "";

        try
        {
            var createPolicyResult = await _amazonIam.CreatePolicyAsync(
                new CreatePolicyRequest
                {
                    PolicyName = policyName,
                    PolicyDocument = policyDocument
                });
            policyArn = createPolicyResult.Policy.Arn;
        }
        catch (EntityAlreadyExistsException)
        {
            // The policy already exists, so we look it up to get the Arn.
            var policiesPaginator = _amazonIam.Paginators.ListPolicies(
                new ListPoliciesRequest()
                {
                    Scope = PolicyScopeType.Local
                });
            // Get the entire list using the paginator.
            await foreach (var policy in policiesPaginator.Policies)
            {
                if (policy.PolicyName.Equals(policyName))
                {
                    policyArn = policy.Arn;
                }
            }

            if (policyArn == null)
            {
                throw new InvalidOperationException("Policy not found");
            }
        }

        try
        {
            await _amazonIam.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = assumeRoleDoc,
            });
            await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
            {
                RoleName = roleName,
                PolicyArn = policyArn
            });
            if (awsManagedPolicies != null)
            {
                foreach (var awsPolicy in awsManagedPolicies)
                {
                    await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
                    {
                        PolicyArn = $"arn:aws:iam::aws:policy/{awsPolicy}",
                        RoleName = roleName
                    });
                }
            }
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Role already exists.");
        }

        string profileArn = "";
        try
        {
            var profileCreateResponse = await _amazonIam.CreateInstanceProfileAsync(
                new CreateInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            // Allow time for the profile to be ready.
            profileArn = profileCreateResponse.InstanceProfile.Arn;
            Thread.Sleep(10000);
            await _amazonIam.AddRoleToInstanceProfileAsync(
                new AddRoleToInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });

        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Policy already exists.");
            var profileGetResponse = await _amazonIam.GetInstanceProfileAsync(
                new GetInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            profileArn = profileGetResponse.InstanceProfile.Arn;
        }
        return profileArn;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateInstanceProfile)을 참조하세요.

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

**AWS CLI**  
**인스턴스 프로파일 생성**  
다음 `create-instance-profile` 명령은 이름이 `Webserver`인 인스턴스 프로파일을 생성합니다.  

```
aws iam create-instance-profile \
    --instance-profile-name Webserver
```
출력:  

```
{
    "InstanceProfile": {
        "InstanceProfileId": "AIPAJMBYC7DLSPEXAMPLE",
        "Roles": [],
        "CreateDate": "2015-03-09T20:33:19.626Z",
        "InstanceProfileName": "Webserver",
        "Path": "/",
        "Arn": "arn:aws:iam::123456789012:instance-profile/Webserver"
    }
}
```
인스턴스 프로파일에 역할을 추가하려면 `add-role-to-instance-profile` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 역할을 사용하여 Amazon EC2 인스턴스에서 실행되는 애플리케이션에 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-instance-profile.html)을 참조하세요.

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

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

```
  const { InstanceProfile } = await iamClient.send(
    new CreateInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
    }),
  );
  await waitUntilInstanceProfileExists(
    { client: iamClient },
    { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName },
  );
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateInstanceProfileCommand)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `ProfileForDevEC2Instance`라는 새 IAM 인스턴스 프로파일을 생성합니다. `Add-IAMRoleToInstanceProfile` 명령을 별도로 실행하여 인스턴스에 권한을 제공하는 기존 IAM 역할과 인스턴스 프로파일을 연결해야 합니다. 마지막으로 EC2 인스턴스를 시작할 때 인스턴스 프로파일을 EC2 인스턴스에 연결합니다. 이를 수행하려면 `InstanceProfile_Arn` 또는 `InstanceProfile_Name` 파라미터와 함께 `New-EC2Instance` cmdlet을 사용합니다.**  

```
New-IAMInstanceProfile -InstanceProfileName ProfileForDevEC2Instance
```
**출력:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ProfileForDevEC2Instance
CreateDate          : 4/14/2015 11:31:39 AM
InstanceProfileId   : DYMFXL556EY46EXAMPLE1
InstanceProfileName : ProfileForDevEC2Instance
Path                : /
Roles               : {}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `ProfileForDevEC2Instance`라는 새 IAM 인스턴스 프로파일을 생성합니다. `Add-IAMRoleToInstanceProfile` 명령을 별도로 실행하여 인스턴스에 권한을 제공하는 기존 IAM 역할과 인스턴스 프로파일을 연결해야 합니다. 마지막으로 EC2 인스턴스를 시작할 때 인스턴스 프로파일을 EC2 인스턴스에 연결합니다. 이를 수행하려면 `InstanceProfile_Arn` 또는 `InstanceProfile_Name` 파라미터와 함께 `New-EC2Instance` cmdlet을 사용합니다.**  

```
New-IAMInstanceProfile -InstanceProfileName ProfileForDevEC2Instance
```
**출력:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ProfileForDevEC2Instance
CreateDate          : 4/14/2015 11:31:39 AM
InstanceProfileId   : DYMFXL556EY46EXAMPLE1
InstanceProfileName : ProfileForDevEC2Instance
Path                : /
Roles               : {}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateInstanceProfile](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예제에서는 정책, 역할, 인스턴스 프로파일을 생성하고 이를 모두 연결합니다.  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_instance_profile(
        self,
        policy_file: str,
        policy_name: str,
        role_name: str,
        profile_name: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> str:
        """
        Creates a policy, role, and profile that is associated with instances created by
        this class. An instance's associated profile defines a role that is assumed by the
        instance. The role has attached policies that specify the AWS permissions granted to
        clients that run on the instance.

        :param policy_file: The name of a JSON file that contains the policy definition to
                            create and attach to the role.
        :param policy_name: The name to give the created policy.
        :param role_name: The name to give the created role.
        :param profile_name: The name to the created profile.
        :param aws_managed_policies: Additional AWS-managed policies that are attached to
                                     the role, such as AmazonSSMManagedInstanceCore to grant
                                     use of Systems Manager to send commands to the instance.
        :return: The ARN of the profile that is created.
        """
        assume_role_doc = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"Service": "ec2.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        policy_arn = self.create_policy(policy_file, policy_name)
        self.create_role(role_name, assume_role_doc)
        self.attach_policy(role_name, policy_arn, aws_managed_policies)

        try:
            profile_response = self.iam_client.create_instance_profile(
                InstanceProfileName=profile_name
            )
            waiter = self.iam_client.get_waiter("instance_profile_exists")
            waiter.wait(InstanceProfileName=profile_name)
            time.sleep(10)  # wait a little longer
            profile_arn = profile_response["InstanceProfile"]["Arn"]
            self.iam_client.add_role_to_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            log.info("Created profile %s and added role %s.", profile_name, role_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                prof_response = self.iam_client.get_instance_profile(
                    InstanceProfileName=profile_name
                )
                profile_arn = prof_response["InstanceProfile"]["Arn"]
                log.info(
                    "Instance profile %s already exists, nothing to do.", profile_name
                )
            log.error(f"Full error:\n\t{err}")
        return profile_arn
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateInstanceProfile)를 참조하세요.

------

# CLI로 `CreateLoginProfile` 사용
<a name="iam_example_iam_CreateLoginProfile_section"></a>

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

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

**AWS CLI**  
**IAM 사용자의 암호 생성**  
IAM 사용자의 암호를 생성하려면 `--cli-input-json` 파라미터를 사용하여 암호가 포함된 JSON 파일을 전달하는 것이 좋습니다. 이 방법을 사용하면 영숫자가 아닌 문자가 포함된 강력한 암호를 생성할 수 있습니다. 명령줄 파라미터로 전달할 때 영숫자가 아닌 문자가 포함된 암호는 만들기 어려울 수 있습니다.  
`--cli-input-json` 파라미터를 사용하려면 다음 예와 같이 `--generate-cli-skeleton` 파라미터와 함께 `create-login-profile` 명령을 사용하는 것으로 시작합니다.  

```
aws iam create-login-profile \
    --generate-cli-skeleton > create-login-profile.json
```
이전 명령은 후속 `create-login-profile` 명령에 대한 정보를 입력하는 데 사용할 수 있는 create-login-profile.json이라는 JSON 파일을 생성합니다. 예제:  

```
{
    "UserName": "Bob",
    "Password": "&1-3a6u:RA0djs",
    "PasswordResetRequired": true
}
```
다음으로 IAM 사용자의 암호를 생성하려면 `create-login-profile` 명령을 다시 사용하되 이번에는 `--cli-input-json` 파라미터를 전달하여 JSON 파일을 지정합니다. 다음 `create-login-profile` 명령은 create-login-profile.json이라는 JSON 파일과 함께 `--cli-input-json` 파라미터를 사용합니다.  

```
aws iam create-login-profile \
    --cli-input-json file://create-login-profile.json
```
출력:  

```
{
    "LoginProfile": {
        "UserName": "Bob",
        "CreateDate": "2015-03-10T20:55:40.274Z",
        "PasswordResetRequired": true
    }
}
```
새 암호가 계정 암호 정책을 위반하는 경우 명령은 `PasswordPolicyViolation` 오류를 반환합니다.  
이미 암호가 있는 사용자의 암호를 변경하려면 `update-login-profile`을 사용합니다. 계정의 암호 정책을 설정하려면 `update-account-password-policy` 명령을 사용합니다.  
계정 암호 정책에서 허용하는 경우 IAM 사용자는 `change-password` 명령을 사용하여 자신의 암호를 변경할 수 있습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자 암호 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-login-profile.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 Bob이라는 IAM 사용자에 대한 (임시) 암호를 생성하고 다음에 `Bob`이 로그인할 때 사용자가 암호를 변경하도록 요구하는 플래그를 설정합니다.**  

```
New-IAMLoginProfile -UserName Bob -Password P@ssw0rd -PasswordResetRequired $true
```
**출력:**  

```
CreateDate                    PasswordResetRequired                UserName
----------                    ---------------------                --------
4/14/2015 12:26:30 PM         True                                 Bob
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateLoginProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 Bob이라는 IAM 사용자에 대한 (임시) 암호를 생성하고 다음에 `Bob`이 로그인할 때 사용자가 암호를 변경하도록 요구하는 플래그를 설정합니다.**  

```
New-IAMLoginProfile -UserName Bob -Password P@ssw0rd -PasswordResetRequired $true
```
**출력:**  

```
CreateDate                    PasswordResetRequired                UserName
----------                    ---------------------                --------
4/14/2015 12:26:30 PM         True                                 Bob
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `CreateOpenIdConnectProvider` 사용
<a name="iam_example_iam_CreateOpenIdConnectProvider_section"></a>

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

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

**AWS CLI**  
**OIDC(OpenID Connect) 제공업체 생성**  
OIDC(OpenID Connect) 제공업체를 생성하려면 `--cli-input-json` 파라미터를 사용하여 필수 파라미터가 포함된 JSON 파일을 전달하는 것이 좋습니다. OIDC 제공업체를 생성할 때는 제공업체의 URL을 전달해야 하며 URL은 `https://`로 시작해야 합니다. 일부 명령줄 환경에서는 콜론(:)과 슬래시(/) 문자가 특별한 의미를 갖기 때문에 URL을 명령줄 파라미터로 전달하기 어려울 수 있습니다. `--cli-input-json` 파라미터를 사용하면 이 제한을 피할 수 있습니다.  
`--cli-input-json` 파라미터를 사용하려면 다음 예와 같이 `--generate-cli-skeleton` 파라미터와 함께 `create-open-id-connect-provider` 명령을 사용하는 것으로 시작합니다.  

```
aws iam create-open-id-connect-provider \
    --generate-cli-skeleton > create-open-id-connect-provider.json
```
이전 명령은 후속 `create-open-id-connect-provider` 명령에 대한 정보를 입력하는 데 사용할 수 있는 create-open-id-connect-provider.json이라는 JSON 파일을 생성합니다. 예제:  

```
{
    "Url": "https://server.example.com",
    "ClientIDList": [
        "example-application-ID"
    ],
    "ThumbprintList": [
        "c3768084dfb3d2b68b7897bf5f565da8eEXAMPLE"
    ]
}
```
다음으로, OIDC(OpenID Connect) 제공업체를 생성하려면 `create-open-id-connect-provider` 명령을 다시 사용하되 이번에는 `--cli-input-json` 파라미터를 전달하여 JSON 파일을 지정합니다. 다음 `create-open-id-connect-provider` 명령은 create-open-id-connect-provider.json이라는 JSON 파일과 함께 `--cli-input-json` 파라미터를 사용합니다.  

```
aws iam create-open-id-connect-provider \
    --cli-input-json file://create-open-id-connect-provider.json
```
출력:  

```
{
    "OpenIDConnectProviderArn": "arn:aws:iam::123456789012:oidc-provider/server.example.com"
}
```
OIDC 제공업체에 대한 자세한 내용은 *AWS IAM 사용 설명서*의 [IAM에서 OIDC(OpenID Connect) ID 제공업체 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)을 참조하세요.  
OIDC 제공업체의 지문 가져오기에 대한 자세한 내용은 *AWS IAM 사용 설명서*의 [OpenID Connect 자격 증명 제공업체의 지문 얻기](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-open-id-connect-provider.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 URL `https://example.oidcprovider.com` 및 클라이언트 ID `my-testapp-1`에 있는 OIDC 호환 제공업체 서비스와 연결된 IAM OIDC 제공업체를 생성합니다. OIDC 제공업체가 지문을 제공합니다. 지문을 인증하려면 http://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc-obtain-thumbprint.html의 단계를 따르세요.**  

```
New-IAMOpenIDConnectProvider -Url https://example.oidcprovider.com -ClientIDList my-testapp-1 -ThumbprintList 990F419EXAMPLEECF12DDEDA5EXAMPLE52F20D9E
```
**출력:**  

```
arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 URL `https://example.oidcprovider.com` 및 클라이언트 ID `my-testapp-1`에 있는 OIDC 호환 제공업체 서비스와 연결된 IAM OIDC 제공업체를 생성합니다. OIDC 제공업체가 지문을 제공합니다. 지문을 인증하려면 http://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc-obtain-thumbprint.html의 단계를 따르세요.**  

```
New-IAMOpenIDConnectProvider -Url https://example.oidcprovider.com -ClientIDList my-testapp-1 -ThumbprintList 990F419EXAMPLEECF12DDEDA5EXAMPLE52F20D9E
```
**출력:**  

```
arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](iam_example_iam_Scenario_CreateUserAssumeRole_section.md) 
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 
+  [속성 기반 액세스 제어 설정](iam_example_dynamodb_Scenario_ABACSetup_section.md) 
+  [IAM 정책 빌더 API 작업](iam_example_iam_Scenario_IamPolicyBuilder_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// Create an IAM policy.
    /// </summary>
    /// <param name="policyName">The name to give the new IAM policy.</param>
    /// <param name="policyDocument">The policy document for the new policy.</param>
    /// <returns>The new IAM policy object.</returns>
    public async Task<ManagedPolicy> CreatePolicyAsync(string policyName, string policyDocument)
    {
        var response = await _IAMService.CreatePolicyAsync(new CreatePolicyRequest
        {
            PolicyDocument = policyDocument,
            PolicyName = policyName,
        });

        return response.Policy;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreatePolicy)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_create_policy
#
# This function creates an IAM policy.
#
# Parameters:
#       -n policy_name -- The name of the IAM policy.
#       -p policy_json -- The policy document.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_policy() {
  local policy_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_policy"
    echo "Creates an AWS Identity and Access Management (IAM) policy."
    echo "  -n policy_name   The name of the IAM policy."
    echo "  -p policy_json -- The policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) policy_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_name" ]]; then
    errecho "ERROR: You must provide a policy name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-policy \
    --policy-name "$policy_name" \
    --policy-document "$policy_document" \
    --output text \
    --query Policy.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
Aws::String AwsDoc::IAM::createPolicy(const Aws::String &policyName,
                                      const Aws::String &rsrcArn,
                                      const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::CreatePolicyRequest request;
    request.SetPolicyName(policyName);
    request.SetPolicyDocument(BuildSamplePolicyDocument(rsrcArn));

    Aws::IAM::Model::CreatePolicyOutcome outcome = iam.CreatePolicy(request);
    Aws::String result;
    if (!outcome.IsSuccess()) {
        std::cerr << "Error creating policy " << policyName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        result = outcome.GetResult().GetPolicy().GetArn();
        std::cout << "Successfully created policy " << policyName <<
                  std::endl;
    }

    return result;
}

Aws::String AwsDoc::IAM::BuildSamplePolicyDocument(const Aws::String &rsrc_arn) {
    std::stringstream stringStream;
    stringStream << "{"
                 << "  \"Version\": \"2012-10-17\","
                 << "  \"Statement\": ["
                 << "    {"
                 << "        \"Effect\": \"Allow\","
                 << "        \"Action\": \"logs:CreateLogGroup\","
                 << "        \"Resource\": \""
                 << rsrc_arn
                 << "\""
                 << "    },"
                 << "    {"
                 << "        \"Effect\": \"Allow\","
                 << "        \"Action\": ["
                 << "            \"dynamodb:DeleteItem\","
                 << "            \"dynamodb:GetItem\","
                 << "            \"dynamodb:PutItem\","
                 << "            \"dynamodb:Scan\","
                 << "            \"dynamodb:UpdateItem\""
                 << "       ],"
                 << "       \"Resource\": \""
                 << rsrc_arn
                 << "\""
                 << "    }"
                 << "   ]"
                 << "}";

    return stringStream.str();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreatePolicy)를 참조하세요.

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

**AWS CLI**  
**예제 1: 고객 관리형 정책 생성**  
다음 명령은 이름이 `my-policy`인 고객 관리형 정책을 생성합니다. `policy.json` 파일은 이름이 `amzn-s3-demo-bucket`인 Amazon S3 버킷의 `shared` 폴더에 대한 읽기 전용 액세스 권한을 부여하는 현재 폴더의 JSON 문서입니다.  

```
aws iam create-policy \
    --policy-name my-policy \
    --policy-document file://policy.json
```
policy.json의 콘텐츠:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket/shared/*"
            ]
        }
    ]
}
```
출력:  

```
{
    "Policy": {
        "PolicyName": "my-policy",
        "CreateDate": "2015-06-01T19:31:18.620Z",
        "AttachmentCount": 0,
        "IsAttachable": true,
        "PolicyId": "ZXR6A36LTYANPAI7NJ5UV",
        "DefaultVersionId": "v1",
        "Path": "/",
        "Arn": "arn:aws:iam::0123456789012:policy/my-policy",
        "UpdateDate": "2015-06-01T19:31:18.620Z"
    }
}
```
파일을 문자열 파라미터의 입력으로 사용하는 방법에 대한 자세한 내용은 [AWS CLI 사용 설명서의 CLI에 대한 파라미터 값 지정](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters.html)을 참조하세요. *AWS *   
**예제 2: 설명이 포함된 고객 관리형 정책 생성**  
다음 명령은 변경 불가능한 설명이 포함된 이름이 `my-policy`인 고객 관리형 정책을 생성합니다.  
`policy.json` 파일은 이름이 `amzn-s3-demo-bucket`인 Amazon S3 버킷의 모든 Put, List, Get 작업에 대한 액세스 권한을 부여하는 현재 폴더의 JSON 문서입니다.  

```
aws iam create-policy \
    --policy-name my-policy \
    --policy-document file://policy.json \
    --description "This policy grants access to all Put, Get, and List actions for amzn-s3-demo-bucket"
```
policy.json의 콘텐츠:  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
       {
           "Effect": "Allow",
           "Action": [
                "s3:ListBucket*",
                "s3:PutBucket*",
                "s3:GetBucket*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket"
            ]
        }
    ]
}
```
출력:  

```
{
    "Policy": {
        "PolicyName": "my-policy",
        "PolicyId": "ANPAWGSUGIDPEXAMPLE",
        "Arn": "arn:aws:iam::123456789012:policy/my-policy",
        "Path": "/",
        "DefaultVersionId": "v1",
        "AttachmentCount": 0,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "CreateDate": "2023-05-24T22:38:47+00:00",
        "UpdateDate": "2023-05-24T22:38:47+00:00"
    }
}
```
자격 증명 기반 정책에 대한 자세한 내용은 *AWS IAM 사용 설명서*의 [자격 증명 기반 정책 및 리소스 기반 정책](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html)을 참조하세요.  
**예제 3: 태그가 포함된 고객 관리형 정책을 생성하는 방법**  
다음 명령은 태그가 포함된 이름이 `my-policy`인 고객 관리형 정책을 생성합니다. 이 예제에서는 JSON 형식의 태그(`'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`)와 함께 `--tags` 파라미터를 사용합니다. 또는 `--tags` 파라미터를 단축 형식의 태그(`'Key=Department,Value=Accounting Key=Location,Value=Seattle'`)와 함께 사용할 수도 있습니다.  
`policy.json` 파일은 이름이 `amzn-s3-demo-bucket`인 Amazon S3 버킷의 모든 Put, List, Get 작업에 대한 액세스 권한을 부여하는 현재 폴더의 JSON 문서입니다.  

```
aws iam create-policy \
    --policy-name my-policy \
    --policy-document file://policy.json \
    --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'
```
policy.json의 콘텐츠:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket*",
                "s3:PutBucket*",
                "s3:GetBucket*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket"
            ]
        }
    ]
}
```
출력:  

```
{
    "Policy": {
        "PolicyName": "my-policy",
        "PolicyId": "ANPAWGSUGIDPEXAMPLE",
        "Arn": "arn:aws:iam::12345678012:policy/my-policy",
        "Path": "/",
        "DefaultVersionId": "v1",
        "AttachmentCount": 0,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "CreateDate": "2023-05-24T23:16:39+00:00",
        "UpdateDate": "2023-05-24T23:16:39+00:00",
        "Tags": [
            {
                "Key": "Department",
                "Value": "Accounting"
            },
                "Key": "Location",
                "Value": "Seattle"
            {
        ]
    }
}
```
정책 태그 지정에 대한 자세한 내용은 *AWS IAM 사용 설명서*의 [고객 관리형 정책 태깅](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_customer-managed-policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    []string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
}

// CreatePolicy creates a policy that grants a list of actions to the specified resource.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper PolicyWrapper) CreatePolicy(ctx context.Context, policyName string, actions []string,
	resourceArn string) (*types.Policy, error) {
	var policy *types.Policy
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(resourceArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", resourceArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreatePolicy(ctx, &iam.CreatePolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
	})
	if err != nil {
		log.Printf("Couldn't create policy %v. Here's why: %v\n", policyName, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [CreatePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreatePolicy)를 참조하십시오.

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

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

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.iam.model.CreatePolicyRequest;
import software.amazon.awssdk.services.iam.model.CreatePolicyResponse;
import software.amazon.awssdk.services.iam.model.GetPolicyRequest;
import software.amazon.awssdk.services.iam.model.GetPolicyResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.waiters.IamWaiter;

/**
 * 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 CreatePolicy {

    public static final String PolicyDocument = "{" +
            "  \"Version\": \"2012-10-17\"," +
            "  \"Statement\": [" +
            "    {" +
            "        \"Effect\": \"Allow\"," +
            "        \"Action\": [" +
            "            \"dynamodb:DeleteItem\"," +
            "            \"dynamodb:GetItem\"," +
            "            \"dynamodb:PutItem\"," +
            "            \"dynamodb:Scan\"," +
            "            \"dynamodb:UpdateItem\"" +
            "       ]," +
            "       \"Resource\": \"*\"" +
            "    }" +
            "   ]" +
            "}";

    public static void main(String[] args) {

        final String usage = """
                Usage:
                    CreatePolicy <policyName>\s

                Where:
                    policyName - A unique policy name.\s
                """;

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

        String policyName = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        String result = createIAMPolicy(iam, policyName);
        System.out.println("Successfully created a policy with this ARN value: " + result);
        iam.close();
    }

    public static String createIAMPolicy(IamClient iam, String policyName) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();

            CreatePolicyRequest request = CreatePolicyRequest.builder()
                    .policyName(policyName)
                    .policyDocument(PolicyDocument)
                    .build();

            CreatePolicyResponse response = iam.createPolicy(request);

            // Wait until the policy is created.
            GetPolicyRequest polRequest = GetPolicyRequest.builder()
                    .policyArn(response.policy().arn())
                    .build();

            WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
            waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
            return response.policy().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreatePolicy)를 참조하십시오.

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

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

```
import { CreatePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyName
 */
export const createPolicy = (policyName) => {
  const command = new CreatePolicyCommand({
    PolicyDocument: JSON.stringify({
      Version: "2012-10-17",
      Statement: [
        {
          Effect: "Allow",
          Action: "*",
          Resource: "*",
        },
      ],
    }),
    PolicyName: policyName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-creating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreatePolicyCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var myManagedPolicy = {
  Version: "2012-10-17",
  Statement: [
    {
      Effect: "Allow",
      Action: "logs:CreateLogGroup",
      Resource: "RESOURCE_ARN",
    },
    {
      Effect: "Allow",
      Action: [
        "dynamodb:DeleteItem",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Scan",
        "dynamodb:UpdateItem",
      ],
      Resource: "RESOURCE_ARN",
    },
  ],
};

var params = {
  PolicyDocument: JSON.stringify(myManagedPolicy),
  PolicyName: "myDynamoDBPolicy",
};

iam.createPolicy(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-creating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreatePolicy)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun createIAMPolicy(policyNameVal: String?): String {
    val policyDocumentVal = """
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "dynamodb:DeleteItem",
                    "dynamodb:GetItem",
                    "dynamodb:PutItem",
                    "dynamodb:Scan",
                    "dynamodb:UpdateItem"
                ],
                "Resource": "*"
            }
        ]
    }
    """.trimIndent()

    val request =
        CreatePolicyRequest {
            policyName = policyNameVal
            policyDocument = policyDocumentVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createPolicy(request)
        return response.policy?.arn.toString()
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreatePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

    /**
     * @param string $policyName
     * @param string $policyDocument
     * @return array
     */
    public function createPolicy(string $policyName, string $policyDocument)
    {
        $result = $this->customWaiter(function () use ($policyName, $policyDocument) {
            return $this->iamClient->createPolicy([
                'PolicyName' => $policyName,
                'PolicyDocument' => $policyDocument,
            ]);
        });
        return $result['Policy'];
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreatePolicy)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제에서는 라는 현재 AWS 계정에 새 IAM 정책을 생성합니다. `MySamplePolicy` 파일은 정책 콘텐츠를 `MySamplePolicy.json` 제공합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
New-IAMPolicy -PolicyName MySamplePolicy -PolicyDocument (Get-Content -Raw MySamplePolicy.json)
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 4/14/2015 2:45:59 PM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : LD4KP6HVFE7WGEXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 4/14/2015 2:45:59 PM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreatePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제에서는 라는 현재 AWS 계정에 새 IAM 정책을 생성합니다. `MySamplePolicy` 파일은 정책 콘텐츠를 `MySamplePolicy.json` 제공합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
New-IAMPolicy -PolicyName MySamplePolicy -PolicyDocument (Get-Content -Raw MySamplePolicy.json)
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 4/14/2015 2:45:59 PM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : LD4KP6HVFE7WGEXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 4/14/2015 2:45:59 PM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreatePolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def create_policy(name, description, actions, resource_arn):
    """
    Creates a policy that contains a single statement.

    :param name: The name of the policy to create.
    :param description: The description of the policy.
    :param actions: The actions allowed by the policy. These typically take the
                    form of service:action, such as s3:PutObject.
    :param resource_arn: The Amazon Resource Name (ARN) of the resource this policy
                         applies to. This ARN can contain wildcards, such as
                         'arn:aws:s3:::amzn-s3-demo-bucket/*' to allow actions on all objects
                         in the bucket named 'amzn-s3-demo-bucket'.
    :return: The newly created policy.
    """
    policy_doc = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}],
    }
    try:
        policy = iam.create_policy(
            PolicyName=name,
            Description=description,
            PolicyDocument=json.dumps(policy_doc),
        )
        logger.info("Created policy %s.", policy.arn)
    except ClientError:
        logger.exception("Couldn't create policy %s.", name)
        raise
    else:
        return policy
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 역할 정책을 나열, 생성, 연결 및 분리합니다.  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreatePolicy)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn create_policy(
    client: &iamClient,
    policy_name: &str,
    policy_document: &str,
) -> Result<Policy, iamError> {
    let policy = client
        .create_policy()
        .policy_name(policy_name)
        .policy_document(policy_document)
        .send()
        .await?;
    Ok(policy.policy.unwrap())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreatePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_policy)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->createpolicy(
          iv_policyname = iv_policy_name
          iv_policydocument = iv_policy_document
          iv_description = iv_description ).
        MESSAGE 'Policy created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'Policy already exists.' TYPE 'E'.
      CATCH /aws1/cx_iammalformedplydocex.
        MESSAGE 'Policy document is malformed.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는AWS *SDK for SAP ABAP API*의 [CreatePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func createPolicy(name: String, policyDocument: String) async throws -> IAMClientTypes.Policy {
        let input = CreatePolicyInput(
            policyDocument: policyDocument,
            policyName: name
        )
        do {
            let output = try await iamClient.createPolicy(input: input)
            guard let policy = output.policy else {
                throw ServiceHandlerError.noSuchPolicy
            }
            return policy
        } catch {
            print("ERROR: createPolicy:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreatePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createpolicy(input:))를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 

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

**AWS CLI**  
**관리형 정책의 새 버전 생성**  
이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyPolicy`인 IAM 정책의 새 `v2` 버전을 생성하고 이를 기본 버전으로 만듭니다.  

```
aws iam create-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --policy-document file://NewPolicyVersion.json \
    --set-as-default
```
출력:  

```
{
    "PolicyVersion": {
        "CreateDate": "2015-06-16T18:56:03.721Z",
        "VersionId": "v2",
        "IsDefaultVersion": true
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 정책 버전 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-versioning.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreatePolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-policy-version.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyPolicy`인 IAM 정책의 새 'v2' 버전을 생성하고 이를 기본 버전으로 만듭니다. `NewPolicyVersion.json` 파일은 정책 콘텐츠를 제공합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
New-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -PolicyDocument (Get-content -Raw NewPolicyVersion.json) -SetAsDefault $true
```
**출력:**  

```
CreateDate                           Document                  IsDefaultVersion             VersionId
----------                           --------                  ----------------             ---------
4/15/2015 10:54:54 AM                                          True                         v2
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreatePolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyPolicy`인 IAM 정책의 새 'v2' 버전을 생성하고 이를 기본 버전으로 만듭니다. `NewPolicyVersion.json` 파일은 정책 콘텐츠를 제공합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
New-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -PolicyDocument (Get-content -Raw NewPolicyVersion.json) -SetAsDefault $true
```
**출력:**  

```
CreateDate                           Document                  IsDefaultVersion             VersionId
----------                           --------                  ----------------             ---------
4/15/2015 10:54:54 AM                                          True                         v2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreatePolicyVersion](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def create_policy_version(policy_arn, actions, resource_arn, set_as_default):
    """
    Creates a policy version. Policies can have up to five versions. The default
    version is the one that is used for all resources that reference the policy.

    :param policy_arn: The ARN of the policy.
    :param actions: The actions to allow in the policy version.
    :param resource_arn: The ARN of the resource this policy version applies to.
    :param set_as_default: When True, this policy version is set as the default
                           version for the policy. Otherwise, the default
                           is not changed.
    :return: The newly created policy version.
    """
    policy_doc = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}],
    }
    try:
        policy = iam.Policy(policy_arn)
        policy_version = policy.create_version(
            PolicyDocument=json.dumps(policy_doc), SetAsDefault=set_as_default
        )
        logger.info(
            "Created policy version %s for policy %s.",
            policy_version.version_id,
            policy_version.arn,
        )
    except ClientError:
        logger.exception("Couldn't create a policy version for %s.", policy_arn)
        raise
    else:
        return policy_version
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreatePolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicyVersion)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->createpolicyversion(
          iv_policyarn = iv_policy_arn
          iv_policydocument = iv_policy_document
          iv_setasdefault = iv_set_as_default ).
        MESSAGE 'Policy version created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iammalformedplydocex.
        MESSAGE 'Policy document is malformed.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy version limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreatePolicyVersion](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------

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

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Create a new IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="rolePolicyDocument">The name of the IAM policy document
    /// for the new role.</param>
    /// <returns>The Amazon Resource Name (ARN) of the role.</returns>
    public async Task<string> CreateRoleAsync(string roleName, string rolePolicyDocument)
    {
        var request = new CreateRoleRequest
        {
            RoleName = roleName,
            AssumeRolePolicyDocument = rolePolicyDocument,
        };

        var response = await _IAMService.CreateRoleAsync(request);
        return response.Role.Arn;
    }
```
+  API 세부 정보는 [AWS SDK for .NET API 참조](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)의 *CreateRole*을 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_create_role
#
# This function creates an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_json -- The assume role policy document.
#
# Returns:
#       The ARN of the role.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_role() {
  local role_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_json -- The assume role policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-role \
    --role-name "$role_name" \
    --assume-role-policy-document "$policy_document" \
    --output text \
    --query Role.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-role operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)을 참조하세요.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::createIamRole(
        const Aws::String &roleName,
        const Aws::String &policy,
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient client(clientConfig);
    Aws::IAM::Model::CreateRoleRequest request;

    request.SetRoleName(roleName);
    request.SetAssumeRolePolicyDocument(policy);

    Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error creating role. " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        const Aws::IAM::Model::Role iamRole = outcome.GetResult().GetRole();
        std::cout << "Created role " << iamRole.GetRoleName() << "\n";
        std::cout << "ID: " << iamRole.GetRoleId() << "\n";
        std::cout << "ARN: " << iamRole.GetArn() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 [AWS SDK for C\$1\$1 API 참조](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)의 *CreateRole*을 참조하세요.

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

**AWS CLI**  
**예제 1: IAM 역할 생성**  
다음 `create-role` 명령은 이름이 `Test-Role`인 역할을 생성하고 해당 역할에 신뢰 정책을 연결합니다.  

```
aws iam create-role \
    --role-name Test-Role \
    --assume-role-policy-document file://Test-Role-Trust-Policy.json
```
출력:  

```
{
    "Role": {
        "AssumeRolePolicyDocument": "<URL-encoded-JSON>",
        "RoleId": "AKIAIOSFODNN7EXAMPLE",
        "CreateDate": "2013-06-07T20:43:32.821Z",
        "RoleName": "Test-Role",
        "Path": "/",
        "Arn": "arn:aws:iam::123456789012:role/Test-Role"
    }
}
```
신뢰 정책은 Test-Role-Trust-Policy.json** 파일에 JSON 문서로 정의됩니다. (파일 이름과 확장자는 중요하지 않습니다.) 신뢰 정책에서 위탁자를 지정해야 합니다.  
역할에 권한 정책을 연결하려면 `put-role-policy` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)을 참조하세요.  
**예제 2: 지정된 최대 세션 시간을 포함한 IAM 역할 생성**  
다음 `create-role` 명령은 이름이 `Test-Role`인 역할을 생성하고 최대 세션 지속 시간을 7,200초(2시간)로 설정합니다.  

```
aws iam create-role \
    --role-name Test-Role \
    --assume-role-policy-document file://Test-Role-Trust-Policy.json \
    --max-session-duration 7200
```
출력:  

```
{
    "Role": {
        "Path": "/",
        "RoleName": "Test-Role",
        "RoleId": "AKIAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::12345678012:role/Test-Role",
        "CreateDate": "2023-05-24T23:50:25+00:00",
        "AssumeRolePolicyDocument": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Sid": "Statement1",
                    "Effect": "Allow",
                    "Principal": {
                        "AWS": "arn:aws:iam::12345678012:root"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [역할 최대 세션 기간(AWS API) 수정](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-modify_max-session-duration-api)을 참조하세요.  
**예제 3: 태그가 포함된 IAM 역할 생성**  
다음 명령은 태그가 포함된 IAM 역할 `Test-Role`을 생성합니다. 이 예제에서는 다음 JSON 형식의 태그(`'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`)에 `--tags` 파라미터 플래그를 사용합니다. 또는 `--tags` 플래그를 짧은 형식의 태그(`'Key=Department,Value=Accounting Key=Location,Value=Seattle'`)에 사용할 수도 있습니다.  

```
aws iam create-role \
    --role-name Test-Role \
    --assume-role-policy-document file://Test-Role-Trust-Policy.json \
    --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'
```
출력:  

```
{
    "Role": {
        "Path": "/",
        "RoleName": "Test-Role",
        "RoleId": "AKIAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:role/Test-Role",
        "CreateDate": "2023-05-25T23:29:41+00:00",
        "AssumeRolePolicyDocument": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Sid": "Statement1",
                    "Effect": "Allow",
                    "Principal": {
                        "AWS": "arn:aws:iam::123456789012:root"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        },
        "Tags": [
            {
                "Key": "Department",
                "Value": "Accounting"
            },
            {
                "Key": "Location",
                "Value": "Seattle"
            }
        ]
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 역할 태그 지정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_roles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-role.html)을 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// CreateRole creates a role that trusts a specified user. The trusted user can assume
// the role to acquire its permissions.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper RoleWrapper) CreateRole(ctx context.Context, roleName string, trustedUserArn string) (*types.Role, error) {
	var role *types.Role
	trustPolicy := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:    "Allow",
			Principal: map[string]string{"AWS": trustedUserArn},
			Action:    []string{"sts:AssumeRole"},
		}},
	}
	policyBytes, err := json.Marshal(trustPolicy)
	if err != nil {
		log.Printf("Couldn't create trust policy for %v. Here's why: %v\n", trustedUserArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreateRole(ctx, &iam.CreateRoleInput{
		AssumeRolePolicyDocument: aws.String(string(policyBytes)),
		RoleName:                 aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't create role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}
```
+  API 세부 정보는 [AWS SDK for Go API 참조](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)의 *CreateRole*을 참조하세요.

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

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

```
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import software.amazon.awssdk.services.iam.model.CreateRoleRequest;
import software.amazon.awssdk.services.iam.model.CreateRoleResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import java.io.FileReader;

/*
*   This example requires a trust policy document. For more information, see:
*   https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/
*
*
*  In addition, set up your development environment, including your credentials.
*
*  For information, see this documentation topic:
*
*  https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class CreateRole {
    public static void main(String[] args) throws Exception {
        final String usage = """
                Usage:
                    <rolename> <fileLocation>\s

                Where:
                    rolename - The name of the role to create.\s
                    fileLocation - The location of the JSON document that represents the trust policy.\s
                """;

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

        String rolename = args[0];
        String fileLocation = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        String result = createIAMRole(iam, rolename, fileLocation);
        System.out.println("Successfully created user: " + result);
        iam.close();
    }

    public static String createIAMRole(IamClient iam, String rolename, String fileLocation) throws Exception {
        try {
            JSONObject jsonObject = (JSONObject) readJsonSimpleDemo(fileLocation);
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(rolename)
                    .assumeRolePolicyDocument(jsonObject.toJSONString())
                    .description("Created using the AWS SDK for Java")
                    .build();

            CreateRoleResponse response = iam.createRole(request);
            System.out.println("The ARN of the role is " + response.role().arn());

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static Object readJsonSimpleDemo(String filename) throws Exception {
        FileReader reader = new FileReader(filename);
        JSONParser jsonParser = new JSONParser();
        return jsonParser.parse(reader);
    }
}
```
+  API 세부 정보는 [AWS SDK for Java 2.x API 참조](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)의 *CreateRole*을 참조하세요.

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

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

```
import { CreateRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const createRole = (roleName) => {
  const command = new CreateRoleCommand({
    AssumeRolePolicyDocument: JSON.stringify({
      Version: "2012-10-17",
      Statement: [
        {
          Effect: "Allow",
          Principal: {
            Service: "lambda.amazonaws.com",
          },
          Action: "sts:AssumeRole",
        },
      ],
    }),
    RoleName: roleName,
  });

  return client.send(command);
};
```
+  API 세부 정보는 [AWS SDK for JavaScript API 참조](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)의 *CreateRole*을 참조하세요.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

$assumeRolePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{$user['Arn']}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }";
$assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument);
echo "Created role: {$assumeRoleRole['RoleName']}\n";

    /**
     * @param string $roleName
     * @param string $rolePolicyDocument
     * @return array
     * @throws AwsException
     */
    public function createRole(string $roleName, string $rolePolicyDocument)
    {
        $result = $this->customWaiter(function () use ($roleName, $rolePolicyDocument) {
            return $this->iamClient->createRole([
                'AssumeRolePolicyDocument' => $rolePolicyDocument,
                'RoleName' => $roleName,
            ]);
        });
        return $result['Role'];
    }
```
+  API 세부 정보는 [AWS SDK for PHP API 참조](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)의 *CreateRole*을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `MyNewRole`이라는 새 역할을 생성하고 여기에 `NewRoleTrustPolicy.json` 파일에 있는 정책을 연결합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다. 출력에 표시된 정책 문서는 URL로 인코딩됩니다. 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다. **   

```
$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole
$results
```
**출력:**  

```
Arn                      : arn:aws:iam::123456789012:role/MyNewRole
AssumeRolePolicyDocument : %7B%0D%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0D%0A%20%20%22Statement%22
                           %3A%20%5B%0D%0A%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%22Sid%22%3A%20%22%22%2C
                           %0D%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0D%0A%20%20%20%20%20%20
                           %22Principal%22%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%22AWS%22%3A%20%22arn%3Aaws
                           %3Aiam%3A%3A123456789012%3ADavid%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20
                           %20%20%20%22Action%22%3A%20%22sts%3AAssumeRole%22%0D%0A%20%20%20%20%7D%0D%0A%20
                           %20%5D%0D%0A%7D
CreateDate               : 4/15/2015 11:04:23 AM
Path                     : /
RoleId                   : V5PAJI2KPN4EAEXAMPLE1
RoleName                 : MyNewRole

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:David"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `MyNewRole`이라는 새 역할을 생성하고 여기에 `NewRoleTrustPolicy.json` 파일에 있는 정책을 연결합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다. 출력에 표시된 정책 문서는 URL로 인코딩됩니다. 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다. **   

```
$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole
$results
```
**출력:**  

```
Arn                      : arn:aws:iam::123456789012:role/MyNewRole
AssumeRolePolicyDocument : %7B%0D%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0D%0A%20%20%22Statement%22
                           %3A%20%5B%0D%0A%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%22Sid%22%3A%20%22%22%2C
                           %0D%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0D%0A%20%20%20%20%20%20
                           %22Principal%22%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%22AWS%22%3A%20%22arn%3Aaws
                           %3Aiam%3A%3A123456789012%3ADavid%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20
                           %20%20%20%22Action%22%3A%20%22sts%3AAssumeRole%22%0D%0A%20%20%20%20%7D%0D%0A%20
                           %20%5D%0D%0A%7D
CreateDate               : 4/15/2015 11:04:23 AM
Path                     : /
RoleId                   : V5PAJI2KPN4EAEXAMPLE1
RoleName                 : MyNewRole

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:David"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateRole](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def create_role(role_name, allowed_services):
    """
    Creates a role that lets a list of specified services assume the role.

    :param role_name: The name of the role.
    :param allowed_services: The services that can assume the role.
    :return: The newly created role.
    """
    trust_policy = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {"Service": service},
                "Action": "sts:AssumeRole",
            }
            for service in allowed_services
        ],
    }

    try:
        role = iam.create_role(
            RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy)
        )
        logger.info("Created role %s.", role.name)
    except ClientError:
        logger.exception("Couldn't create role %s.", role_name)
        raise
    else:
        return role
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)를 참조하세요.

------
#### [ Ruby ]

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

```
  # Creates a role and attaches policies to it.
  #
  # @param role_name [String] The name of the role.
  # @param assume_role_policy_document [Hash] The trust relationship policy document.
  # @param policy_arns [Array<String>] The ARNs of the policies to attach.
  # @return [String, nil] The ARN of the new role if successful, or nil if an error occurred.
  def create_role(role_name, assume_role_policy_document, policy_arns)
    response = @iam_client.create_role(
      role_name: role_name,
      assume_role_policy_document: assume_role_policy_document.to_json
    )
    role_arn = response.role.arn

    policy_arns.each do |policy_arn|
      @iam_client.attach_role_policy(
        role_name: role_name,
        policy_arn: policy_arn
      )
    end

    role_arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating role: #{e.message}")
    nil
  end
```
+  API 세부 정보는 [AWS SDK for Ruby API 참조](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)의 *CreateRole*을 참조하세요.

------
#### [ Rust ]

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

```
pub async fn create_role(
    client: &iamClient,
    role_name: &str,
    role_policy_document: &str,
) -> Result<Role, iamError> {
    let response: CreateRoleOutput = loop {
        if let Ok(response) = client
            .create_role()
            .role_name(role_name)
            .assume_role_policy_document(role_policy_document)
            .send()
            .await
        {
            break response;
        }
    };

    Ok(response.role.unwrap())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->createrole(
          iv_rolename = iv_role_name
          iv_assumerolepolicydocument = iv_assume_role_policy_document ).
        MESSAGE 'Role created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'Role already exists.' TYPE 'E'.
      CATCH /aws1/cx_iammalformedplydocex.
        MESSAGE 'Assume role policy document is malformed.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Role limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func createRole(name: String, policyDocument: String) async throws -> String {
        let input = CreateRoleInput(
            assumeRolePolicyDocument: policyDocument,
            roleName: name
        )
        do {
            let output = try await client.createRole(input: input)
            guard let role = output.role else {
                throw ServiceHandlerError.noSuchRole
            }
            guard let id = role.roleId else {
                throw ServiceHandlerError.noSuchRole
            }
            return id
        } catch {
            print("ERROR: createRole:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreateRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createrole(input:))을 참조하세요.

------

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

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

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

**AWS CLI**  
**SAML 공급자 생성**  
이 예제는 IAM에 이름이 `MySAMLProvider`인 새 SAML 공급자를 생성합니다. `SAMLMetaData.xml` 파일에 있는 SAML 메타데이터 문서에 설명되어 있습니다.  

```
aws iam create-saml-provider \
    --saml-metadata-document file://SAMLMetaData.xml \
    --name MySAMLProvider
```
출력:  

```
{
    "SAMLProviderArn": "arn:aws:iam::123456789012:saml-provider/MySAMLProvider"
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM SAML 자격 증명 공급자 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateSAMLProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-saml-provider.html)를 참조하세요.

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

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

```
import { CreateSAMLProviderCommand, IAMClient } from "@aws-sdk/client-iam";
import { readFileSync } from "node:fs";
import * as path from "node:path";
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";

const client = new IAMClient({});

/**
 * This sample document was generated using Auth0.
 * For more information on generating this document, see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html#samlstep1.
 */
const sampleMetadataDocument = readFileSync(
  path.join(
    dirnameFromMetaUrl(import.meta.url),
    "../../../../resources/sample_files/sample_saml_metadata.xml",
  ),
);

/**
 *
 * @param {*} providerName
 * @returns
 */
export const createSAMLProvider = async (providerName) => {
  const command = new CreateSAMLProviderCommand({
    Name: providerName,
    SAMLMetadataDocument: sampleMetadataDocument.toString(),
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API 세부 정보는AWS SDK for JavaScript API 참조의 [CreateSAMLProvider](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateSAMLProviderCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM에 새 SAML 제공업체를 생성합니다. 이름은 `MySAMLProvider`이며 SAML 서비스 제공업체의 웹 사이트에서 별도로 다운로드한 `SAMLMetaData.xml` 파일에 있는 SAML 메타데이터 문서에 설명되어 있습니다.**  

```
New-IAMSAMLProvider -Name MySAMLProvider -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
**출력:**  

```
arn:aws:iam::123456789012:saml-provider/MySAMLProvider
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateSAMLProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM에 새 SAML 제공업체를 생성합니다. 이름은 `MySAMLProvider`이며 SAML 서비스 제공업체의 웹 사이트에서 별도로 다운로드한 `SAMLMetaData.xml` 파일에 있는 SAML 메타데이터 문서에 설명되어 있습니다.**  

```
New-IAMSAMLProvider -Name MySAMLProvider -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
**출력:**  

```
arn:aws:iam::123456789012:saml-provider/MySAMLProvider
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateSAMLProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Create an IAM service-linked role.
    /// </summary>
    /// <param name="serviceName">The name of the AWS Service.</param>
    /// <param name="description">A description of the IAM service-linked role.</param>
    /// <returns>The IAM role that was created.</returns>
    public async Task<Role> CreateServiceLinkedRoleAsync(string serviceName, string description)
    {
        var request = new CreateServiceLinkedRoleRequest
        {
            AWSServiceName = serviceName,
            Description = description
        };

        var response = await _IAMService.CreateServiceLinkedRoleAsync(request);
        return response.Role;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateServiceLinkedRole)을 참조하세요.

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

**AWS CLI**  
**서비스 연결 역할 생성**  
다음 `create-service-linked-role` 예제에서는 지정된 서비스에 대한 AWS 서비스 연결 역할을 생성하고 지정된 설명을 연결합니다.  

```
aws iam create-service-linked-role \
    --aws-service-name lex.amazonaws.com \
    --description "My service-linked role to support Lex"
```
출력:  

```
{
    "Role": {
        "Path": "/aws-service-role/lex.amazonaws.com/",
        "RoleName": "AWSServiceRoleForLexBots",
        "RoleId": "AROA1234567890EXAMPLE",
        "Arn": "arn:aws:iam::1234567890:role/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots",
        "CreateDate": "2019-04-17T20:34:14+00:00",
        "AssumeRolePolicyDocument": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Action": [
                        "sts:AssumeRole"
                    ],
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "lex.amazonaws.com"
                        ]
                    }
                }
            ]
        }
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [서비스 연결 역할 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateServiceLinkedRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-service-linked-role.html)을 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// CreateServiceLinkedRole creates a service-linked role that is owned by the specified service.
func (wrapper RoleWrapper) CreateServiceLinkedRole(ctx context.Context, serviceName string, description string) (
	*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.CreateServiceLinkedRole(ctx, &iam.CreateServiceLinkedRoleInput{
		AWSServiceName: aws.String(serviceName),
		Description:    aws.String(description),
	})
	if err != nil {
		log.Printf("Couldn't create service-linked role %v. Here's why: %v\n", serviceName, err)
	} else {
		role = result.Role
	}
	return role, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [CreateServiceLinkedRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateServiceLinkedRole)을 참조하십시오.

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

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

```
import {
  CreateServiceLinkedRoleCommand,
  GetRoleCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} serviceName
 */
export const createServiceLinkedRole = async (serviceName) => {
  const command = new CreateServiceLinkedRoleCommand({
    // For a list of AWS services that support service-linked roles,
    // see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html.
    //
    // For a list of AWS service endpoints, see https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html.
    AWSServiceName: serviceName,
  });
  try {
    const response = await client.send(command);
    console.log(response);
    return response;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInputException" &&
      caught.message.includes(
        "Service role name AWSServiceRoleForElasticBeanstalk has been taken in this account",
      )
    ) {
      console.warn(caught.message);
      return client.send(
        new GetRoleCommand({ RoleName: "AWSServiceRoleForElasticBeanstalk" }),
      );
    }
    throw caught;
  }
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateServiceLinkedRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateServiceLinkedRoleCommand)을 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function createServiceLinkedRole($awsServiceName, $customSuffix = "", $description = "")
    {
        $createServiceLinkedRoleArguments = ['AWSServiceName' => $awsServiceName];
        if ($customSuffix) {
            $createServiceLinkedRoleArguments['CustomSuffix'] = $customSuffix;
        }
        if ($description) {
            $createServiceLinkedRoleArguments['Description'] = $description;
        }
        return $this->iamClient->createServiceLinkedRole($createServiceLinkedRoleArguments);
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateServiceLinkedRole)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 AutoScaling 서비스에 대한 서비스 연결 역할을 생성합니다.**  

```
New-IAMServiceLinkedRole -AWSServiceName autoscaling.amazonaws.com -CustomSuffix RoleNameEndsWithThis -Description "My service-linked role to support autoscaling"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateServiceLinkedRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 AutoScaling 서비스에 대한 서비스 연결 역할을 생성합니다.**  

```
New-IAMServiceLinkedRole -AWSServiceName autoscaling.amazonaws.com -CustomSuffix RoleNameEndsWithThis -Description "My service-linked role to support autoscaling"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateServiceLinkedRole](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def create_service_linked_role(service_name, description):
    """
    Creates a service-linked role.

    :param service_name: The name of the service that owns the role.
    :param description: A description to give the role.
    :return: The newly created role.
    """
    try:
        response = iam.meta.client.create_service_linked_role(
            AWSServiceName=service_name, Description=description
        )
        role = iam.Role(response["Role"]["RoleName"])
        logger.info("Created service-linked role %s.", role.name)
    except ClientError:
        logger.exception("Couldn't create service-linked role for %s.", service_name)
        raise
    else:
        return role
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateServiceLinkedRole)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Creates a service-linked role
  #
  # @param service_name [String] The service name to create the role for.
  # @param description [String] The description of the service-linked role.
  # @param suffix [String] Suffix for customizing role name.
  # @return [String] The name of the created role
  def create_service_linked_role(service_name, description, suffix)
    response = @iam_client.create_service_linked_role(
      aws_service_name: service_name, description: description, custom_suffix: suffix
    )
    role_name = response.role.role_name
    @logger.info("Created service-linked role #{role_name}.")
    role_name
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't create service-linked role for #{service_name}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateServiceLinkedRole)을 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn create_service_linked_role(
    client: &iamClient,
    aws_service_name: String,
    custom_suffix: Option<String>,
    description: Option<String>,
) -> Result<CreateServiceLinkedRoleOutput, SdkError<CreateServiceLinkedRoleError>> {
    let response = client
        .create_service_linked_role()
        .aws_service_name(aws_service_name)
        .set_custom_suffix(custom_suffix)
        .set_description(description)
        .send()
        .await?;

    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateServiceLinkedRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_service_linked_role)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listpolicyversions(
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Retrieved policy versions list.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing policy versions.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateServiceLinkedRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func createServiceLinkedRole(service: String, suffix: String? = nil, description: String?)
                    async throws -> IAMClientTypes.Role {
        let input = CreateServiceLinkedRoleInput(
            awsServiceName: service,
            customSuffix: suffix,
            description: description
        )
        do {
            let output = try await client.createServiceLinkedRole(input: input)
            guard let role = output.role else {
                throw ServiceHandlerError.noSuchRole
            }
            return role
        } catch {
            print("ERROR: createServiceLinkedRole:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreateServiceLinkedRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createservicelinkedrole(input:))을 참조하세요.

------

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

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Create an IAM user.
    /// </summary>
    /// <param name="userName">The username for the new IAM user.</param>
    /// <returns>The IAM user that was created.</returns>
    public async Task<User> CreateUserAsync(string userName)
    {
        var response = await _IAMService.CreateUserAsync(new CreateUserRequest { UserName = userName });
        return response.User;
    }
```
+  API 세부 정보는 [AWS SDK for .NET API 참조](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateUser)의 *CreateUser*를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_create_user
#
# This function creates the specified IAM user, unless
# it already exists.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       The ARN of the user.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user"
    echo "Creates an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user. It must be unique within the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user already exists, we don't want to try to create it.
  if (iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name already exists in the account."
    return 1
  fi

  response=$(aws iam create-user --user-name "$user_name" \
    --output text \
    --query 'User.Arn')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-user operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateUser)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::CreateUserRequest create_request;
    create_request.SetUserName(userName);

    auto create_outcome = iam.CreateUser(create_request);
    if (!create_outcome.IsSuccess()) {
        std::cerr << "Error creating IAM user " << userName << ":" <<
                  create_outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully created IAM user " << userName << std::endl;
    }

    return create_outcome.IsSuccess();
```
+  API 세부 정보는 [AWS SDK for C\$1\$1 API 참조](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateUser)의 *CreateUser*를 참조하세요.

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

**AWS CLI**  
**예제 1: IAM 사용자 생성**  
다음 `create-user` 명령은 현재 계정에서 이름이 `Bob`인 IAM 사용자를 생성합니다.  

```
aws iam create-user \
    --user-name Bob
```
출력:  

```
{
    "User": {
        "UserName": "Bob",
        "Path": "/",
        "CreateDate": "2023-06-08T03:20:41.270Z",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:user/Bob"
    }
}
```
자세한 내용은 [IAM 사용 설명서의 AWS 계정에서 IAM 사용자 생성을 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html). *AWS *   
**예제 2: 지정된 경로에 IAM 사용자 생성**  
다음 `create-user` 명령은 지정된 경로에서 이름이 `Bob`인 IAM 사용자를 생성합니다.  

```
aws iam create-user \
    --user-name Bob \
    --path /division_abc/subdivision_xyz/
```
출력:  

```
{
    "User": {
        "Path": "/division_abc/subdivision_xyz/",
        "UserName": "Bob",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::12345678012:user/division_abc/subdivision_xyz/Bob",
        "CreateDate": "2023-05-24T18:20:17+00:00"
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 식별자](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html)를 참조하세요.  
**예제 3: 태그가 포함된 IAM 사용자 생성**  
다음 `create-user` 명령은 태그가 포함된 이름이 `Bob`인 IAM 사용자를 생성합니다. 이 예제에서는 다음 JSON 형식의 태그(`'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`)에 `--tags` 파라미터 플래그를 사용합니다. 또는 `--tags` 플래그를 짧은 형식의 태그(`'Key=Department,Value=Accounting Key=Location,Value=Seattle'`)에 사용할 수도 있습니다.  

```
aws iam create-user \
    --user-name Bob \
    --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'
```
출력:  

```
{
    "User": {
        "Path": "/",
        "UserName": "Bob",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::12345678012:user/Bob",
        "CreateDate": "2023-05-25T17:14:21+00:00",
        "Tags": [
            {
                "Key": "Department",
                "Value": "Accounting"
            },
            {
                "Key": "Location",
                "Value": "Seattle"
            }
        ]
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자 태깅](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_users.html)을 참조하세요.  
**예제 3: 권한 경계가 설정된 IAM 사용자 생성**  
다음 `create-user` 명령은 AmazonS3FullAccess의 권한 경계가 포함되어 있으며 이름이 `Bob`인 IAM 사용자를 생성합니다.  

```
aws iam create-user \
    --user-name Bob \
    --permissions-boundary arn:aws:iam::aws:policy/AmazonS3FullAccess
```
출력:  

```
{
    "User": {
        "Path": "/",
        "UserName": "Bob",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::12345678012:user/Bob",
        "CreateDate": "2023-05-24T17:50:53+00:00",
        "PermissionsBoundary": {
        "PermissionsBoundaryType": "Policy",
        "PermissionsBoundaryArn": "arn:aws:iam::aws:policy/AmazonS3FullAccess"
        }
    }
}
```
자세한 정보는 *AWS IAM 사용 설명서*의 [IAM 엔터티의 권한 경계](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-user.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// CreateUser creates a new user with the specified name.
func (wrapper UserWrapper) CreateUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.CreateUser(ctx, &iam.CreateUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
	} else {
		user = result.User
	}
	return user, err
}
```
+  API 세부 정보는 [AWS SDK for Go API 참조](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateUser)의 *CreateUser*를 참조하십시오.

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

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

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.iam.model.CreateUserRequest;
import software.amazon.awssdk.services.iam.model.CreateUserResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.waiters.IamWaiter;
import software.amazon.awssdk.services.iam.model.GetUserRequest;
import software.amazon.awssdk.services.iam.model.GetUserResponse;

/**
 * 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 CreateUser {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <username>\s

                Where:
                    username - The name of the user to create.\s
                """;

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

        String username = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        String result = createIAMUser(iam, username);
        System.out.println("Successfully created user: " + result);
        iam.close();
    }

    public static String createIAMUser(IamClient iam, String username) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();

            CreateUserRequest request = CreateUserRequest.builder()
                    .userName(username)
                    .build();

            CreateUserResponse response = iam.createUser(request);

            // Wait until the user is created.
            GetUserRequest userRequest = GetUserRequest.builder()
                    .userName(response.user().userName())
                    .build();

            WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);
            waitUntilUserExists.matched().response().ifPresent(System.out::println);
            return response.user().userName();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API 세부 정보는 [AWS SDK for Java 2.x API 참조](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateUser)의 *CreateUser*를 참조하십시오.

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

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

```
import { CreateUserCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} name
 */
export const createUser = (name) => {
  const command = new CreateUserCommand({ UserName: name });
  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-creating-users)를 참조하세요.
+  API 세부 정보는 [AWS SDK for JavaScript API 참조](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateUserCommand)의 *CreateUser*를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
};

iam.getUser(params, function (err, data) {
  if (err && err.code === "NoSuchEntity") {
    iam.createUser(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data);
      }
    });
  } else {
    console.log(
      "User " + process.argv[2] + " already exists",
      data.User.UserId
    );
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-creating-users)를 참조하세요.
+  API 세부 정보는 [AWS SDK for JavaScript API 참조](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreateUser)의 *CreateUser*를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun createIAMUser(usernameVal: String?): String? {
    val request =
        CreateUserRequest {
            userName = usernameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createUser(request)
        return response.user?.userName
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

$user = $service->createUser("iam_demo_user_$uuid");
echo "Created user with the arn: {$user['Arn']}\n";


    /**
     * @param string $name
     * @return array
     * @throws AwsException
     */
    public function createUser(string $name): array
    {
        $result = $this->iamClient->createUser([
            'UserName' => $name,
        ]);

        return $result['User'];
    }
```
+  API 세부 정보는 [AWS SDK for PHP API 참조](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateUser)의 *CreateUser*를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자를 생성합니다. Bob이 AWS 콘솔에 로그인해야 하는 경우 명령을 별도로 실행`New-IAMLoginProfile`하여 암호로 로그인 프로필을 생성해야 합니다. Bob이 AWS PowerShell 또는 교차 플랫폼 CLI 명령을 실행하거나 AWS API 호출을 수행해야 하는 경우 `New-IAMAccessKey` 명령을 별도로 실행하여 액세스 키를 생성해야 합니다.**  

```
New-IAMUser -UserName Bob
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 4/22/2015 12:02:11 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : AIDAJWGEFDMEMEXAMPLE1
UserName         : Bob
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateUser](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자를 생성합니다. Bob이 AWS 콘솔에 로그인해야 하는 경우 명령을 별도로 실행`New-IAMLoginProfile`하여 암호로 로그인 프로필을 생성해야 합니다. Bob이 AWS PowerShell 또는 교차 플랫폼 CLI 명령을 실행하거나 AWS API 호출을 수행해야 하는 경우 `New-IAMAccessKey` 명령을 별도로 실행하여 액세스 키를 생성해야 합니다.**  

```
New-IAMUser -UserName Bob
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 4/22/2015 12:02:11 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : AIDAJWGEFDMEMEXAMPLE1
UserName         : Bob
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateUser](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def create_user(user_name):
    """
    Creates a user. By default, a user has no permissions or access keys.

    :param user_name: The name of the user.
    :return: The newly created user.
    """
    try:
        user = iam.create_user(UserName=user_name)
        logger.info("Created user %s.", user.name)
    except ClientError:
        logger.exception("Couldn't create user %s.", user_name)
        raise
    else:
        return user
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateUser)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Creates a user and their login profile
  #
  # @param user_name [String] The name of the user
  # @param initial_password [String] The initial password for the user
  # @return [String, nil] The ID of the user if created, or nil if an error occurred
  def create_user(user_name, initial_password)
    response = @iam_client.create_user(user_name: user_name)
    @iam_client.wait_until(:user_exists, user_name: user_name)
    @iam_client.create_login_profile(
      user_name: user_name,
      password: initial_password,
      password_reset_required: true
    )
    @logger.info("User '#{user_name}' created successfully.")
    response.user.user_id
  rescue Aws::IAM::Errors::EntityAlreadyExists
    @logger.error("Error creating user '#{user_name}': user already exists.")
    nil
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating user '#{user_name}': #{e.message}")
    nil
  end
```
+  API 세부 정보는 [AWS SDK for Ruby API 참조](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateUser)의 *CreateUser*를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn create_user(client: &iamClient, user_name: &str) -> Result<User, iamError> {
    let response = client.create_user().user_name(user_name).send().await?;

    Ok(response.user.unwrap())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_user)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->createuser(
          iv_username = iv_user_name ).
        MESSAGE 'User created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'User already exists.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Limit exceeded for IAM users.' TYPE 'E'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Entity does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [CreateUser](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func createUser(name: String) async throws -> String {
        let input = CreateUserInput(
            userName: name
        )
        do {
            let output = try await client.createUser(input: input)
            guard let user = output.user else {
                throw ServiceHandlerError.noSuchUser
            }
            guard let id = user.userId else {
                throw ServiceHandlerError.noSuchUser
            }
            return id
        } catch {
            print("ERROR: createUser:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreateUser](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createuser(input:))를 참조하세요.

------

# CLI로 `CreateVirtualMfaDevice` 사용
<a name="iam_example_iam_CreateVirtualMfaDevice_section"></a>

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

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

**AWS CLI**  
**가상 MFA 디바이스 생성**  
이 예제는 `BobsMFADevice`라는 새 가상 MFA 디바이스를 생성합니다. 부트스트랩 정보가 포함된 `QRCode.png`라는 파일을 생성하여 `C:/` 디렉터리에 배치합니다. 이 예제에서 사용된 부트스트랩 방법은 `QRCodePNG`입니다.  

```
aws iam create-virtual-mfa-device \
    --virtual-mfa-device-name BobsMFADevice \
    --outfile C:/QRCode.png \
    --bootstrap-method QRCodePNG
```
출력:  

```
{
    "VirtualMFADevice": {
        "SerialNumber": "arn:aws:iam::210987654321:mfa/BobsMFADevice"
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [AWS에서 다중 인증(MFA) 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateVirtualMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-virtual-mfa-device.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 새 가상 MFA 디바이스를 생성합니다. 줄 2와 3은 가상 MFA 소프트웨어 프로그램에서 계정을 생성하는 데 필요한 `Base32StringSeed` 값을 QR 코드의 대안으로 추출합니다. 값으로 프로그램을 구성한 후 프로그램에서 두 개의 순차적 인증 코드를 받습니다. 끝으로 마지막 명령을 사용하여 가상 MFA 디바이스를 IAM 사용자 `Bob`에게 연결하고 계정을 두 개의 인증 코드와 동기화합니다.**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$SR = New-Object System.IO.StreamReader($Device.Base32StringSeed)
$base32stringseed = $SR.ReadToEnd()
$base32stringseed   
CZWZMCQNW4DEXAMPLE3VOUGXJFZYSUW7EXAMPLECR4NJFD65GX2SLUDW2EXAMPLE
```
**출력:**  

```
-- Pause here to enter base-32 string seed code into virtual MFA program to register account. --

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
**예제 2: 이 예제는 새 가상 MFA 디바이스를 생성합니다. 줄 2와 3은 `QRCodePNG` 값을 추출하여 파일에 씁니다. Base32StringSeed 값을 수동으로 입력하는 대신 가상 MFA 소프트웨어 프로그램에서 이 이미지를 스캔하여 계정을 생성할 수 있습니다. 가상 MFA 프로그램에서 계정을 생성한 후 두 개의 순차적 인증 코드를 받아 마지막 명령에 입력하여 가상 MFA 디바이스를 IAM 사용자 `Bob`에게 연결하고 계정을 동기화합니다.**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$BR = New-Object System.IO.BinaryReader($Device.QRCodePNG)
$BR.ReadBytes($BR.BaseStream.Length) | Set-Content -Encoding Byte -Path QRCode.png
```
**출력:**  

```
 -- Pause here to scan PNG with virtual MFA program to register account. -- 

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 새 가상 MFA 디바이스를 생성합니다. 줄 2와 3은 가상 MFA 소프트웨어 프로그램에서 계정을 생성하는 데 필요한 `Base32StringSeed` 값을 QR 코드의 대안으로 추출합니다. 값으로 프로그램을 구성한 후 프로그램에서 두 개의 순차적 인증 코드를 받습니다. 끝으로 마지막 명령을 사용하여 가상 MFA 디바이스를 IAM 사용자 `Bob`에게 연결하고 계정을 두 개의 인증 코드와 동기화합니다.**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$SR = New-Object System.IO.StreamReader($Device.Base32StringSeed)
$base32stringseed = $SR.ReadToEnd()
$base32stringseed   
CZWZMCQNW4DEXAMPLE3VOUGXJFZYSUW7EXAMPLECR4NJFD65GX2SLUDW2EXAMPLE
```
**출력:**  

```
-- Pause here to enter base-32 string seed code into virtual MFA program to register account. --

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
**예제 2: 이 예제는 새 가상 MFA 디바이스를 생성합니다. 줄 2와 3은 `QRCodePNG` 값을 추출하여 파일에 씁니다. Base32StringSeed 값을 수동으로 입력하는 대신 가상 MFA 소프트웨어 프로그램에서 이 이미지를 스캔하여 계정을 생성할 수 있습니다. 가상 MFA 프로그램에서 계정을 생성한 후 두 개의 순차적 인증 코드를 받아 마지막 명령에 입력하여 가상 MFA 디바이스를 IAM 사용자 `Bob`에게 연결하고 계정을 동기화합니다.**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$BR = New-Object System.IO.BinaryReader($Device.QRCodePNG)
$BR.ReadBytes($BR.BaseStream.Length) | Set-Content -Encoding Byte -Path QRCode.png
```
**출력:**  

```
 -- Pause here to scan PNG with virtual MFA program to register account. -- 

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DeactivateMfaDevice` 사용
<a name="iam_example_iam_DeactivateMfaDevice_section"></a>

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

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

**AWS CLI**  
**MFA 디바이스 비활성화**  
이 명령은 사용자 `Bob`과 연결된 ARN `arn:aws:iam::210987654321:mfa/BobsMFADevice`의 가상 MFA 디바이스를 비활성화합니다.  

```
aws iam deactivate-mfa-device \
    --user-name Bob \
    --serial-number arn:aws:iam::210987654321:mfa/BobsMFADevice
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [AWS에서 다중 인증(MFA) 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeactivateMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/deactivate-mfa-device.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 일련 번호 `123456789012`를 가진 사용자 `Bob`과 연결된 하드웨어 MFA 디바이스를 비활성화합니다.**  

```
Disable-IAMMFADevice -UserName "Bob" -SerialNumber "123456789012"
```
**예제 2: 이 명령은 ARN `arn:aws:iam::210987654321:mfa/David`를 가진 사용자 `David`과 연결된 가상 MFA 디바이스를 비활성화합니다. 단, 가상 MFA 디바이스는 계정에서 삭제되지 않습니다. 가상 디바이스는 여전히 존재하며 `Get-IAMVirtualMFADevice` 명령 출력에 나타납니다. 동일한 사용자를 위한 새 가상 MFA 디바이스를 생성하려면 먼저 `Remove-IAMVirtualMFADevice` 명령을 사용하여 이전 디바이스를 삭제해야 합니다.**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeactivateMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 일련 번호 `123456789012`를 가진 사용자 `Bob`과 연결된 하드웨어 MFA 디바이스를 비활성화합니다.**  

```
Disable-IAMMFADevice -UserName "Bob" -SerialNumber "123456789012"
```
**예제 2: 이 명령은 ARN `arn:aws:iam::210987654321:mfa/David`를 가진 사용자 `David`과 연결된 가상 MFA 디바이스를 비활성화합니다. 단, 가상 MFA 디바이스는 계정에서 삭제되지 않습니다. 가상 디바이스는 여전히 존재하며 `Get-IAMVirtualMFADevice` 명령 출력에 나타납니다. 동일한 사용자를 위한 새 가상 MFA 디바이스를 생성하려면 먼저 `Remove-IAMVirtualMFADevice` 명령을 사용하여 이전 디바이스를 삭제해야 합니다.**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeactivateMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](iam_example_iam_Scenario_CreateUserAssumeRole_section.md) 
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 
+  [ 액세스 키 관리](iam_example_iam_Scenario_ManageAccessKeys_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// Delete an IAM user's access key.
    /// </summary>
    /// <param name="accessKeyId">The Id for the IAM access key.</param>
    /// <param name="userName">The username of the user that owns the IAM
    /// access key.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAccessKeyAsync(string accessKeyId, string userName)
    {
        var response = await _IAMService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest
        {
            AccessKeyId = accessKeyId,
            UserName = userName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteAccessKey)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_delete_access_key
#
# This function deletes an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to delete.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_access_key() {
  local user_name access_key response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_access_key"
    echo "Deletes an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:k:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      k) access_key="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  if [[ -z "$access_key" ]]; then
    errecho "ERROR: You must provide an access key with the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Username:   $user_name"
  iecho "    Access key:   $access_key"
  iecho ""

  response=$(aws iam delete-access-key \
    --user-name "$user_name" \
    --access-key-id "$access_key")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-access-key operation failed.\n$response"
    return 1
  fi

  iecho "delete-access-key response:$response"
  iecho

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteAccessKey)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::deleteAccessKey(const Aws::String &userName,
                                  const Aws::String &accessKeyID,
                                  const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DeleteAccessKeyRequest request;
    request.SetUserName(userName);
    request.SetAccessKeyId(accessKeyID);

    auto outcome = iam.DeleteAccessKey(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting access key " << accessKeyID << " from user "
                  << userName << ": " << outcome.GetError().GetMessage() <<
                  std::endl;
    }
    else {
        std::cout << "Successfully deleted access key " << accessKeyID
                  << " for IAM user " << userName << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccessKey)를 참조하세요.

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

**AWS CLI**  
**IAM 사용자의 액세스 키 삭제**  
다음 `delete-access-key` 명령은 이름이 `Bob`인 IAM 사용자의 지정된 액세스 키(액세스 키 ID 및 시크릿 액세스 키)를 삭제합니다.  

```
aws iam delete-access-key \
    --access-key-id AKIDPMS9RO4H3FEXAMPLE \
    --user-name Bob
```
이 명령은 출력을 생성하지 않습니다.  
IAM 사용자에 대해 정의된 액세스 키를 나열하려면 `list-access-keys` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자의 액세스 키 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteAccessKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-access-key.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// DeleteAccessKey deletes an access key from a user.
func (wrapper UserWrapper) DeleteAccessKey(ctx context.Context, userName string, keyId string) error {
	_, err := wrapper.IamClient.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{
		AccessKeyId: aws.String(keyId),
		UserName:    aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete access key %v. Here's why: %v\n", keyId, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DeleteAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteAccessKey)를 참조하십시오.

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

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

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeleteAccessKey {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <username> <accessKey>\s

                Where:
                    username - The name of the user.\s
                    accessKey - The access key ID for the secret access key you want to delete.\s
                """;

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

        String username = args[0];
        String accessKey = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();
        deleteKey(iam, username, accessKey);
        iam.close();
    }

    public static void deleteKey(IamClient iam, String username, String accessKey) {
        try {
            DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()
                    .accessKeyId(accessKey)
                    .userName(username)
                    .build();

            iam.deleteAccessKey(request);
            System.out.println("Successfully deleted access key " + accessKey +
                    " from user " + username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccessKey)를 참조하십시오.

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

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

```
import { DeleteAccessKeyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} userName
 * @param {string} accessKeyId
 */
export const deleteAccessKey = (userName, accessKeyId) => {
  const command = new DeleteAccessKeyCommand({
    AccessKeyId: accessKeyId,
    UserName: userName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-deleting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccessKeyCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  AccessKeyId: "ACCESS_KEY_ID",
  UserName: "USER_NAME",
};

iam.deleteAccessKey(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-deleting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteAccessKey)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun deleteKey(
    userNameVal: String,
    accessKey: String,
) {
    val request =
        DeleteAccessKeyRequest {
            accessKeyId = accessKey
            userName = userNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deleteAccessKey(request)
        println("Successfully deleted access key $accessKey from $userNameVal")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DeleteAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제에서는 이름이 인 사용자`AKIAIOSFODNN7EXAMPLE`로부터 키 ID가 인 AWS 액세스 키 페어를 삭제합니다`Bob`.**  

```
Remove-IAMAccessKey -AccessKeyId AKIAIOSFODNN7EXAMPLE -UserName Bob -Force
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteAccessKey](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제에서는 이름이 인 사용자`AKIAIOSFODNN7EXAMPLE`로부터 키 ID가 인 AWS 액세스 키 페어를 삭제합니다`Bob`.**  

```
Remove-IAMAccessKey -AccessKeyId AKIAIOSFODNN7EXAMPLE -UserName Bob -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteAccessKey](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def delete_key(user_name, key_id):
    """
    Deletes a user's access key.

    :param user_name: The user that owns the key.
    :param key_id: The ID of the key to delete.
    """

    try:
        key = iam.AccessKey(user_name, key_id)
        key.delete()
        logger.info("Deleted access key %s for %s.", key.id, key.user_name)
    except ClientError:
        logger.exception("Couldn't delete key %s for %s", key_id, user_name)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 액세스 키를 나열, 생성, 비활성화 및 삭제합니다.  

```
# Manages access keys for IAM users
class AccessKeyManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'AccessKeyManager'
  end

  # Lists access keys for a user
  #
  # @param user_name [String] The name of the user.
  def list_access_keys(user_name)
    response = @iam_client.list_access_keys(user_name: user_name)
    if response.access_key_metadata.empty?
      @logger.info("No access keys found for user '#{user_name}'.")
    else
      response.access_key_metadata.map(&:access_key_id)
    end
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Error listing access keys: cannot find user '#{user_name}'.")
    []
  rescue StandardError => e
    @logger.error("Error listing access keys: #{e.message}")
    []
  end

  # Creates an access key for a user
  #
  # @param user_name [String] The name of the user.
  # @return [Boolean]
  def create_access_key(user_name)
    response = @iam_client.create_access_key(user_name: user_name)
    access_key = response.access_key
    @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}")
    access_key
  rescue Aws::IAM::Errors::LimitExceeded
    @logger.error('Error creating access key: limit exceeded. Cannot create more.')
    nil
  rescue StandardError => e
    @logger.error("Error creating access key: #{e.message}")
    nil
  end

  # Deactivates an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def deactivate_access_key(user_name, access_key_id)
    @iam_client.update_access_key(
      user_name: user_name,
      access_key_id: access_key_id,
      status: 'Inactive'
    )
    true
  rescue StandardError => e
    @logger.error("Error deactivating access key: #{e.message}")
    false
  end

  # Deletes an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def delete_access_key(user_name, access_key_id)
    @iam_client.delete_access_key(
      user_name: user_name,
      access_key_id: access_key_id
    )
    true
  rescue StandardError => e
    @logger.error("Error deleting access key: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccessKey)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn delete_access_key(
    client: &iamClient,
    user: &User,
    key: &AccessKey,
) -> Result<(), iamError> {
    loop {
        match client
            .delete_access_key()
            .user_name(user.user_name())
            .access_key_id(key.access_key_id())
            .send()
            .await
        {
            Ok(_) => {
                break;
            }
            Err(e) => {
                println!("Can't delete the access key: {:?}", e);
                sleep(Duration::from_secs(2)).await;
            }
        }
    }
    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_access_key)을 참조하세요.

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

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

```
    TRY.
        lo_iam->deleteaccesskey(
          iv_accesskeyid = iv_access_key_id
          iv_username = iv_user_name ).
        MESSAGE 'Access key deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Access key or user does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteAccessKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func deleteAccessKey(user: IAMClientTypes.User? = nil,
                                key: IAMClientTypes.AccessKey) async throws
    {
        let userName: String?

        if user != nil {
            userName = user!.userName
        } else {
            userName = nil
        }

        let input = DeleteAccessKeyInput(
            accessKeyId: key.accessKeyId,
            userName: userName
        )
        do {
            _ = try await iamClient.deleteAccessKey(input: input)
        } catch {
            print("ERROR: deleteAccessKey:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeleteAccessKey](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleteaccesskey(input:))를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [계정 관리](iam_example_iam_Scenario_AccountManagement_section.md) 

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::deleteAccountAlias(const Aws::String &accountAlias,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DeleteAccountAliasRequest request;
    request.SetAccountAlias(accountAlias);

    const auto outcome = iam.DeleteAccountAlias(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting account alias " << accountAlias << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully deleted account alias " << accountAlias <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeleteAccountAlias](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccountAlias)를 참조하세요.

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

**AWS CLI**  
**계정 별칭 삭제**  
다음 `delete-account-alias` 명령은 현재 계정의 별칭 `mycompany`를 제거합니다.  

```
aws iam delete-account-alias \
    --account-alias mycompany
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [AWS 계정 ID 및 별칭](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteAccountAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-account-alias.html)를 참조하세요.

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

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

```
import software.amazon.awssdk.services.iam.model.DeleteAccountAliasRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeleteAccountAlias {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <alias>\s

                Where:
                    alias - The account alias to delete.\s
                """;

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

        String alias = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        deleteIAMAccountAlias(iam, alias);
        iam.close();
    }

    public static void deleteIAMAccountAlias(IamClient iam, String alias) {
        try {
            DeleteAccountAliasRequest request = DeleteAccountAliasRequest.builder()
                    .accountAlias(alias)
                    .build();

            iam.deleteAccountAlias(request);
            System.out.println("Successfully deleted account alias " + alias);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DeleteAccountAlias](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccountAlias)를 참조하십시오.

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

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

```
import { DeleteAccountAliasCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} alias
 */
export const deleteAccountAlias = (alias) => {
  const command = new DeleteAccountAliasCommand({ AccountAlias: alias });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-deleting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteAccountAlias](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccountAliasCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.deleteAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-deleting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteAccountAlias](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteAccountAlias)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun deleteIAMAccountAlias(alias: String) {
    val request =
        DeleteAccountAliasRequest {
            accountAlias = alias
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deleteAccountAlias(request)
        println("Successfully deleted account alias $alias")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DeleteAccountAlias](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제는에서 계정 별칭을 제거합니다 AWS 계정. https://mycompanyaws.signin.aws.amazon.com/console에서 별칭을 사용하는 사용자 로그인 페이지가 더 이상 작동하지 않습니다. 대신 https://<accountidnumber>.signin.aws.amazon.com/console AWS 계정 ID 번호와 함께 원래 URL을 사용해야 합니다.**  

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

**Tools for PowerShell V5**  
**예제 1:이 예제는에서 계정 별칭을 제거합니다 AWS 계정. https://mycompanyaws.signin.aws.amazon.com/console에서 별칭을 사용하는 사용자 로그인 페이지가 더 이상 작동하지 않습니다. 대신 https://<accountidnumber>.signin.aws.amazon.com/console AWS 계정 ID 번호와 함께 원래 URL을 사용해야 합니다.**  

```
Remove-IAMAccountAlias -AccountAlias mycompanyaws
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteAccountAlias](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def delete_alias(alias):
    """
    Removes the alias from the current account.

    :param alias: The alias to remove.
    """
    try:
        iam.meta.client.delete_account_alias(AccountAlias=alias)
        logger.info("Removed alias '%s' from your account.", alias)
    except ClientError:
        logger.exception("Couldn't remove alias '%s' from your account.", alias)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteAccountAlias](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccountAlias)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
계정 별칭을 나열하고, 생성하고, 삭제합니다.  

```
class IAMAliasManager
  # Initializes the IAM client and logger
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists available AWS account aliases.
  def list_aliases
    response = @iam_client.list_account_aliases

    if response.account_aliases.count.positive?
      @logger.info('Account aliases are:')
      response.account_aliases.each { |account_alias| @logger.info("  #{account_alias}") }
    else
      @logger.info('No account aliases found.')
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing account aliases: #{e.message}")
  end

  # Creates an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to create.
  # @return [Boolean] true if the account alias was created; otherwise, false.
  def create_account_alias(account_alias)
    @iam_client.create_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating account alias: #{e.message}")
    false
  end

  # Deletes an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to delete.
  # @return [Boolean] true if the account alias was deleted; otherwise, false.
  def delete_account_alias(account_alias)
    @iam_client.delete_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting account alias: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DeleteAccountAlias](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccountAlias)를 참조하세요.

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

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

```
    TRY.
        lo_iam->deleteaccountalias(
          iv_accountalias = iv_account_alias ).
        MESSAGE 'Account alias deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Account alias does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteAccountAlias](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `DeleteAccountPasswordPolicy` 사용
<a name="iam_example_iam_DeleteAccountPasswordPolicy_section"></a>

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

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

**AWS CLI**  
**현재 계정 암호 정책 삭제**  
다음 `delete-account-password-policy` 명령은 현재 계정의 암호 정책을 제거합니다.  

```
aws iam delete-account-password-policy
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자의 계정 암호 정책 설정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteAccountPasswordPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-account-password-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제에서는에 대한 암호 정책을 삭제 AWS 계정 하고 모든 값을 원래 기본값으로 재설정합니다. 암호 정책이 현재 존재하지 않는 경우 다음과 같은 오류 메시지가 나타납니다. PasswordPolicy라는 계정 정책을 찾을 수 없습니다.**  

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

**Tools for PowerShell V5**  
**예제 1:이 예제에서는에 대한 암호 정책을 삭제 AWS 계정 하고 모든 값을 원래 기본값으로 재설정합니다. 암호 정책이 현재 존재하지 않는 경우 다음과 같은 오류 메시지가 나타납니다. PasswordPolicy라는 계정 정책을 찾을 수 없습니다.**  

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

------

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

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

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

**AWS CLI**  
**IAM 그룹 삭제**  
다음 `delete-group` 명령은 이름이 `MyTestGroup`인 IAM 그룹을 삭제합니다.  

```
aws iam delete-group \
    --group-name MyTestGroup
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 그룹 삭제](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_delete.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-group.html)을 참조하세요.

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

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

```
import { DeleteGroupCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} groupName
 */
export const deleteGroup = async (groupName) => {
  const command = new DeleteGroupCommand({
    GroupName: groupName,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteGroupCommand)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `MyTestGroup`이라는 IAM 그룹을 삭제합니다. 첫 번째 명령은 그룹 멤버인 IAM 사용자를 모두 제거하고, 두 번째 명령은 IAM 그룹을 삭제합니다. 두 명령 모두 확인 프롬프트 없이 작동합니다.**  

```
(Get-IAMGroup -GroupName MyTestGroup).Users | Remove-IAMUserFromGroup -GroupName MyTestGroup -Force
Remove-IAMGroup -GroupName MyTestGroup -Force
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `MyTestGroup`이라는 IAM 그룹을 삭제합니다. 첫 번째 명령은 그룹 멤버인 IAM 사용자를 모두 제거하고, 두 번째 명령은 IAM 그룹을 삭제합니다. 두 명령 모두 확인 프롬프트 없이 작동합니다.**  

```
(Get-IAMGroup -GroupName MyTestGroup).Users | Remove-IAMUserFromGroup -GroupName MyTestGroup -Force
Remove-IAMGroup -GroupName MyTestGroup -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `DeleteGroupPolicy` 사용
<a name="iam_example_iam_DeleteGroupPolicy_section"></a>

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

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

**AWS CLI**  
**IAM 그룹에서 정책 삭제**  
다음 `delete-group-policy` 명령은 이름이 `Admins`인 그룹에서 이름이 `ExamplePolicy`인 정책을 삭제합니다.  

```
aws iam delete-group-policy \
    --group-name Admins \
    --policy-name ExamplePolicy
```
이 명령은 출력을 생성하지 않습니다.  
그룹에 연결된 정책을 보려면 `list-group-policies` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 정책 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-group-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 그룹 `Testers`에서 `TesterPolicy`라는 인라인 정책을 제거합니다. 해당 그룹의 사용자는 해당 정책에 정의된 권한을 즉시 잃게 됩니다.**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 그룹 `Testers`에서 `TesterPolicy`라는 인라인 정책을 제거합니다. 해당 그룹의 사용자는 해당 정책에 정의된 권한을 즉시 잃게 됩니다.**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [복원력이 뛰어난 서비스 구축 및 관리](iam_example_cross_ResilientService_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// Detaches a role from an instance profile, detaches policies from the role,
    /// and deletes all the resources.
    /// </summary>
    /// <param name="profileName">The name of the profile to delete.</param>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteInstanceProfile(string profileName, string roleName)
    {
        try
        {
            await _amazonIam.RemoveRoleFromInstanceProfileAsync(
                new RemoveRoleFromInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });
            await _amazonIam.DeleteInstanceProfileAsync(
                new DeleteInstanceProfileRequest() { InstanceProfileName = profileName });
            var attachedPolicies = await _amazonIam.ListAttachedRolePoliciesAsync(
                new ListAttachedRolePoliciesRequest() { RoleName = roleName });
            foreach (var policy in attachedPolicies.AttachedPolicies)
            {
                await _amazonIam.DetachRolePolicyAsync(
                    new DetachRolePolicyRequest()
                    {
                        RoleName = roleName,
                        PolicyArn = policy.PolicyArn
                    });
                // Delete the custom policies only.
                if (!policy.PolicyArn.StartsWith("arn:aws:iam::aws"))
                {
                    await _amazonIam.DeletePolicyAsync(
                        new Amazon.IdentityManagement.Model.DeletePolicyRequest()
                        {
                            PolicyArn = policy.PolicyArn
                        });
                }
            }

            await _amazonIam.DeleteRoleAsync(
                new DeleteRoleRequest() { RoleName = roleName });
        }
        catch (NoSuchEntityException)
        {
            Console.WriteLine($"Instance profile {profileName} does not exist.");
        }
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteInstanceProfile)을 참조하세요.

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

**AWS CLI**  
**인스턴스 프로파일 삭제**  
다음 `delete-instance-profile` 명령은 이름이 `ExampleInstanceProfile`인 인스턴스 프로파일을 삭제합니다.  

```
aws iam delete-instance-profile \
    --instance-profile-name ExampleInstanceProfile
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [인스턴스 프로파일 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-instance-profile.html)을 참조하세요.

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

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

```
      const client = new IAMClient({});
      await client.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteInstanceProfileCommand)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `MyAppInstanceProfile`이라는 EC2 인스턴스 프로파일을 삭제합니다. 첫 번째 명령은 인스턴스 프로파일에서 모든 역할을 분리하고, 두 번째 명령은 인스턴스 프로파일을 삭제합니다.**  

```
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `MyAppInstanceProfile`이라는 EC2 인스턴스 프로파일을 삭제합니다. 첫 번째 명령은 인스턴스 프로파일에서 모든 역할을 분리하고, 두 번째 명령은 인스턴스 프로파일을 삭제합니다.**  

```
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteInstanceProfile](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예제에서는 인스턴스 프로파일에서 역할을 제거하고 역할에 연결된 모든 정책을 분리하며 모든 리소스를 삭제합니다.  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def delete_instance_profile(self, profile_name: str, role_name: str) -> None:
        """
        Detaches a role from an instance profile, detaches policies from the role,
        and deletes all the resources.

        :param profile_name: The name of the profile to delete.
        :param role_name: The name of the role to delete.
        """
        try:
            self.iam_client.remove_role_from_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            self.iam_client.delete_instance_profile(InstanceProfileName=profile_name)
            log.info("Deleted instance profile %s.", profile_name)
            attached_policies = self.iam_client.list_attached_role_policies(
                RoleName=role_name
            )
            for pol in attached_policies["AttachedPolicies"]:
                self.iam_client.detach_role_policy(
                    RoleName=role_name, PolicyArn=pol["PolicyArn"]
                )
                if not pol["PolicyArn"].startswith("arn:aws:iam::aws"):
                    self.iam_client.delete_policy(PolicyArn=pol["PolicyArn"])
                log.info("Detached and deleted policy %s.", pol["PolicyName"])
            self.iam_client.delete_role(RoleName=role_name)
            log.info("Deleted role %s.", role_name)
        except ClientError as err:
            log.error(
                f"Couldn't delete instance profile {profile_name} or detach "
                f"policies and delete role {role_name}: {err}"
            )
            if err.response["Error"]["Code"] == "NoSuchEntity":
                log.info(
                    "Instance profile %s doesn't exist, nothing to do.", profile_name
                )
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteInstanceProfile)를 참조하세요.

------

# CLI로 `DeleteLoginProfile` 사용
<a name="iam_example_iam_DeleteLoginProfile_section"></a>

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

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

**AWS CLI**  
**IAM 사용자의 암호 삭제**  
다음 `delete-login-profile` 명령은 이름이 `Bob`인 IAM 사용자의 암호를 삭제합니다.  

```
aws iam delete-login-profile \
    --user-name Bob
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자 암호 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-login-profile.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자로부터 로그인 프로파일을 삭제합니다. 이렇게 하면 사용자가 AWS 콘솔에 로그인할 수 없습니다. 이는 사용자가 여전히 사용자 계정에 연결될 수 있는 AWS 액세스 키를 사용하여 AWS CLI, PowerShell 또는 API 호출을 실행하는 것을 방지하지 않습니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자로부터 로그인 프로파일을 삭제합니다. 이렇게 하면 사용자가 AWS 콘솔에 로그인할 수 없습니다. 이는 사용자가 여전히 사용자 계정에 연결될 수 있는 AWS 액세스 키를 사용하여 AWS CLI, PowerShell 또는 API 호출을 실행하는 것을 방지하지 않습니다.**  

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

------

# CLI로 `DeleteOpenIdConnectProvider` 사용
<a name="iam_example_iam_DeleteOpenIdConnectProvider_section"></a>

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

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

**AWS CLI**  
**IAM OpenID Connect ID 제공업체 삭제**  
이 예제는 제공업체 `example.oidcprovider.com`에 연결되는 IAM OIDC 제공업체를 삭제합니다.  

```
aws iam delete-open-id-connect-provider \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM에서 OIDC(OpenID Connect) ID 제공업체 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-open-id-connect-provider.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 제공업체 `example.oidcprovider.com`에 연결되는 IAM OIDC 제공업체를 삭제합니다. 역할 신뢰 정책의 `Principal` 요소에서 이 제공업체를 참조하는 모든 역할을 업데이트하거나 삭제해야 합니다.**  

```
Remove-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 제공업체 `example.oidcprovider.com`에 연결되는 IAM OIDC 제공업체를 삭제합니다. 역할 신뢰 정책의 `Principal` 요소에서 이 제공업체를 참조하는 모든 역할을 업데이트하거나 삭제해야 합니다.**  

```
Remove-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [기본 사항 알아보기](iam_example_iam_Scenario_CreateUserAssumeRole_section.md) 
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// Delete an IAM policy.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the policy to
    /// delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeletePolicyAsync(string policyArn)
    {
        var response = await _IAMService.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeletePolicy)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_delete_policy
#
# This function deletes an IAM policy.
#
# Parameters:
#       -n policy_arn -- The name of the IAM policy arn.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_policy() {
  local policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_policy"
    echo "Deletes an AWS Identity and Access Management (IAM) policy"
    echo "  -n policy_arn -- The name of the IAM policy arn."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy arn with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Policy arn:  $policy_arn"
  iecho ""

  response=$(aws iam delete-policy \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-policy operation failed.\n$response"
    return 1
  fi

  iecho "delete-policy response:$response"
  iecho

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeletePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeletePolicy)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::deletePolicy(const Aws::String &policyArn,
                               const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::DeletePolicyRequest request;
    request.SetPolicyArn(policyArn);

    auto outcome = iam.DeletePolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting policy with arn " << policyArn << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully deleted policy with arn " << policyArn
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeletePolicy)를 참조하세요.

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

**AWS CLI**  
**IAM 정책 삭제**  
이 예제에서는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 정책을 삭제합니다.  

```
aws iam delete-policy \
    --policy-arn arn:aws:iam::123456789012:policy/MySamplePolicy
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// DeletePolicy deletes a policy.
func (wrapper PolicyWrapper) DeletePolicy(ctx context.Context, policyArn string) error {
	_, err := wrapper.IamClient.DeletePolicy(ctx, &iam.DeletePolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't delete policy %v. Here's why: %v\n", policyArn, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DeletePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeletePolicy)를 참조하십시오.

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

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

```
import software.amazon.awssdk.services.iam.model.DeletePolicyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeletePolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <policyARN>\s

                Where:
                    policyARN - A policy ARN value to delete.\s
                """;

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

        String policyARN = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        deleteIAMPolicy(iam, policyARN);
        iam.close();
    }

    public static void deleteIAMPolicy(IamClient iam, String policyARN) {
        try {
            DeletePolicyRequest request = DeletePolicyRequest.builder()
                    .policyArn(policyARN)
                    .build();

            iam.deletePolicy(request);
            System.out.println("Successfully deleted the policy");

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeletePolicy)를 참조하십시오.

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

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

```
import { DeletePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 */
export const deletePolicy = (policyArn) => {
  const command = new DeletePolicyCommand({ PolicyArn: policyArn });
  return client.send(command);
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeletePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeletePolicyCommand)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun deleteIAMPolicy(policyARNVal: String?) {
    val request =
        DeletePolicyRequest {
            policyArn = policyARNVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deletePolicy(request)
        println("Successfully deleted $policyARNVal")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DeletePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 정책을 삭제합니다. 정책을 삭제하려면 먼저 `Remove-IAMPolicyVersion`을 실행하여 기본값을 제외한 모든 버전을 삭제해야 합니다. 또한 모든 IAM 사용자, 그룹 또는 역할에서 정책을 분리해야 합니다.**  

```
Remove-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**예제 2: 이 예제는 먼저 기본이 아닌 모든 정책 버전을 삭제하고 연결된 모든 IAM 엔티티에서 분리한 다음 마지막으로 정책 자체를 삭제하여 정책을 삭제합니다. 줄 1은 정책 객체를 검색합니다. 줄 2는 기본값으로 플래그가 지정되지 않은 모든 정책 버전을 컬렉션으로 검색한 다음 컬렉션의 각 정책을 삭제합니다. 줄 3은 정책이 연결된 모든 IAM 사용자, 그룹 및 역할을 검색합니다. 줄 4\$16은 연결된 각 엔터티에서 정책을 분리합니다. 마지막 줄은 이 명령을 사용하여 관리형 정책과 나머지 기본 버전을 제거합니다. 이 예제에는 확인 프롬프트를 표시하지 않는 데 필요한 모든 줄에 `-Force` 스위치 파라미터가 포함되어 있습니다.**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
$attached = Get-IAMEntitiesForPolicy -PolicyArn $pol.Arn
$attached.PolicyGroups | Unregister-IAMGroupPolicy -PolicyArn $pol.arn
$attached.PolicyRoles | Unregister-IAMRolePolicy -PolicyArn $pol.arn
$attached.PolicyUsers | Unregister-IAMUserPolicy -PolicyArn $pol.arn
Remove-IAMPolicy $pol.Arn -Force
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeletePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 정책을 삭제합니다. 정책을 삭제하려면 먼저 `Remove-IAMPolicyVersion`을 실행하여 기본값을 제외한 모든 버전을 삭제해야 합니다. 또한 모든 IAM 사용자, 그룹 또는 역할에서 정책을 분리해야 합니다.**  

```
Remove-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**예제 2: 이 예제는 먼저 기본이 아닌 모든 정책 버전을 삭제하고 연결된 모든 IAM 엔티티에서 분리한 다음 마지막으로 정책 자체를 삭제하여 정책을 삭제합니다. 줄 1은 정책 객체를 검색합니다. 줄 2는 기본값으로 플래그가 지정되지 않은 모든 정책 버전을 컬렉션으로 검색한 다음 컬렉션의 각 정책을 삭제합니다. 줄 3은 정책이 연결된 모든 IAM 사용자, 그룹 및 역할을 검색합니다. 줄 4\$16은 연결된 각 엔터티에서 정책을 분리합니다. 마지막 줄은 이 명령을 사용하여 관리형 정책과 나머지 기본 버전을 제거합니다. 이 예제에는 확인 프롬프트를 표시하지 않는 데 필요한 모든 줄에 `-Force` 스위치 파라미터가 포함되어 있습니다.**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
$attached = Get-IAMEntitiesForPolicy -PolicyArn $pol.Arn
$attached.PolicyGroups | Unregister-IAMGroupPolicy -PolicyArn $pol.arn
$attached.PolicyRoles | Unregister-IAMRolePolicy -PolicyArn $pol.arn
$attached.PolicyUsers | Unregister-IAMUserPolicy -PolicyArn $pol.arn
Remove-IAMPolicy $pol.Arn -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeletePolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def delete_policy(policy_arn):
    """
    Deletes a policy.

    :param policy_arn: The ARN of the policy to delete.
    """
    try:
        iam.Policy(policy_arn).delete()
        logger.info("Deleted policy %s.", policy_arn)
    except ClientError:
        logger.exception("Couldn't delete policy %s.", policy_arn)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn delete_policy(client: &iamClient, policy: Policy) -> Result<(), iamError> {
    client
        .delete_policy()
        .policy_arn(policy.arn.unwrap())
        .send()
        .await?;
    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeletePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_policy)을 참조하세요.

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

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

```
    TRY.
        lo_iam->deletepolicy( iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'Policy cannot be deleted due to attachments.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 [AWS SDK for SAP ABAP API 참조](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)의 *DeletePolicy*를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func deletePolicy(policy: IAMClientTypes.Policy) async throws {
        let input = DeletePolicyInput(
            policyArn: policy.arn
        )
        do {
            _ = try await iamClient.deletePolicy(input: input)
        } catch {
            print("ERROR: deletePolicy:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeletePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deletepolicy(input:))를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 
+  [정책 버전 롤백](iam_example_iam_Scenario_RollbackPolicyVersion_section.md) 

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

**AWS CLI**  
**관리형 정책의 버전 삭제**  
이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 정책에서 `v2`로 식별된 버전을 삭제합니다.  

```
aws iam delete-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --version-id v2
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeletePolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-policy-version.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 정책에서 `v2`로 식별된 버전을 삭제합니다.**  

```
Remove-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy -VersionID v2
```
**예제 2: 이 예제는 먼저 기본이 아닌 모든 정책 버전을 삭제한 다음 정책 자체를 삭제하여 정책을 삭제합니다. 줄 1은 정책 객체를 검색합니다. 줄 2는 기본값으로 플래그가 지정되지 않은 모든 정책 버전을 컬렉션으로 검색한 다음 이 명령을 사용하여 컬렉션의 각 정책을 삭제합니다. 마지막 줄은 나머지 기본 버전뿐만 아니라 정책 자체도 제거합니다. 관리형 정책을 성공적으로 삭제하려면 `Unregister-IAMUserPolicy`, `Unregister-IAMGroupPolicy` 및 `Unregister-IAMRolePolicy` 명령을 사용하여 모든 사용자, 그룹 또는 역할에서 정책을 분리해야 합니다. `Remove-IAMPolicy` cmdlet의 예를 참조하세요.**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
Remove-IAMPolicy -PolicyArn $pol.Arn -force
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeletePolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 정책에서 `v2`로 식별된 버전을 삭제합니다.**  

```
Remove-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy -VersionID v2
```
**예제 2: 이 예제는 먼저 기본이 아닌 모든 정책 버전을 삭제한 다음 정책 자체를 삭제하여 정책을 삭제합니다. 줄 1은 정책 객체를 검색합니다. 줄 2는 기본값으로 플래그가 지정되지 않은 모든 정책 버전을 컬렉션으로 검색한 다음 이 명령을 사용하여 컬렉션의 각 정책을 삭제합니다. 마지막 줄은 나머지 기본 버전뿐만 아니라 정책 자체도 제거합니다. 관리형 정책을 성공적으로 삭제하려면 `Unregister-IAMUserPolicy`, `Unregister-IAMGroupPolicy` 및 `Unregister-IAMRolePolicy` 명령을 사용하여 모든 사용자, 그룹 또는 역할에서 정책을 분리해야 합니다. `Remove-IAMPolicy` cmdlet의 예를 참조하세요.**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
Remove-IAMPolicy -PolicyArn $pol.Arn -force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeletePolicyVersion](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_iam->deletepolicyversion(
          iv_policyarn = iv_policy_arn
          iv_versionid = iv_version_id ).
        MESSAGE 'Policy version deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy or version does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'Cannot delete default policy version.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeletePolicyVersion](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------

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

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Delete an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRoleAsync(string roleName)
    {
        var response = await _IAMService.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRole)을 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_delete_role
#
# This function deletes an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_role() {
  local role_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_role"
    echo "Deletes an AWS Identity and Access Management (IAM) role"
    echo "  -n role_name -- The name of the IAM role."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  echo "role_name:$role_name"
  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Role name:  $role_name"
  iecho ""

  response=$(aws iam delete-role \
    --role-name "$role_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-role operation failed.\n$response"
    return 1
  fi

  iecho "delete-role response:$response"
  iecho

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteRole)을 참조하세요.

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

**AWS CLI**  
**IAM 역할 삭제**  
다음 `delete-role` 명령은 이름이 `Test-Role`인 역할을 제거합니다.  

```
aws iam delete-role \
    --role-name Test-Role
```
이 명령은 출력을 생성하지 않습니다.  
역할을 삭제하려면 먼저 인스턴스 프로파일에서 역할을 제거하고 (`remove-role-from-instance-profile`), 관리형 정책을 모두 분리하고(`detach-role-policy`), 역할에 연결된 인라인 정책을 모두 삭제해야 합니다(`delete-role-policy`).  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html) 및 [인스턴스 프로파일 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-role.html)을 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// DeleteRole deletes a role. All attached policies must be detached before a
// role can be deleted.
func (wrapper RoleWrapper) DeleteRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteRole(ctx, &iam.DeleteRoleInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't delete role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DeleteRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteRole)을 참조하십시오.

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

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

```
import { DeleteRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const deleteRole = (roleName) => {
  const command = new DeleteRoleCommand({ RoleName: roleName });
  return client.send(command);
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRoleCommand)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 현재 IAM 계정에서 `MyNewRole`이라는 역할을 삭제합니다. 역할을 삭제하려면 먼저 `Unregister-IAMRolePolicy` 명령을 사용하여 관리형 정책을 분리해야 합니다. 인라인 정책은 역할과 함께 삭제됩니다.**  

```
Remove-IAMRole -RoleName MyNewRole
```
**예제 2: 이 예제는 `MyNewRole`이라는 역할에서 관리형 정책을 분리한 다음 역할을 삭제합니다. 줄 1은 역할에 연결된 모든 관리형 정책을 컬렉션으로 검색한 다음 컬렉션의 각 정책을 역할에서 분리합니다. 줄 2는 역할 자체를 삭제합니다. 인라인 정책은 역할과 함께 삭제됩니다.**  

```
Get-IAMAttachedRolePolicyList -RoleName MyNewRole | Unregister-IAMRolePolicy -RoleName MyNewRole
Remove-IAMRole -RoleName MyNewRole
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 현재 IAM 계정에서 `MyNewRole`이라는 역할을 삭제합니다. 역할을 삭제하려면 먼저 `Unregister-IAMRolePolicy` 명령을 사용하여 관리형 정책을 분리해야 합니다. 인라인 정책은 역할과 함께 삭제됩니다.**  

```
Remove-IAMRole -RoleName MyNewRole
```
**예제 2: 이 예제는 `MyNewRole`이라는 역할에서 관리형 정책을 분리한 다음 역할을 삭제합니다. 줄 1은 역할에 연결된 모든 관리형 정책을 컬렉션으로 검색한 다음 컬렉션의 각 정책을 역할에서 분리합니다. 줄 2는 역할 자체를 삭제합니다. 인라인 정책은 역할과 함께 삭제됩니다.**  

```
Get-IAMAttachedRolePolicyList -RoleName MyNewRole | Unregister-IAMRolePolicy -RoleName MyNewRole
Remove-IAMRole -RoleName MyNewRole
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteRole](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def delete_role(role_name):
    """
    Deletes a role.

    :param role_name: The name of the role to delete.
    """
    try:
        iam.Role(role_name).delete()
        logger.info("Deleted role %s.", role_name)
    except ClientError:
        logger.exception("Couldn't delete role %s.", role_name)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteRole)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Deletes a role and its attached policies.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_role(role_name)
    # Detach and delete attached policies
    @iam_client.list_attached_role_policies(role_name: role_name).each do |response|
      response.attached_policies.each do |policy|
        @iam_client.detach_role_policy({
                                         role_name: role_name,
                                         policy_arn: policy.policy_arn
                                       })
        # Check if the policy is a customer managed policy (not AWS managed)
        unless policy.policy_arn.include?('aws:policy/')
          @iam_client.delete_policy({ policy_arn: policy.policy_arn })
          @logger.info("Deleted customer managed policy #{policy.policy_name}.")
        end
      end
    end

    # Delete the role
    @iam_client.delete_role({ role_name: role_name })
    @logger.info("Deleted role #{role_name}.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't detach policies and delete role #{role_name}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DeleteRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteRole)을 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn delete_role(client: &iamClient, role: &Role) -> Result<(), iamError> {
    let role = role.clone();
    while client
        .delete_role()
        .role_name(role.role_name())
        .send()
        .await
        .is_err()
    {
        sleep(Duration::from_secs(2)).await;
    }
    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_role)을 참조하세요.

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

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

```
    TRY.
        lo_iam->deleterole( iv_rolename = iv_role_name ).
        MESSAGE 'Role deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'Role cannot be deleted due to attached resources.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func deleteRole(role: IAMClientTypes.Role) async throws {
        let input = DeleteRoleInput(
            roleName: role.roleName
        )
        do {
            _ = try await iamClient.deleteRole(input: input)
        } catch {
            print("ERROR: deleteRole:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeleteRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleterole(input:))을 참조하세요.

------

# CLI로 `DeleteRolePermissionsBoundary` 사용
<a name="iam_example_iam_DeleteRolePermissionsBoundary_section"></a>

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

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

**AWS CLI**  
**IAM 역할에서 권한 경계 삭제**  
다음 `delete-role-permissions-boundary` 예제는 지정된 IAM 역할의 권한 경계를 삭제합니다. 역할에 권한 경계를 적용하려면 `put-role-permissions-boundary` 명령을 사용합니다.  

```
aws iam delete-role-permissions-boundary \
    --role-name lambda-application-role
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteRolePermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-role-permissions-boundary.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 역할에 연결된 권한 경계를 제거하는 방법을 보여줍니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 역할에 연결된 권한 경계를 제거하는 방법을 보여줍니다.**  

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

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Delete an IAM role policy.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="policyName">The name of the IAM role policy to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRolePolicyAsync(string roleName, string policyName)
    {
        var response = await _IAMService.DeleteRolePolicyAsync(new DeleteRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRolePolicy)를 참조하세요.

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

**AWS CLI**  
**IAM 역할에서 정책 제거**  
다음 `delete-role-policy` 명령은 이름이 `Test-Role`인 역할에서 이름이 `ExamplePolicy`인 정책을 제거합니다.  

```
aws iam delete-role-policy \
    --role-name Test-Role \
    --policy-name ExamplePolicy
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [역할 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-role-policy.html)를 참조하세요.

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

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

```
import { DeleteRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 * @param {string} policyName
 */
export const deleteRolePolicy = (roleName, policyName) => {
  const command = new DeleteRolePolicyCommand({
    RoleName: roleName,
    PolicyName: policyName,
  });
  return client.send(command);
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRolePolicyCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 역할 `S3BackupRole`에 포함된 인라인 정책 `S3AccessPolicy`를 삭제합니다.**  

```
Remove-IAMRolePolicy -PolicyName S3AccessPolicy -RoleName S3BackupRole
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 역할 `S3BackupRole`에 포함된 인라인 정책 `S3AccessPolicy`를 삭제합니다.**  

```
Remove-IAMRolePolicy -PolicyName S3AccessPolicy -RoleName S3BackupRole
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

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

**AWS CLI**  
**SAML 공급자 삭제**  
이 예제에서는 ARN이 `arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider`인 IAM SAML 2.0 공급자를 삭제합니다.  

```
aws iam delete-saml-provider \
--saml-provider-arn arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM SAML 자격 증명 공급자 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteSAMLProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-saml-provider.html)를 참조하세요.

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

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

```
import { DeleteSAMLProviderCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} providerArn
 * @returns
 */
export const deleteSAMLProvider = async (providerArn) => {
  const command = new DeleteSAMLProviderCommand({
    SAMLProviderArn: providerArn,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API 세부 정보는AWS SDK for JavaScript API 참조의 [DeleteSAMLProvider](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteSAMLProviderCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider`인 IAM SAML 2.0 제공업체를 삭제합니다.**  

```
Remove-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteSAMLProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider`인 IAM SAML 2.0 제공업체를 삭제합니다.**  

```
Remove-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)의* [DeleteSAMLProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::deleteServerCertificate(const Aws::String &certificateName,
                                          const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::DeleteServerCertificateRequest request;
    request.SetServerCertificateName(certificateName);

    const auto outcome = iam.DeleteServerCertificate(request);
    bool result = true;
    if (!outcome.IsSuccess()) {
        if (outcome.GetError().GetErrorType() != Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
            std::cerr << "Error deleting server certificate " << certificateName <<
                      ": " << outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Certificate '" << certificateName
                      << "' not found." << std::endl;
        }
    }
    else {
        std::cout << "Successfully deleted server certificate " << certificateName
                  << std::endl;
    }

    return result;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeleteServerCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteServerCertificate)를 참조하세요.

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

**AWS CLI**  
** AWS 계정에서 서버 인증서를 삭제하려면**  
다음 `delete-server-certificate` 명령은 AWS 계정에서 지정된 서버 인증서를 제거합니다.  

```
aws iam delete-server-certificate \
    --server-certificate-name myUpdatedServerCertificate
```
이 명령은 출력을 생성하지 않습니다.  
 AWS 계정에서 사용할 수 있는 서버 인증서를 나열하려면 `list-server-certificates` 명령을 사용합니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM에서 서버 인증서 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-server-certificate.html)를 참조하세요.

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

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

```
import { DeleteServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} certName
 */
export const deleteServerCertificate = (certName) => {
  const command = new DeleteServerCertificateCommand({
    ServerCertificateName: certName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-deleting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteServerCertificateCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.deleteServerCertificate(
  { ServerCertificateName: "CERTIFICATE_NAME" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-deleting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteServerCertificate](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteServerCertificate)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `MyServerCert`라는 서버 인증서를 삭제합니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `MyServerCert`라는 서버 인증서를 삭제합니다.**  

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

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
서버 인증서를 나열하고, 업데이트하고, 삭제합니다.  

```
class ServerCertificateManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'ServerCertificateManager'
  end

  # Creates a new server certificate.
  # @param name [String] the name of the server certificate
  # @param certificate_body [String] the contents of the certificate
  # @param private_key [String] the private key contents
  # @return [Boolean] returns true if the certificate was successfully created
  def create_server_certificate(name, certificate_body, private_key)
    @iam_client.upload_server_certificate({
                                            server_certificate_name: name,
                                            certificate_body: certificate_body,
                                            private_key: private_key
                                          })
    true
  rescue Aws::IAM::Errors::ServiceError => e
    puts "Failed to create server certificate: #{e.message}"
    false
  end

  # Lists available server certificate names.
  def list_server_certificate_names
    response = @iam_client.list_server_certificates

    if response.server_certificate_metadata_list.empty?
      @logger.info('No server certificates found.')
      return
    end

    response.server_certificate_metadata_list.each do |certificate_metadata|
      @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}")
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing server certificates: #{e.message}")
  end

  # Updates the name of a server certificate.
  def update_server_certificate_name(current_name, new_name)
    @iam_client.update_server_certificate(
      server_certificate_name: current_name,
      new_server_certificate_name: new_name
    )
    @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error updating server certificate name: #{e.message}")
    false
  end

  # Deletes a server certificate.
  def delete_server_certificate(name)
    @iam_client.delete_server_certificate(server_certificate_name: name)
    @logger.info("Server certificate '#{name}' deleted.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting server certificate: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DeleteServerCertificate](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteServerCertificate)를 참조하세요.

------

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

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

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

**AWS CLI**  
**서비스 연결 역할 삭제**  
다음 `delete-service-linked-role` 예제에서는 더 이상 필요하지 않은 지정된 서비스 연결 역할을 삭제합니다. 삭제는 비동기식으로 이루어집니다. `get-service-linked-role-deletion-status` 명령을 사용하여 삭제 상태를 확인하고 언제 삭제되는지 확인할 수 있습니다.  

```
aws iam delete-service-linked-role \
    --role-name AWSServiceRoleForLexBots
```
출력:  

```
{
    "DeletionTaskId": "task/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots/1a2b3c4d-1234-abcd-7890-abcdeEXAMPLE"
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [서비스 연결 역할 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteServiceLinkedRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-service-linked-role.html)을 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// DeleteServiceLinkedRole deletes a service-linked role.
func (wrapper RoleWrapper) DeleteServiceLinkedRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteServiceLinkedRole(ctx, &iam.DeleteServiceLinkedRoleInput{
		RoleName: aws.String(roleName)},
	)
	if err != nil {
		log.Printf("Couldn't delete service-linked role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DeleteServiceLinkedRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteServiceLinkedRole)을 참조하십시오.

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

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

```
import { DeleteServiceLinkedRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const deleteServiceLinkedRole = (roleName) => {
  const command = new DeleteServiceLinkedRoleCommand({ RoleName: roleName });
  return client.send(command);
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteServiceLinkedRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteServiceLinkedRoleCommand)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 서비스 연결 역할을 삭제했습니다. 서비스에서 여전히 이 역할을 사용하고 있는 경우 이 명령을 실행하면 실패합니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 서비스 연결 역할을 삭제했습니다. 서비스에서 여전히 이 역할을 사용하고 있는 경우 이 명령을 실행하면 실패합니다.**  

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

------
#### [ Ruby ]

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

```
  # Deletes a service-linked role.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_service_linked_role(role_name)
    response = @iam_client.delete_service_linked_role(role_name: role_name)
    task_id = response.deletion_task_id
    check_deletion_status(role_name, task_id)
  rescue Aws::Errors::ServiceError => e
    handle_deletion_error(e, role_name)
  end

  private

  # Checks the deletion status of a service-linked role
  #
  # @param role_name [String] The name of the role being deleted
  # @param task_id [String] The task ID for the deletion process
  def check_deletion_status(role_name, task_id)
    loop do
      response = @iam_client.get_service_linked_role_deletion_status(
        deletion_task_id: task_id
      )
      status = response.status
      @logger.info("Deletion of #{role_name} #{status}.")
      break if %w[SUCCEEDED FAILED].include?(status)

      sleep(3)
    end
  end

  # Handles deletion error
  #
  # @param e [Aws::Errors::ServiceError] The error encountered during deletion
  # @param role_name [String] The name of the role attempted to delete
  def handle_deletion_error(e, role_name)
    return if e.code == 'NoSuchEntity'

    @logger.error("Couldn't delete #{role_name}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DeleteServiceLinkedRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteServiceLinkedRole)을 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn delete_service_linked_role(
    client: &iamClient,
    role_name: &str,
) -> Result<(), iamError> {
    client
        .delete_service_linked_role()
        .role_name(role_name)
        .send()
        .await?;

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteServiceLinkedRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_service_linked_role)을 참조하세요.

------

# CLI로 `DeleteSigningCertificate` 사용
<a name="iam_example_iam_DeleteSigningCertificate_section"></a>

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

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

**AWS CLI**  
**IAM 사용자의 서명 인증서 삭제**  
다음 `delete-signing-certificate` 명령은 `Bob`이라는 IAM 사용자에 대해 지정된 서명 인증서를 삭제합니다.  

```
aws iam delete-signing-certificate \
    --user-name Bob \
    --certificate-id TA7SMP42TDN5Z26OBPJE7EXAMPLE
```
이 명령은 출력을 생성하지 않습니다.  
서명 인증서의 ID를 가져오려면 `list-signing-certificates` 명령을 사용합니다.  
자세한 내용은 **Amazon EC2 사용 설명서의 [서명 인증서 관리](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-up-ami-tools.html#ami-tools-managing-certs)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteSigningCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-signing-certificate.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자로부터 ID가 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU`인 서명 인증서를 삭제합니다.**  

```
Remove-IAMSigningCertificate -UserName Bob -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteSigningCertificate](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자로부터 ID가 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU`인 서명 인증서를 삭제합니다.**  

```
Remove-IAMSigningCertificate -UserName Bob -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Delete an IAM user.
    /// </summary>
    /// <param name="userName">The username of the IAM user to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserAsync(string userName)
    {
        var response = await _IAMService.DeleteUserAsync(new DeleteUserRequest { UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUser)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_delete_user
#
# This function deletes the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_user"
    echo "Deletes an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user does not exist, we don't want to try to delete it.
  if (! iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name does not exist in the account."
    return 1
  fi

  response=$(aws iam delete-user \
    --user-name "$user_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-user operation failed.$response"
    return 1
  fi

  iecho "delete-user response:$response"
  iecho

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUser)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DeleteUserRequest request;
    request.SetUserName(userName);
    auto outcome = iam.DeleteUser(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting IAM user " << userName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;;
    }
    else {
        std::cout << "Successfully deleted IAM user " << userName << std::endl;
    }

    return outcome.IsSuccess();
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeleteUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUser)를 참조하세요.

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

**AWS CLI**  
**IAM 사용자 삭제**  
다음 `delete-user` 명령은 현재 계정에서 이름이 `Bob`인 IAM 사용자를 제거합니다.  

```
aws iam delete-user \
    --user-name Bob
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 삭제](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_deleting)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-user.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// DeleteUser deletes a user.
func (wrapper UserWrapper) DeleteUser(ctx context.Context, userName string) error {
	_, err := wrapper.IamClient.DeleteUser(ctx, &iam.DeleteUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUser)를 참조하십시오.

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

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

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.DeleteUserRequest;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeleteUser {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <userName>\s

                Where:
                    userName - The name of the user to delete.\s
                """;

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

        String userName = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        deleteIAMUser(iam, userName);
        System.out.println("Done");
        iam.close();
    }

    public static void deleteIAMUser(IamClient iam, String userName) {
        try {
            DeleteUserRequest request = DeleteUserRequest.builder()
                    .userName(userName)
                    .build();

            iam.deleteUser(request);
            System.out.println("Successfully deleted IAM user " + userName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DeleteUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUser)를 참조하십시오.

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

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

```
import { DeleteUserCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} name
 */
export const deleteUser = (name) => {
  const command = new DeleteUserCommand({ UserName: name });
  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-deleting-users)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
};

iam.getUser(params, function (err, data) {
  if (err && err.code === "NoSuchEntity") {
    console.log("User " + process.argv[2] + " does not exist.");
  } else {
    iam.deleteUser(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data);
      }
    });
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-deleting-users)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteUser](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteUser)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun deleteIAMUser(userNameVal: String) {
    val request =
        DeleteUserRequest {
            userName = userNameVal
        }

    // To delete a user, ensure that the user's access keys are deleted first.
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deleteUser(request)
        println("Successfully deleted user $userNameVal")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DeleteUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자를 삭제합니다.**  

```
Remove-IAMUser -UserName Bob
```
**예제 2: 이 예제는 먼저 삭제해야 하는 모든 요소와 함께 `Theresa`라는 IAM 사용자를 삭제합니다.**  

```
$name = "Theresa"

# find any groups and remove user from them
$groups = Get-IAMGroupForUser -UserName $name
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName $name -Force }

# find any inline policies and delete them
$inlinepols = Get-IAMUserPolicies -UserName $name
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName $name -Force}

# find any managed polices and detach them
$managedpols = Get-IAMAttachedUserPolicies -UserName $name
foreach ($pol in $managedpols) { Unregister-IAMUserPolicy -PolicyArn $pol.PolicyArn -UserName $name }

# find any signing certificates and delete them
$certs = Get-IAMSigningCertificate -UserName $name
foreach ($cert in $certs) { Remove-IAMSigningCertificate -CertificateId $cert.CertificateId -UserName $name -Force }

# find any access keys and delete them
$keys = Get-IAMAccessKey -UserName $name
foreach ($key in $keys) { Remove-IAMAccessKey -AccessKeyId $key.AccessKeyId -UserName $name -Force }

# delete the user's login profile, if one exists - note: need to use try/catch to suppress not found error
try { $prof = Get-IAMLoginProfile -UserName $name -ea 0 } catch { out-null }
if ($prof) { Remove-IAMLoginProfile -UserName $name -Force }

# find any MFA device, detach it, and if virtual, delete it.
$mfa = Get-IAMMFADevice -UserName $name
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}

# finally, remove the user
Remove-IAMUser -UserName $name -Force
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteUser](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자를 삭제합니다.**  

```
Remove-IAMUser -UserName Bob
```
**예제 2: 이 예제는 먼저 삭제해야 하는 모든 요소와 함께 `Theresa`라는 IAM 사용자를 삭제합니다.**  

```
$name = "Theresa"

# find any groups and remove user from them
$groups = Get-IAMGroupForUser -UserName $name
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName $name -Force }

# find any inline policies and delete them
$inlinepols = Get-IAMUserPolicies -UserName $name
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName $name -Force}

# find any managed polices and detach them
$managedpols = Get-IAMAttachedUserPolicies -UserName $name
foreach ($pol in $managedpols) { Unregister-IAMUserPolicy -PolicyArn $pol.PolicyArn -UserName $name }

# find any signing certificates and delete them
$certs = Get-IAMSigningCertificate -UserName $name
foreach ($cert in $certs) { Remove-IAMSigningCertificate -CertificateId $cert.CertificateId -UserName $name -Force }

# find any access keys and delete them
$keys = Get-IAMAccessKey -UserName $name
foreach ($key in $keys) { Remove-IAMAccessKey -AccessKeyId $key.AccessKeyId -UserName $name -Force }

# delete the user's login profile, if one exists - note: need to use try/catch to suppress not found error
try { $prof = Get-IAMLoginProfile -UserName $name -ea 0 } catch { out-null }
if ($prof) { Remove-IAMLoginProfile -UserName $name -Force }

# find any MFA device, detach it, and if virtual, delete it.
$mfa = Get-IAMMFADevice -UserName $name
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}

# finally, remove the user
Remove-IAMUser -UserName $name -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteUser](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def delete_user(user_name):
    """
    Deletes a user. Before a user can be deleted, all associated resources,
    such as access keys and policies, must be deleted or detached.

    :param user_name: The name of the user.
    """
    try:
        iam.User(user_name).delete()
        logger.info("Deleted user %s.", user_name)
    except ClientError:
        logger.exception("Couldn't delete user %s.", user_name)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUser)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Deletes a user and their associated resources
  #
  # @param user_name [String] The name of the user to delete
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DeleteUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUser)를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn delete_user(client: &iamClient, user: &User) -> Result<(), SdkError<DeleteUserError>> {
    let user = user.clone();
    let mut tries: i32 = 0;
    let max_tries: i32 = 10;

    let response: Result<(), SdkError<DeleteUserError>> = loop {
        match client
            .delete_user()
            .user_name(user.user_name())
            .send()
            .await
        {
            Ok(_) => {
                break Ok(());
            }
            Err(e) => {
                tries += 1;
                if tries > max_tries {
                    break Err(e);
                }
                sleep(Duration::from_secs(2)).await;
            }
        }
    };

    response
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user)을 참조하세요.

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

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

```
    TRY.
        lo_iam->deleteuser( iv_username = iv_user_name ).
        MESSAGE 'User deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'User cannot be deleted due to attached resources.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DeleteUser](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func deleteUser(user: IAMClientTypes.User) async throws {
        let input = DeleteUserInput(
            userName: user.userName
        )
        do {
            _ = try await iamClient.deleteUser(input: input)
        } catch {
            print("ERROR: deleteUser:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeleteUser](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleteuser(input:))를 참조하세요.

------

# CLI로 `DeleteUserPermissionsBoundary` 사용
<a name="iam_example_iam_DeleteUserPermissionsBoundary_section"></a>

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

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

**AWS CLI**  
**IAM 사용자에게서 권한 경계 삭제**  
다음 `delete-user-permissions-boundary` 예제는 `intern`이라는 IAM 사용자에게 연결된 권한 경계를 삭제합니다. 사용자에게 권한 경계를 적용하려면 `put-user-permissions-boundary` 명령을 사용합니다.  

```
aws iam delete-user-permissions-boundary \
    --user-name intern
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteUserPermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-user-permissions-boundary.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 사용자에게 연결된 권한 경계를 제거하는 방법을 보여줍니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 사용자에게 연결된 권한 경계를 제거하는 방법을 보여줍니다.**  

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

------

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

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Delete an IAM user policy.
    /// </summary>
    /// <param name="policyName">The name of the IAM policy to delete.</param>
    /// <param name="userName">The username of the IAM user.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserPolicyAsync(string policyName, string userName)
    {
        var response = await _IAMService.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policyName, UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUserPolicy)를 참조하세요.

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

**AWS CLI**  
**IAM 사용자에서 정책 제거**  
다음 `delete-user-policy` 명령은 이름이 `Bob`인 IAM 사용자에서 지정된 정책을 제거합니다.  

```
aws iam delete-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy
```
이 명령은 출력을 생성하지 않습니다.  
IAM 사용자의 정책 목록을 가져오려면 `list-user-policies` 명령을 사용합니다.  
자세한 내용은 [IAM 사용 설명서의 AWS 계정에서 IAM 사용자 생성을 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html). *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-user-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// DeleteUserPolicy deletes an inline policy from a user.
func (wrapper UserWrapper) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
	_, err := wrapper.IamClient.DeleteUserPolicy(ctx, &iam.DeleteUserPolicyInput{
		PolicyName: aws.String(policyName),
		UserName:   aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete policy from user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DeleteUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUserPolicy)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자에게 포함된 `AccessToEC2Policy`라는 인라인 정책을 삭제합니다.**  

```
Remove-IAMUserPolicy -PolicyName AccessToEC2Policy -UserName Bob
```
**예제 2: 이 예제는 `Theresa`라는 IAM 사용자에게 포함된 모든 인라인 정책을 찾아 삭제합니다.**  

```
$inlinepols = Get-IAMUserPolicies -UserName Theresa
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName Theresa -Force}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자에게 포함된 `AccessToEC2Policy`라는 인라인 정책을 삭제합니다.**  

```
Remove-IAMUserPolicy -PolicyName AccessToEC2Policy -UserName Bob
```
**예제 2: 이 예제는 `Theresa`라는 IAM 사용자에게 포함된 모든 인라인 정책을 찾아 삭제합니다.**  

```
$inlinepols = Get-IAMUserPolicies -UserName Theresa
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName Theresa -Force}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Ruby ]

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

```
  # Deletes a user and their associated resources
  #
  # @param user_name [String] The name of the user to delete
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUserPolicy)를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn delete_user_policy(
    client: &iamClient,
    user: &User,
    policy_name: &str,
) -> Result<(), SdkError<DeleteUserPolicyError>> {
    client
        .delete_user_policy()
        .user_name(user.user_name())
        .policy_name(policy_name)
        .send()
        .await?;

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DeleteUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user_policy)을 참조하십시오.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    func deleteUserPolicy(user: IAMClientTypes.User, policyName: String) async throws {
        let input = DeleteUserPolicyInput(
            policyName: policyName,
            userName: user.userName
        )
        do {
            _ = try await iamClient.deleteUserPolicy(input: input)
        } catch {
            print("ERROR: deleteUserPolicy:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeleteUserPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleteuserpolicy(input:))를 참조하세요.

------

# CLI로 `DeleteVirtualMfaDevice` 사용
<a name="iam_example_iam_DeleteVirtualMfaDevice_section"></a>

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

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

**AWS CLI**  
**가상 MFA 디바이스 제거**  
다음 `delete-virtual-mfa-device` 명령은 현재 계정에서 지정된 MFA 디바이스를 제거합니다.  

```
aws iam delete-virtual-mfa-device \
    --serial-number arn:aws:iam::123456789012:mfa/MFATest
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [MFA 디바이스 비활성화](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_disable.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DeleteVirtualMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-virtual-mfa-device.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:mfa/bob`인 IAM 가상 MFA 디바이스를 삭제합니다.**  

```
Remove-IAMVirtualMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/bob
```
**예제 2: 이 예제는 IAM 사용자 Theresa에게 MFA 디바이스가 할당되었는지 확인합니다. 발견된 디바이스는 IAM 사용자에 대해 비활성화됩니다. 디바이스가 가상이면 삭제됩니다.**  

```
$mfa = Get-IAMMFADevice -UserName Theresa
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DeleteVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:mfa/bob`인 IAM 가상 MFA 디바이스를 삭제합니다.**  

```
Remove-IAMVirtualMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/bob
```
**예제 2: 이 예제는 IAM 사용자 Theresa에게 MFA 디바이스가 할당되었는지 확인합니다. 발견된 디바이스는 IAM 사용자에 대해 비활성화됩니다. 디바이스가 가상이면 삭제됩니다.**  

```
$mfa = Get-IAMMFADevice -UserName Theresa
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DeleteVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `DetachGroupPolicy` 사용
<a name="iam_example_iam_DetachGroupPolicy_section"></a>

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

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

**AWS CLI**  
**그룹에서 정책 분리**  
이 예제는 `Testers`라는 그룹에서 ARN `arn:aws:iam::123456789012:policy/TesterAccessPolicy`가 있는 관리형 정책을 제거합니다.  

```
aws iam detach-group-policy \
    --group-name Testers \
    --policy-arn arn:aws:iam::123456789012:policy/TesterAccessPolicy
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 그룹 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [DetachGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/detach-group-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/TesterAccessPolicy`인 관리형 그룹 정책을 `Testers`라는 그룹에서 분리합니다.**  

```
Unregister-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterAccessPolicy
```
**예제 2: 이 예제는 `Testers`라는 그룹에 연결된 모든 관리형 정책을 찾아 그룹에서 분리합니다.**  

```
Get-IAMAttachedGroupPolicies -GroupName Testers | Unregister-IAMGroupPolicy -Groupname Testers
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DetachGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/TesterAccessPolicy`인 관리형 그룹 정책을 `Testers`라는 그룹에서 분리합니다.**  

```
Unregister-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterAccessPolicy
```
**예제 2: 이 예제는 `Testers`라는 그룹에 연결된 모든 관리형 정책을 찾아 그룹에서 분리합니다.**  

```
Get-IAMAttachedGroupPolicies -GroupName Testers | Unregister-IAMGroupPolicy -Groupname Testers
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DetachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Detach an IAM policy from an IAM role.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DetachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.DetachRolePolicyAsync(new DetachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DetachRolePolicy)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_detach_role_policy
#
# This function detaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_detach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_detach_role_policy"
    echo "Detaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam detach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports detach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API 세부 정보는 *AWS CLI  명령 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DetachRolePolicy)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DetachRolePolicyRequest detachRequest;
    detachRequest.SetRoleName(roleName);
    detachRequest.SetPolicyArn(policyArn);

    auto detachOutcome = iam.DetachRolePolicy(detachRequest);
    if (!detachOutcome.IsSuccess()) {
        std::cerr << "Failed to detach policy " << policyArn << " from role "
                  << roleName << ": " << detachOutcome.GetError().GetMessage() <<
                  std::endl;
    }
    else {
        std::cout << "Successfully detached policy " << policyArn << " from role "
                  << roleName << std::endl;
    }

    return detachOutcome.IsSuccess();
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DetachRolePolicy)를 참조하세요.

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

**AWS CLI**  
**역할에서 정책 분리**  
이 예제에서는 `FedTesterRole`을 호출한 역할에서 ARN이 `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy`인 관리형 정책을 제거합니다.  

```
aws iam detach-role-policy \
    --role-name FedTesterRole \
    --policy-arn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [역할 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)을 참조하세요.  
+  API 세부 정보는 *AWS CLI  명령 참조*의 [DetachRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/detach-role-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// DetachRolePolicy detaches a policy from a role.
func (wrapper RoleWrapper) DetachRolePolicy(ctx context.Context, roleName string, policyArn string) error {
	_, err := wrapper.IamClient.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't detach policy from role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DetachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DetachRolePolicy)를 참조하십시오.

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

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

```
import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DetachRolePolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <roleName> <policyArn>\s

                Where:
                    roleName - A role name that you can obtain from the AWS Management Console.\s
                    policyArn - A policy ARN that you can obtain from the AWS Management Console.\s
                """;

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

        String roleName = args[0];
        String policyArn = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();
        detachPolicy(iam, roleName, policyArn);
        System.out.println("Done");
        iam.close();
    }

    public static void detachPolicy(IamClient iam, String roleName, String policyArn) {
        try {
            DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.detachRolePolicy(request);
            System.out.println("Successfully detached policy " + policyArn +
                    " from role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DetachRolePolicy)를 참조하십시오.

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

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

```
import { DetachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 * @param {string} roleName
 */
export const detachRolePolicy = (policyArn, roleName) => {
  const command = new DetachRolePolicyCommand({
    PolicyArn: policyArn,
    RoleName: roleName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-detaching-role-policy)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DetachRolePolicyCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var paramsRoleList = {
  RoleName: process.argv[2],
};

iam.listAttachedRolePolicies(paramsRoleList, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var myRolePolicies = data.AttachedPolicies;
    myRolePolicies.forEach(function (val, index, array) {
      if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") {
        var params = {
          PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",
          RoleName: process.argv[2],
        };
        iam.detachRolePolicy(params, function (err, data) {
          if (err) {
            console.log("Unable to detach policy from role", err);
          } else {
            console.log("Policy detached from role successfully");
            process.exit();
          }
        });
      }
    });
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-detaching-role-policy)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DetachRolePolicy)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun detachPolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        DetachRolePolicyRequest {
            roleName = roleNameVal
            policyArn = policyArnVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.detachRolePolicy(request)
        println("Successfully detached policy $policyArnVal from role $roleNameVal")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DetachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy`인 관리형 그룹 정책을 `FedTesterRole`라는 역할에서 분리합니다.**  

```
Unregister-IAMRolePolicy -RoleName FedTesterRole -PolicyArn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy
```
**예제 2: 이 예제는 `FedTesterRole`라는 역할에 연결된 모든 관리형 정책을 찾아 역할에서 분리합니다.**  

```
Get-IAMAttachedRolePolicyList -RoleName FedTesterRole | Unregister-IAMRolePolicy -Rolename FedTesterRole
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DetachRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy`인 관리형 그룹 정책을 `FedTesterRole`라는 역할에서 분리합니다.**  

```
Unregister-IAMRolePolicy -RoleName FedTesterRole -PolicyArn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy
```
**예제 2: 이 예제는 `FedTesterRole`라는 역할에 연결된 모든 관리형 정책을 찾아 역할에서 분리합니다.**  

```
Get-IAMAttachedRolePolicyList -RoleName FedTesterRole | Unregister-IAMRolePolicy -Rolename FedTesterRole
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DetachRolePolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
Boto3 정책 객체를 사용하여 역할에서 정책을 분리합니다.  

```
def detach_from_role(role_name, policy_arn):
    """
    Detaches a policy from a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Policy(policy_arn).detach_role(RoleName=role_name)
        logger.info("Detached policy %s from role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from role %s.", policy_arn, role_name
        )
        raise
```
Boto3 역할 객체를 사용하여 역할에서 정책을 분리합니다.  

```
def detach_policy(role_name, policy_arn):
    """
    Detaches a policy from a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Role(role_name).detach_policy(PolicyArn=policy_arn)
        logger.info("Detached policy %s from role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from role %s.", policy_arn, role_name
        )
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachRolePolicy)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 역할 정책을 나열, 생성, 연결 및 분리합니다.  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachRolePolicy)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn detach_role_policy(
    client: &iamClient,
    role_name: &str,
    policy_arn: &str,
) -> Result<(), iamError> {
    client
        .detach_role_policy()
        .role_name(role_name)
        .policy_arn(policy_arn)
        .send()
        .await?;

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DetachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_role_policy)을 참조하세요.

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

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

```
    TRY.
        lo_iam->detachrolepolicy(
          iv_rolename = iv_role_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy detached from role successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role or policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DetachRolePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func detachRolePolicy(policy: IAMClientTypes.Policy, role: IAMClientTypes.Role) async throws {
        let input = DetachRolePolicyInput(
            policyArn: policy.arn,
            roleName: role.roleName
        )

        do {
            _ = try await iamClient.detachRolePolicy(input: input)
        } catch {
            print("ERROR: detachRolePolicy:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DetachRolePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/detachrolepolicy(input:))를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 

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

**AWS CLI**  
**사용자에서 정책 분리**  
이 예제에서는 사용자 `Bob`에서 ARN이 `arn:aws:iam::123456789012:policy/TesterPolicy`인 관리형 정책을 제거합니다.  

```
aws iam detach-user-policy \
    --user-name Bob \
    --policy-arn arn:aws:iam::123456789012:policy/TesterPolicy
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자의 권한 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI  명령 참조의 [DetachUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/detach-user-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/TesterPolicy`인 관리형 정책을 `Bob`라는 IAM 사용자에게서 분리합니다.**  

```
Unregister-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**예제 2: 이 예제는 `Theresa`라는 IAM 사용자에게 연결된 모든 관리형 정책을 찾아 사용자에게서 분리합니다.**  

```
Get-IAMAttachedUserPolicyList -UserName Theresa | Unregister-IAMUserPolicy -Username Theresa
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [DetachUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/TesterPolicy`인 관리형 정책을 `Bob`라는 IAM 사용자에게서 분리합니다.**  

```
Unregister-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**예제 2: 이 예제는 `Theresa`라는 IAM 사용자에게 연결된 모든 관리형 정책을 찾아 사용자에게서 분리합니다.**  

```
Get-IAMAttachedUserPolicyList -UserName Theresa | Unregister-IAMUserPolicy -Username Theresa
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [DetachUserPolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def detach_policy(user_name, policy_arn):
    """
    Detaches a policy from a user.

    :param user_name: The name of the user.
    :param policy_arn: The Amazon Resource Name (ARN) of the policy.
    """
    try:
        iam.User(user_name).detach_policy(PolicyArn=policy_arn)
        logger.info("Detached policy %s from user %s.", policy_arn, user_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from user %s.", policy_arn, user_name
        )
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DetachUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachUserPolicy)를 참조하세요.

------
#### [ Ruby ]

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

```
  # Detaches a policy from a user
  #
  # @param user_name [String] The name of the user
  # @param policy_arn [String] The ARN of the policy to detach
  # @return [Boolean] true if the policy was successfully detached, false otherwise
  def detach_user_policy(user_name, policy_arn)
    @iam_client.detach_user_policy(
      user_name: user_name,
      policy_arn: policy_arn
    )
    @logger.info("Policy '#{policy_arn}' detached from user '#{user_name}' successfully.")
    true
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error('Error detaching policy: Policy or user does not exist.')
    false
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from user '#{user_name}': #{e.message}")
    false
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [DetachUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachUserPolicy)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn detach_user_policy(
    client: &iamClient,
    user_name: &str,
    policy_arn: &str,
) -> Result<(), iamError> {
    client
        .detach_user_policy()
        .user_name(user_name)
        .policy_arn(policy_arn)
        .send()
        .await?;

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [DetachUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_user_policy)을 참조하세요.

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

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

```
    TRY.
        lo_iam->detachuserpolicy(
          iv_username = iv_user_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy detached from user successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User or policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [DetachUserPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `EnableMfaDevice` 사용
<a name="iam_example_iam_EnableMfaDevice_section"></a>

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

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

**AWS CLI**  
**MFA 디바이스 활성화**  
`create-virtual-mfa-device` 명령을 사용하여 새 가상 MFA 디바이스를 생성한 후 사용자에게 MFA 디바이스를 할당할 수 있습니다. 다음 `enable-mfa-device` 예제는 일련 번호가 `arn:aws:iam::210987654321:mfa/BobsMFADevice`인 MFA 디바이스를 사용자 `Bob`에게 할당합니다. 또한이 명령은 가상 MFA 디바이스의 처음 두 코드를 순서대로 AWS 포함하여 디바이스를와 동기화합니다.  

```
aws iam enable-mfa-device \
    --user-name Bob \
    --serial-number arn:aws:iam::210987654321:mfa/BobsMFADevice \
    --authentication-code1 123456 \
    --authentication-code2 789012
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [가상 다중 인증(MFA) 디바이스 활성화](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [EnableMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-mfa-device.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 일련 번호 `987654321098`을 사용하여 하드웨어 MFA 디바이스를 활성화하고 디바이스를 사용자 `Bob`과 연결합니다. 여기에는 디바이스의 처음 두 코드가 순서대로 포함됩니다.**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**예제 2: 이 예제는 가상 MFA 디바이스를 생성하고 활성화합니다. 첫 번째 명령은 가상 디바이스를 생성하고 `$MFADevice` 변수에 디바이스의 객체 표현을 반환합니다. `.Base32StringSeed` 또는 `QRCodePng` 속성을 사용하여 사용자의 소프트웨어 애플리케이션을 구성할 수 있습니다. 마지막 명령은 사용자 `David`에게 디바이스를 할당하고 일련 번호로 디바이스를 식별합니다. 또한 명령은 가상 MFA 디바이스의 처음 두 코드를 순서대로 AWS 포함하여 디바이스를와 동기화합니다.**  

```
$MFADevice = New-IAMVirtualMFADevice -VirtualMFADeviceName "MyMFADevice"
# see example for New-IAMVirtualMFADevice to see how to configure the software program with PNG or base32 seed code
Enable-IAMMFADevice -UserName "David" -SerialNumber -SerialNumber $MFADevice.SerialNumber -AuthenticationCode1 "24681357" -AuthenticationCode2 "13572468"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [EnableMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 일련 번호 `987654321098`을 사용하여 하드웨어 MFA 디바이스를 활성화하고 디바이스를 사용자 `Bob`과 연결합니다. 여기에는 디바이스의 처음 두 코드가 순서대로 포함됩니다.**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**예제 2: 이 예제는 가상 MFA 디바이스를 생성하고 활성화합니다. 첫 번째 명령은 가상 디바이스를 생성하고 `$MFADevice` 변수에 디바이스의 객체 표현을 반환합니다. `.Base32StringSeed` 또는 `QRCodePng` 속성을 사용하여 사용자의 소프트웨어 애플리케이션을 구성할 수 있습니다. 마지막 명령은 사용자 `David`에게 디바이스를 할당하고 일련 번호로 디바이스를 식별합니다. 또한 명령은 가상 MFA 디바이스의 처음 두 코드를 순서대로 AWS 포함하여 디바이스를와 동기화합니다.**  

```
$MFADevice = New-IAMVirtualMFADevice -VirtualMFADeviceName "MyMFADevice"
# see example for New-IAMVirtualMFADevice to see how to configure the software program with PNG or base32 seed code
Enable-IAMMFADevice -UserName "David" -SerialNumber -SerialNumber $MFADevice.SerialNumber -AuthenticationCode1 "24681357" -AuthenticationCode2 "13572468"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [EnableMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [계정 관리](iam_example_iam_Scenario_AccountManagement_section.md) 

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

**AWS CLI**  
**자격 증명 보고서 생성**  
다음 예시에서는 AWS 계정에 대한 자격 증명 보고서를 생성하려고 시도합니다.  

```
aws iam generate-credential-report
```
출력:  

```
{
    "State":  "STARTED",
    "Description": "No report exists. Starting a new report generation task"
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [AWS 계정에 대한 자격 증명 보고서 가져오기를 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html).  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GenerateCredentialReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/generate-credential-report.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 4시간마다 수행할 수 있는 새 보고서 생성을 요청합니다. 마지막 보고서가 아직 최신인 경우 State 필드에 `COMPLETE`가 표시됩니다. 완성된 보고서를 보려면 `Get-IAMCredentialReport`를 사용합니다.**  

```
Request-IAMCredentialReport
```
**출력:**  

```
Description                                                    State
-----------                                                    -----
No report exists. Starting a new report generation task        STARTED
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GenerateCredentialReport](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 4시간마다 수행할 수 있는 새 보고서 생성을 요청합니다. 마지막 보고서가 아직 최신인 경우 State 필드에 `COMPLETE`가 표시됩니다. 완성된 보고서를 보려면 `Get-IAMCredentialReport`를 사용합니다.**  

```
Request-IAMCredentialReport
```
**출력:**  

```
Description                                                    State
-----------                                                    -----
No report exists. Starting a new report generation task        STARTED
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GenerateCredentialReport](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def generate_credential_report():
    """
    Starts generation of a credentials report about the current account. After
    calling this function to generate the report, call get_credential_report
    to get the latest report. A new report can be generated a minimum of four hours
    after the last one was generated.
    """
    try:
        response = iam.meta.client.generate_credential_report()
        logger.info(
            "Generating credentials report for your account. " "Current state is %s.",
            response["State"],
        )
    except ClientError:
        logger.exception("Couldn't generate a credentials report for your account.")
        raise
    else:
        return response
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GenerateCredentialReport](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GenerateCredentialReport)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->generatecredentialreport( ).
        MESSAGE 'Credential report generation started.' TYPE 'I'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Report generation limit exceeded.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when generating credential report.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GenerateCredentialReport](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `GenerateServiceLastAccessedDetails` 사용
<a name="iam_example_iam_GenerateServiceLastAccessedDetails_section"></a>

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

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

**AWS CLI**  
**예제 1: 사용자 지정 정책에 대한 서비스 액세스 보고서 생성**  
다음 `generate-service-last-accessed-details` 예제는 백그라운드 작업을 시작하여 `intern-boundary`라는 사용자 지정 정책으로 IAM 사용자와 기타 엔터티가 액세스하는 서비스를 나열하는 보고서를 생성합니다. 보고서가 생성된 후에는 `get-service-last-accessed-details` 명령을 실행하여 보고서를 표시할 수 있습니다.  

```
aws iam generate-service-last-accessed-details \
    --arn arn:aws:iam::123456789012:policy/intern-boundary
```
출력:  

```
{
    "JobId": "2eb6c2b8-7b4c-3xmp-3c13-03b72c8cdfdc"
}
```
**예제 2: AWS 관리형 AdministratorAccess 정책에 대한 서비스 액세스 보고서를 생성하는 방법**  
다음 `generate-service-last-accessed-details` 예제에서는 백그라운드 작업을 시작하여 AWS 관리형 `AdministratorAccess` 정책을 사용하여 IAM 사용자 및 기타 엔터티가 액세스하는 서비스를 나열하는 보고서를 생성합니다. 보고서가 생성된 후에는 `get-service-last-accessed-details` 명령을 실행하여 보고서를 표시할 수 있습니다.  

```
aws iam generate-service-last-accessed-details \
    --arn arn:aws:iam::aws:policy/AdministratorAccess
```
출력:  

```
{
    "JobId": "78b6c2ba-d09e-6xmp-7039-ecde30b26916"
}
```
자세한 내용은 *AWS IAM 사용 설명서*[의 마지막으로 액세스한 정보를 AWS 사용하여에서 권한 구체화를](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GenerateServiceLastAccessedDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/generate-service-last-accessed-details.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 GenerateServiceLastAccessedDetails API와 동등한 cmdlet입니다. 이는 Get-IAMServiceLastAccessedDetail과 Get-IAMServiceLastAccessedDetailWithEntity에서 사용할 수 있는 작업 ID를 제공합니다.**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GenerateServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 GenerateServiceLastAccessedDetails API와 동등한 cmdlet입니다. 이는 Get-IAMServiceLastAccessedDetail과 Get-IAMServiceLastAccessedDetailWithEntity에서 사용할 수 있는 작업 ID를 제공합니다.**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GenerateServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [ 액세스 키 관리](iam_example_iam_Scenario_ManageAccessKeys_section.md) 

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::accessKeyLastUsed(const Aws::String &secretKeyID,
                                    const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::GetAccessKeyLastUsedRequest request;

    request.SetAccessKeyId(secretKeyID);

    Aws::IAM::Model::GetAccessKeyLastUsedOutcome outcome = iam.GetAccessKeyLastUsed(
            request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error querying last used time for access key " <<
                  secretKeyID << ":" << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        Aws::String lastUsedTimeString =
                outcome.GetResult()
                        .GetAccessKeyLastUsed()
                        .GetLastUsedDate()
                        .ToGmtString(Aws::Utils::DateFormat::ISO_8601);
        std::cout << "Access key " << secretKeyID << " last used at time " <<
                  lastUsedTimeString << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [GetAccessKeyLastUsed](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/GetAccessKeyLastUsed)를 참조하세요.

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

**AWS CLI**  
**지정된 액세스 키가 마지막으로 사용된 경우에 대한 정보 검색**  
다음 예제에서는 액세스 키 `ABCDEXAMPLE`이 마지막으로 사용된 시간에 대한 정보를 검색합니다.  

```
aws iam get-access-key-last-used \
    --access-key-id ABCDEXAMPLE
```
출력:  

```
{
    "UserName":  "Bob",
    "AccessKeyLastUsed": {
        "Region": "us-east-1",
        "ServiceName": "iam",
        "LastUsedDate": "2015-06-16T22:45:00Z"
    }
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자의 액세스 키 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetAccessKeyLastUsed](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-access-key-last-used.html)를 참조하세요.

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

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

```
import { GetAccessKeyLastUsedCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} accessKeyId
 */
export const getAccessKeyLastUsed = async (accessKeyId) => {
  const command = new GetAccessKeyLastUsedCommand({
    AccessKeyId: accessKeyId,
  });

  const response = await client.send(command);

  if (response.AccessKeyLastUsed?.LastUsedDate) {
    console.log(`
    ${accessKeyId} was last used by ${response.UserName} via 
    the ${response.AccessKeyLastUsed.ServiceName} service on
    ${response.AccessKeyLastUsed.LastUsedDate.toISOString()}
    `);
  }

  return response;
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-last-used)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetAccessKeyLastUsed](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetAccessKeyLastUsedCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.getAccessKeyLastUsed(
  { AccessKeyId: "ACCESS_KEY_ID" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data.AccessKeyLastUsed);
    }
  }
);
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-last-used)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetAccessKeyLastUsed](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/GetAccessKeyLastUsed)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 제공된 액세스 키의 소유 사용자 이름과 마지막 사용 정보를 반환합니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 제공된 액세스 키의 소유 사용자 이름과 마지막 사용 정보를 반환합니다.**  

```
Get-IAMAccessKeyLastUsed -AccessKeyId ABCDEXAMPLE
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetAccessKeyLastUsed](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def get_last_use(key_id):
    """
    Gets information about when and how a key was last used.

    :param key_id: The ID of the key to look up.
    :return: Information about the key's last use.
    """
    try:
        response = iam.meta.client.get_access_key_last_used(AccessKeyId=key_id)
        last_used_date = response["AccessKeyLastUsed"].get("LastUsedDate", None)
        last_service = response["AccessKeyLastUsed"].get("ServiceName", None)
        logger.info(
            "Key %s was last used by %s on %s to access %s.",
            key_id,
            response["UserName"],
            last_used_date,
            last_service,
        )
    except ClientError:
        logger.exception("Couldn't get last use of key %s.", key_id)
        raise
    else:
        return response
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetAccessKeyLastUsed](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccessKeyLastUsed)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->getaccesskeylastused(
          iv_accesskeyid = iv_access_key_id ).
        MESSAGE 'Retrieved access key last used information.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Access key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GetAccessKeyLastUsed](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [계정 관리](iam_example_iam_Scenario_AccountManagement_section.md) 

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

**AWS CLI**  
** AWS 계정의 IAM 사용자, 그룹, 역할 및 정책을 나열하려면**  
다음 `get-account-authorization-details` 명령은 AWS 계정의 모든 IAM 사용자, 그룹, 역할 및 정책에 대한 정보를 반환합니다.  

```
aws iam get-account-authorization-details
```
출력:  

```
{
    "RoleDetailList": [
        {
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "RoleId": "AROA1234567890EXAMPLE",
            "CreateDate": "2014-07-30T17:09:20Z",
            "InstanceProfileList": [
                {
                    "InstanceProfileId": "AIPA1234567890EXAMPLE",
                    "Roles": [
                        {
                            "AssumeRolePolicyDocument": {
                                "Version":"2012-10-17",		 	 	 
                                "Statement": [
                                    {
                                        "Sid": "",
                                        "Effect": "Allow",
                                        "Principal": {
                                            "Service": "ec2.amazonaws.com"
                                        },
                                        "Action": "sts:AssumeRole"
                                    }
                                ]
                            },
                            "RoleId": "AROA1234567890EXAMPLE",
                            "CreateDate": "2014-07-30T17:09:20Z",
                            "RoleName": "EC2role",
                            "Path": "/",
                            "Arn": "arn:aws:iam::123456789012:role/EC2role"
                        }
                    ],
                    "CreateDate": "2014-07-30T17:09:20Z",
                    "InstanceProfileName": "EC2role",
                    "Path": "/",
                    "Arn": "arn:aws:iam::123456789012:instance-profile/EC2role"
                }
            ],
            "RoleName": "EC2role",
            "Path": "/",
            "AttachedManagedPolicies": [
                {
                    "PolicyName": "AmazonS3FullAccess",
                    "PolicyArn": "arn:aws:iam::aws:policy/AmazonS3FullAccess"
                },
                {
                    "PolicyName": "AmazonDynamoDBFullAccess",
                    "PolicyArn": "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"
                }
            ],
            "RoleLastUsed": {
                "Region": "us-west-2",
                "LastUsedDate": "2019-11-13T17:30:00Z"
            },
            "RolePolicyList": [],
            "Arn": "arn:aws:iam::123456789012:role/EC2role"
        }
    ],
    "GroupDetailList": [
        {
            "GroupId": "AIDA1234567890EXAMPLE",
            "AttachedManagedPolicies": {
                "PolicyName": "AdministratorAccess",
                "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
            },
            "GroupName": "Admins",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:group/Admins",
            "CreateDate": "2013-10-14T18:32:24Z",
            "GroupPolicyList": []
        },
        {
            "GroupId": "AIDA1234567890EXAMPLE",
            "AttachedManagedPolicies": {
                "PolicyName": "PowerUserAccess",
                "PolicyArn": "arn:aws:iam::aws:policy/PowerUserAccess"
            },
            "GroupName": "Dev",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:group/Dev",
            "CreateDate": "2013-10-14T18:33:55Z",
            "GroupPolicyList": []
        },
        {
            "GroupId": "AIDA1234567890EXAMPLE",
            "AttachedManagedPolicies": [],
            "GroupName": "Finance",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:group/Finance",
            "CreateDate": "2013-10-14T18:57:48Z",
            "GroupPolicyList": [
                {
                    "PolicyName": "policygen-201310141157",
                    "PolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Action": "aws-portal:*",
                                "Sid": "Stmt1381777017000",
                                "Resource": "*",
                                "Effect": "Allow"
                            }
                        ]
                    }
                }
            ]
        }
    ],
    "UserDetailList": [
        {
            "UserName": "Alice",
            "GroupList": [
                "Admins"
            ],
            "CreateDate": "2013-10-14T18:32:24Z",
            "UserId": "AIDA1234567890EXAMPLE",
            "UserPolicyList": [],
            "Path": "/",
            "AttachedManagedPolicies": [],
            "Arn": "arn:aws:iam::123456789012:user/Alice"
        },
        {
            "UserName": "Bob",
            "GroupList": [
                "Admins"
            ],
            "CreateDate": "2013-10-14T18:32:25Z",
            "UserId": "AIDA1234567890EXAMPLE",
            "UserPolicyList": [
                {
                    "PolicyName": "DenyBillingAndIAMPolicy",
                    "PolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": {
                            "Effect": "Deny",
                            "Action": [
                                "aws-portal:*",
                                "iam:*"
                            ],
                            "Resource": "*"
                        }
                    }
                }
            ],
            "Path": "/",
            "AttachedManagedPolicies": [],
            "Arn": "arn:aws:iam::123456789012:user/Bob"
        },
        {
            "UserName": "Charlie",
            "GroupList": [
                "Dev"
            ],
            "CreateDate": "2013-10-14T18:33:56Z",
            "UserId": "AIDA1234567890EXAMPLE",
            "UserPolicyList": [],
            "Path": "/",
            "AttachedManagedPolicies": [],
            "Arn": "arn:aws:iam::123456789012:user/Charlie"
        }
    ],
    "Policies": [
        {
            "PolicyName": "create-update-delete-set-managed-policies",
            "CreateDate": "2015-02-06T19:58:34Z",
            "AttachmentCount": 1,
            "IsAttachable": true,
            "PolicyId": "ANPA1234567890EXAMPLE",
            "DefaultVersionId": "v1",
            "PolicyVersionList": [
                {
                    "CreateDate": "2015-02-06T19:58:34Z",
                    "VersionId": "v1",
                    "Document": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": {
                            "Effect": "Allow",
                            "Action": [
                                "iam:CreatePolicy",
                                "iam:CreatePolicyVersion",
                                "iam:DeletePolicy",
                                "iam:DeletePolicyVersion",
                                "iam:GetPolicy",
                                "iam:GetPolicyVersion",
                                "iam:ListPolicies",
                                "iam:ListPolicyVersions",
                                "iam:SetDefaultPolicyVersion"
                            ],
                            "Resource": "*"
                        }
                    },
                    "IsDefaultVersion": true
                }
            ],
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:policy/create-update-delete-set-managed-policies",
            "UpdateDate": "2015-02-06T19:58:34Z"
        },
        {
            "PolicyName": "S3-read-only-specific-bucket",
            "CreateDate": "2015-01-21T21:39:41Z",
            "AttachmentCount": 1,
            "IsAttachable": true,
            "PolicyId": "ANPA1234567890EXAMPLE",
            "DefaultVersionId": "v1",
            "PolicyVersionList": [
                {
                    "CreateDate": "2015-01-21T21:39:41Z",
                    "VersionId": "v1",
                    "Document": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Action": [
                                    "s3:Get*",
                                    "s3:List*"
                                ],
                                "Resource": [
                                    "arn:aws:s3:::amzn-s3-demo-bucket",
                                    "arn:aws:s3:::amzn-s3-demo-bucket/*"
                                ]
                            }
                        ]
                    },
                    "IsDefaultVersion": true
                }
            ],
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:policy/S3-read-only-specific-bucket",
            "UpdateDate": "2015-01-21T23:39:41Z"
        },
        {
            "PolicyName": "AmazonEC2FullAccess",
            "CreateDate": "2015-02-06T18:40:15Z",
            "AttachmentCount": 1,
            "IsAttachable": true,
            "PolicyId": "ANPA1234567890EXAMPLE",
            "DefaultVersionId": "v1",
            "PolicyVersionList": [
                {
                    "CreateDate": "2014-10-30T20:59:46Z",
                    "VersionId": "v1",
                    "Document": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Action": "ec2:*",
                                "Effect": "Allow",
                                "Resource": "*"
                            },
                            {
                                "Effect": "Allow",
                                "Action": "elasticloadbalancing:*",
                                "Resource": "*"
                            },
                            {
                                "Effect": "Allow",
                                "Action": "cloudwatch:*",
                                "Resource": "*"
                            },
                            {
                                "Effect": "Allow",
                                "Action": "autoscaling:*",
                                "Resource": "*"
                            }
                        ]
                    },
                    "IsDefaultVersion": true
                }
            ],
            "Path": "/",
            "Arn": "arn:aws:iam::aws:policy/AmazonEC2FullAccess",
            "UpdateDate": "2015-02-06T18:40:15Z"
        }
    ],
    "Marker": "EXAMPLEkakv9BCuUNFDtxWSyfzetYwEx2ADc8dnzfvERF5S6YMvXKx41t6gCl/eeaCX3Jo94/bKqezEAg8TEVS99EKFLxm3jtbpl25FDWEXAMPLE",
    "IsTruncated": true
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [AWS 보안 감사 지침](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-audit-guide.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetAccountAuthorizationDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-account-authorization-details.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제에서는 AWS 계정의 자격 증명에 대한 권한 부여 세부 정보를 가져오고 사용자, 그룹 및 역할을 포함하여 반환된 객체의 요소 목록을 표시합니다. 예를 들어, `UserDetailList` 속성은 사용자에 대한 세부 정보를 표시합니다. `RoleDetailList` 및 `GroupDetailList` 속성에서 유사한 정보를 확인할 수 있습니다.**  

```
$Details=Get-IAMAccountAuthorizationDetail
$Details
```
**출력:**  

```
GroupDetailList : {Administrators, Developers, Testers, Backup}
IsTruncated     : False
Marker          : 
RoleDetailList  : {TestRole1, AdminRole, TesterRole, clirole...}
UserDetailList  : {Administrator, Bob, BackupToS3, }
```

```
$Details.UserDetailList
```
**출력:**  

```
Arn            : arn:aws:iam::123456789012:user/Administrator
CreateDate     : 10/16/2014 9:03:09 AM
GroupList      : {Administrators}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE1
UserName       : Administrator
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/Bob
CreateDate     : 4/6/2015 12:54:42 PM
GroupList      : {Developers}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE2
UserName       : bab
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/BackupToS3
CreateDate     : 1/27/2015 10:15:08 AM
GroupList      : {Backup}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE3
UserName       : BackupToS3
UserPolicyList : {BackupServicePermissionsToS3Buckets}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetAccountAuthorizationDetails](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제에서는 AWS 계정의 자격 증명에 대한 권한 부여 세부 정보를 가져오고 사용자, 그룹 및 역할을 포함하여 반환된 객체의 요소 목록을 표시합니다. 예를 들어, `UserDetailList` 속성은 사용자에 대한 세부 정보를 표시합니다. `RoleDetailList` 및 `GroupDetailList` 속성에서 유사한 정보를 확인할 수 있습니다.**  

```
$Details=Get-IAMAccountAuthorizationDetail
$Details
```
**출력:**  

```
GroupDetailList : {Administrators, Developers, Testers, Backup}
IsTruncated     : False
Marker          : 
RoleDetailList  : {TestRole1, AdminRole, TesterRole, clirole...}
UserDetailList  : {Administrator, Bob, BackupToS3, }
```

```
$Details.UserDetailList
```
**출력:**  

```
Arn            : arn:aws:iam::123456789012:user/Administrator
CreateDate     : 10/16/2014 9:03:09 AM
GroupList      : {Administrators}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE1
UserName       : Administrator
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/Bob
CreateDate     : 4/6/2015 12:54:42 PM
GroupList      : {Developers}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE2
UserName       : bab
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/BackupToS3
CreateDate     : 1/27/2015 10:15:08 AM
GroupList      : {Backup}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE3
UserName       : BackupToS3
UserPolicyList : {BackupServicePermissionsToS3Buckets}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetAccountAuthorizationDetails](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def get_authorization_details(response_filter):
    """
    Gets an authorization detail report for the current account.

    :param response_filter: A list of resource types to include in the report, such
                            as users or roles. When not specified, all resources
                            are included.
    :return: The authorization detail report.
    """
    try:
        account_details = iam.meta.client.get_account_authorization_details(
            Filter=response_filter
        )
        logger.debug(account_details)
    except ClientError:
        logger.exception("Couldn't get details for your account.")
        raise
    else:
        return account_details
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetAccountAuthorizationDetails](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountAuthorizationDetails)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->getaccountauthdetails( ).
        MESSAGE 'Retrieved account authorization details.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting account authorization details.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Gets the IAM password policy for an AWS account.
    /// </summary>
    /// <returns>The PasswordPolicy for the AWS account.</returns>
    public async Task<PasswordPolicy> GetAccountPasswordPolicyAsync()
    {
        var response = await _IAMService.GetAccountPasswordPolicyAsync(new GetAccountPasswordPolicyRequest());
        return response.PasswordPolicy;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetAccountPasswordPolicy)를 참조하세요.

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

**AWS CLI**  
**현재 계정 암호 정책 보기**  
다음 `get-account-password-policy` 명령은 현재 계정의 암호 정책에 대한 세부 정보를 표시합니다.  

```
aws iam get-account-password-policy
```
출력:  

```
{
    "PasswordPolicy": {
        "AllowUsersToChangePassword": false,
        "RequireLowercaseCharacters": false,
        "RequireUppercaseCharacters": false,
        "MinimumPasswordLength": 8,
        "RequireNumbers": true,
        "RequireSymbols": true
    }
}
```
계정에 대해 정의된 암호 정책이 없는 경우 명령은 `NoSuchEntity` 오류를 반환합니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자의 계정 암호 정책 설정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetAccountPasswordPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-account-password-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// GetAccountPasswordPolicy gets the account password policy for the current account.
// If no policy has been set, a NoSuchEntityException is error is returned.
func (wrapper AccountWrapper) GetAccountPasswordPolicy(ctx context.Context) (*types.PasswordPolicy, error) {
	var pwPolicy *types.PasswordPolicy
	result, err := wrapper.IamClient.GetAccountPasswordPolicy(ctx,
		&iam.GetAccountPasswordPolicyInput{})
	if err != nil {
		log.Printf("Couldn't get account password policy. Here's why: %v\n", err)
	} else {
		pwPolicy = result.PasswordPolicy
	}
	return pwPolicy, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [GetAccountPasswordPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetAccountPasswordPolicy)를 참조하십시오.

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

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

```
import {
  GetAccountPasswordPolicyCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const getAccountPasswordPolicy = async () => {
  const command = new GetAccountPasswordPolicyCommand({});

  const response = await client.send(command);
  console.log(response.PasswordPolicy);
  return response;
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetAccountPasswordPolicyCommand)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function getAccountPasswordPolicy()
    {
        return $this->iamClient->getAccountPasswordPolicy();
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/GetAccountPasswordPolicy)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 현재 계정의 암호 정책에 대한 세부 정보를 반환합니다. 계정에 대해 정의된 암호 정책이 없는 경우 명령은 `NoSuchEntity` 오류를 반환합니다.**  

```
Get-IAMAccountPasswordPolicy
```
**출력:**  

```
AllowUsersToChangePassword : True
ExpirePasswords            : True
HardExpiry                 : False
MaxPasswordAge             : 90
MinimumPasswordLength      : 8
PasswordReusePrevention    : 20
RequireLowercaseCharacters : True
RequireNumbers             : True
RequireSymbols             : False
RequireUppercaseCharacters : True
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 현재 계정의 암호 정책에 대한 세부 정보를 반환합니다. 계정에 대해 정의된 암호 정책이 없는 경우 명령은 `NoSuchEntity` 오류를 반환합니다.**  

```
Get-IAMAccountPasswordPolicy
```
**출력:**  

```
AllowUsersToChangePassword : True
ExpirePasswords            : True
HardExpiry                 : False
MaxPasswordAge             : 90
MinimumPasswordLength      : 8
PasswordReusePrevention    : 20
RequireLowercaseCharacters : True
RequireNumbers             : True
RequireSymbols             : False
RequireUppercaseCharacters : True
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetAccountPasswordPolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def print_password_policy():
    """
    Prints the password policy for the account.
    """
    try:
        pw_policy = iam.AccountPasswordPolicy()
        print("Current account password policy:")
        print(
            f"\tallow_users_to_change_password: {pw_policy.allow_users_to_change_password}"
        )
        print(f"\texpire_passwords: {pw_policy.expire_passwords}")
        print(f"\thard_expiry: {pw_policy.hard_expiry}")
        print(f"\tmax_password_age: {pw_policy.max_password_age}")
        print(f"\tminimum_password_length: {pw_policy.minimum_password_length}")
        print(f"\tpassword_reuse_prevention: {pw_policy.password_reuse_prevention}")
        print(
            f"\trequire_lowercase_characters: {pw_policy.require_lowercase_characters}"
        )
        print(f"\trequire_numbers: {pw_policy.require_numbers}")
        print(f"\trequire_symbols: {pw_policy.require_symbols}")
        print(
            f"\trequire_uppercase_characters: {pw_policy.require_uppercase_characters}"
        )
        printed = True
    except ClientError as error:
        if error.response["Error"]["Code"] == "NoSuchEntity":
            print("The account does not have a password policy set.")
        else:
            logger.exception("Couldn't get account password policy.")
            raise
    else:
        return printed
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountPasswordPolicy)를 참조하십시오.

------
#### [ Ruby ]

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

```
# Class to manage IAM account password policies
class PasswordPolicyManager
  attr_accessor :iam_client, :logger

  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'IAMPolicyManager'
  end

  # Retrieves and logs the account password policy
  def print_account_password_policy
    response = @iam_client.get_account_password_policy
    @logger.info("The account password policy is: #{response.password_policy.to_h}")
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.info('The account does not have a password policy.')
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't print the account password policy. Error: #{e.code} - #{e.message}")
    raise
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetAccountPasswordPolicy)를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn get_account_password_policy(
    client: &iamClient,
) -> Result<GetAccountPasswordPolicyOutput, SdkError<GetAccountPasswordPolicyError>> {
    let response = client.get_account_password_policy().send().await?;

    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [GetAccountPasswordPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.get_account_password_policy)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->getaccountpasswordpolicy( ).
        MESSAGE 'Retrieved account password policy.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'No password policy exists.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting password policy.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GetAccountPasswordPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [계정 관리](iam_example_iam_Scenario_AccountManagement_section.md) 

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

**AWS CLI**  
**현재 계정의 IAM 엔터티 사용량 및 IAM 할당량에 대한 정보 가져오기**  
다음 `get-account-summary` 명령은 계정의 현재 IAM 엔터티 사용량과 현재 IAM 엔터티 할당량에 대한 정보를 반환합니다.  

```
aws iam get-account-summary
```
출력:  

```
{
    "SummaryMap": {
        "UsersQuota": 5000,
        "GroupsQuota": 100,
        "InstanceProfiles": 6,
        "SigningCertificatesPerUserQuota": 2,
        "AccountAccessKeysPresent": 0,
        "RolesQuota": 250,
        "RolePolicySizeQuota": 10240,
        "AccountSigningCertificatesPresent": 0,
        "Users": 27,
        "ServerCertificatesQuota": 20,
        "ServerCertificates": 0,
        "AssumeRolePolicySizeQuota": 2048,
        "Groups": 7,
        "MFADevicesInUse": 1,
        "Roles": 3,
        "AccountMFAEnabled": 1,
        "MFADevices": 3,
        "GroupsPerUserQuota": 10,
        "GroupPolicySizeQuota": 5120,
        "InstanceProfilesQuota": 100,
        "AccessKeysPerUserQuota": 2,
        "Providers": 0,
        "UserPolicySizeQuota": 2048
    }
}
```
개체 제한에 대한 자세한 내용은 [IAM 사용 설명서의 IAM 및 AWS STS 할당량을 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html). *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetAccountSummary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-account-summary.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 AWS 계정의 현재 IAM 엔터티 사용량과 현재 IAM 엔터티 할당량에 대한 정보를 반환합니다.**  

```
Get-IAMAccountSummary
```
**출력:**  

```
Key                                        Value
Users                                      7
GroupPolicySizeQuota                       5120
PolicyVersionsInUseQuota                   10000
ServerCertificatesQuota                    20
AccountSigningCertificatesPresent          0
AccountAccessKeysPresent                   0
Groups                                     3
UsersQuota                                 5000
RolePolicySizeQuota                        10240
UserPolicySizeQuota                        2048
GroupsPerUserQuota                         10
AssumeRolePolicySizeQuota                  2048
AttachedPoliciesPerGroupQuota              2
Roles                                      9
VersionsPerPolicyQuota                     5
GroupsQuota                                100
PolicySizeQuota                            5120
Policies                                   5
RolesQuota                                 250
ServerCertificates                         0
AttachedPoliciesPerRoleQuota               2
MFADevicesInUse                            2
PoliciesQuota                              1000
AccountMFAEnabled                          1
Providers                                  2
InstanceProfilesQuota                      100
MFADevices                                 4
AccessKeysPerUserQuota                     2
AttachedPoliciesPerUserQuota               2
SigningCertificatesPerUserQuota            2
PolicyVersionsInUse                        4
InstanceProfiles                           1
...
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetAccountSummary](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 AWS 계정의 현재 IAM 엔터티 사용량과 현재 IAM 엔터티 할당량에 대한 정보를 반환합니다.**  

```
Get-IAMAccountSummary
```
**출력:**  

```
Key                                        Value
Users                                      7
GroupPolicySizeQuota                       5120
PolicyVersionsInUseQuota                   10000
ServerCertificatesQuota                    20
AccountSigningCertificatesPresent          0
AccountAccessKeysPresent                   0
Groups                                     3
UsersQuota                                 5000
RolePolicySizeQuota                        10240
UserPolicySizeQuota                        2048
GroupsPerUserQuota                         10
AssumeRolePolicySizeQuota                  2048
AttachedPoliciesPerGroupQuota              2
Roles                                      9
VersionsPerPolicyQuota                     5
GroupsQuota                                100
PolicySizeQuota                            5120
Policies                                   5
RolesQuota                                 250
ServerCertificates                         0
AttachedPoliciesPerRoleQuota               2
MFADevicesInUse                            2
PoliciesQuota                              1000
AccountMFAEnabled                          1
Providers                                  2
InstanceProfilesQuota                      100
MFADevices                                 4
AccessKeysPerUserQuota                     2
AttachedPoliciesPerUserQuota               2
SigningCertificatesPerUserQuota            2
PolicyVersionsInUse                        4
InstanceProfiles                           1
...
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetAccountSummary](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def get_summary():
    """
    Gets a summary of account usage.

    :return: The summary of account usage.
    """
    try:
        summary = iam.AccountSummary()
        logger.debug(summary.summary_map)
    except ClientError:
        logger.exception("Couldn't get a summary for your account.")
        raise
    else:
        return summary.summary_map
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetAccountSummary](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountSummary)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->getaccountsummary( ).
        MESSAGE 'Retrieved account summary.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting account summary.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GetAccountSummary](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `GetContextKeysForCustomPolicy` 사용
<a name="iam_example_iam_GetContextKeysForCustomPolicy_section"></a>

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

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

**AWS CLI**  
**예제 1: 명령줄에서 파라미터로 제공된 하나 이상의 사용자 지정 JSON 정책에서 참조하는 컨텍스트 키 나열**  
다음 `get-context-keys-for-custom-policy` 명령은 제공된 각 정책을 구문 분석하고 해당 정책에서 사용되는 컨텍스트 키를 나열합니다. 이 명령을 사용하여 정책 시뮬레이터 명령 `simulate-custom-policy` 및 `simulate-custom-policy`를 성공적으로 사용하기 위해 제공해야 하는 컨텍스트 키 값을 식별합니다. `get-context-keys-for-custom-policy` 명령을 사용하여 IAM 사용자 또는 역할과 관련된 모든 정책에서 사용되는 컨텍스트 키 목록을 검색할 수도 있습니다. `file://`로 시작하는 파라미터 값은 명령에 파일을 읽고 파일 이름 자체 대신 파라미터 값으로 내용을 사용하도록 지시합니다.  

```
aws iam get-context-keys-for-custom-policy \
    --policy-input-list '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/${aws:username}","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
```
출력:  

```
{
    "ContextKeyNames": [
        "aws:username",
        "aws:CurrentTime"
    ]
}
```
**예제 2: 파일 입력으로 제공된 하나 이상의 사용자 지정 JSON 정책에서 참조하는 컨텍스트 키 나열**  
다음 `get-context-keys-for-custom-policy` 명령은 정책이 파라미터 대신 파일로 제공된다는 점을 제외하면 이전 예와 동일합니다. 명령에는 JSON 구조 목록이 아닌 JSON 문자열 목록이 필요하므로 파일은 하나로 축소할 수 있지만 다음과 같이 구성되어야 합니다.  

```
[
    "Policy1",
    "Policy2"
]
```
예를 들어 이전 예제의 정책이 포함된 파일은 다음과 같아야 합니다. 정책 문자열 내에 포함된 각 큰따옴표는 앞에 백슬래시를 붙여 이스케이프 처리해야 합니다.  

```
[ "{\"Version\": \"2012-10-17\", \"Statement\": {\"Effect\": \"Allow\", \"Action\": \"dynamodb:*\", \"Resource\": \"arn:aws:dynamodb:us-west-2:128716708097:table/${aws:username}\", \"Condition\": {\"DateGreaterThan\": {\"aws:CurrentTime\": \"2015-08-16T12:00:00Z\"}}}}" ]
```
그런 다음 이 파일을 다음 명령에 제출할 수 있습니다.  

```
aws iam get-context-keys-for-custom-policy \
    --policy-input-list file://policyfile.json
```
출력:  

```
{
    "ContextKeyNames": [
        "aws:username",
        "aws:CurrentTime"
    ]
}
```
자세한 내용은 [IAM 사용 설명서의 IAM 정책 시뮬레이터(AWS CLI 및 AWS API) 사용을](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html#policies-simulator-using-api) 참조하세요. *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetContextKeysForCustomPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-context-keys-for-custom-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 제공된 정책 json에 있는 모든 컨텍스트 키를 가져옵니다. 여러 정책을 제공하려면 쉼표로 구분된 값 목록으로 제공합니다.**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForCustomPolicy -PolicyInputList $policy1,$policy2
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetContextKeysForCustomPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 제공된 정책 json에 있는 모든 컨텍스트 키를 가져옵니다. 여러 정책을 제공하려면 쉼표로 구분된 값 목록으로 제공합니다.**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForCustomPolicy -PolicyInputList $policy1,$policy2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetContextKeysForCustomPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetContextKeysForPrincipalPolicy` 사용
<a name="iam_example_iam_GetContextKeysForPrincipalPolicy_section"></a>

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

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

**AWS CLI**  
**IAM 위탁자와 연결된 모든 정책에서 참조하는 컨텍스트 키 나열**  
다음 `get-context-keys-for-principal-policy` 명령은 사용자 `saanvi` 및 해당 사용자가 속한 그룹에 연결된 모든 정책을 검색합니다. 그런 다음 각 정책을 분석하여 해당 정책에서 사용하는 컨텍스트 키를 나열합니다. 이 명령을 사용하여 `simulate-custom-policy` 및 `simulate-principal-policy` 명령을 성공적으로 사용하기 위해 제공해야 하는 컨텍스트 키 값을 식별합니다. `get-context-keys-for-custom-policy` 명령을 사용하여 임의의 JSON 정책에서 사용하는 컨텍스트 키 목록을 검색할 수도 있습니다.  

```
aws iam get-context-keys-for-principal-policy \
   --policy-source-arn arn:aws:iam::123456789012:user/saanvi
```
출력:  

```
{
    "ContextKeyNames": [
        "aws:username",
        "aws:CurrentTime"
    ]
}
```
자세한 내용은 [IAM 사용 설명서의 IAM 정책 시뮬레이터(AWS CLI 및 AWS API) 사용을](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html#policies-simulator-using-api) 참조하세요. *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetContextKeysForPrincipalPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-context-keys-for-principal-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 제공된 정책 json에 있는 모든 컨텍스트 키와 IAM 엔티티(사용자/역할 등)에 연결된 정책을 가져옵니다. -PolicyInputList의 경우 여러 값 목록을 쉼표로 구분된 값으로 제공할 수 있습니다. **   

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForPrincipalPolicy -PolicyInputList $policy1,$policy2 -PolicySourceArn arn:aws:iam::852640994763:user/TestUser
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 제공된 정책 json에 있는 모든 컨텍스트 키와 IAM 엔티티(사용자/역할 등)에 연결된 정책을 가져옵니다. -PolicyInputList의 경우 여러 값 목록을 쉼표로 구분된 값으로 제공할 수 있습니다. **   

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForPrincipalPolicy -PolicyInputList $policy1,$policy2 -PolicySourceArn arn:aws:iam::852640994763:user/TestUser
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [계정 관리](iam_example_iam_Scenario_AccountManagement_section.md) 

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

**AWS CLI**  
**자격 증명 보고서 가져오기**  
이 예제에서는 반환된 보고서를 열고 파이프라인에 텍스트 라인 배열로 출력합니다.  

```
aws iam get-credential-report
```
출력:  

```
{
    "GeneratedTime":  "2015-06-17T19:11:50Z",
    "ReportFormat": "text/csv"
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [AWS 계정에 대한 자격 증명 보고서 가져오기를 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html).  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetCredentialReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-credential-report.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 반환된 보고서를 열고 파이프라인에 텍스트 라인 배열로 출력합니다. 줄 1은 쉼표로 구분된 열 이름이 있는 헤더입니다. 그 후의 각 행은 한 사용자에 대한 세부 정보 행이며 각 필드는 쉼표로 구분됩니다. 보고서를 보려면 먼저 `Request-IAMCredentialReport` cmdlet을 사용하여 보고서를 생성해야 합니다. 보고서를 단일 문자열로 검색하려면 `-AsTextArray` 대신 `-Raw`를 사용합니다. `-AsTextArray` 스위치에는 `-SplitLines` 별칭도 허용됩니다. 출력의 전체 열 목록은 서비스 API 참조를 참조하세요. `-AsTextArray` 또는 `-SplitLines`를 사용하지 않는 경우 .NET `StreamReader` 클래스를 사용하여 `.Content` 속성에서 텍스트를 추출해야 합니다.**  

```
Request-IAMCredentialReport
```
**출력:**  

```
Description                                                         State
-----------                                                         -----
No report exists. Starting a new report generation task             STARTED
```

```
Get-IAMCredentialReport -AsTextArray
```
**출력:**  

```
      user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_2_active,access_key_2_last_rotated,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated root_account,arn:aws:iam::123456789012:root,2014-10-15T16:31:25+00:00,not_supported,2015-04-20T17:41:10+00:00,not_supported,not_supported,true,false,N/A,false,N/A,false,N/A,false,N/A
Administrator,arn:aws:iam::123456789012:user/Administrator,2014-10-16T16:03:09+00:00,true,2015-04-20T15:18:32+00:00,2014-10-16T16:06:00+00:00,N/A,false,true,2014-12-03T18:53:41+00:00,true,2015-03-25T20:38:14+00:00,false,N/A,false,N/A
Bill,arn:aws:iam::123456789012:user/Bill,2015-04-15T18:27:44+00:00,false,N/A,N/A,N/A,false,false,N/A,false,N/A,false,2015-04-20T20:00:12+00:00,false,N/A
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetCredentialReport](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 반환된 보고서를 열고 파이프라인에 텍스트 라인 배열로 출력합니다. 줄 1은 쉼표로 구분된 열 이름이 있는 헤더입니다. 그 후의 각 행은 한 사용자에 대한 세부 정보 행이며 각 필드는 쉼표로 구분됩니다. 보고서를 보려면 먼저 `Request-IAMCredentialReport` cmdlet을 사용하여 보고서를 생성해야 합니다. 보고서를 단일 문자열로 검색하려면 `-AsTextArray` 대신 `-Raw`를 사용합니다. `-AsTextArray` 스위치에는 `-SplitLines` 별칭도 허용됩니다. 출력의 전체 열 목록은 서비스 API 참조를 참조하세요. `-AsTextArray` 또는 `-SplitLines`를 사용하지 않는 경우 .NET `StreamReader` 클래스를 사용하여 `.Content` 속성에서 텍스트를 추출해야 합니다.**  

```
Request-IAMCredentialReport
```
**출력:**  

```
Description                                                         State
-----------                                                         -----
No report exists. Starting a new report generation task             STARTED
```

```
Get-IAMCredentialReport -AsTextArray
```
**출력:**  

```
      user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_2_active,access_key_2_last_rotated,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated root_account,arn:aws:iam::123456789012:root,2014-10-15T16:31:25+00:00,not_supported,2015-04-20T17:41:10+00:00,not_supported,not_supported,true,false,N/A,false,N/A,false,N/A,false,N/A
Administrator,arn:aws:iam::123456789012:user/Administrator,2014-10-16T16:03:09+00:00,true,2015-04-20T15:18:32+00:00,2014-10-16T16:06:00+00:00,N/A,false,true,2014-12-03T18:53:41+00:00,true,2015-03-25T20:38:14+00:00,false,N/A,false,N/A
Bill,arn:aws:iam::123456789012:user/Bill,2015-04-15T18:27:44+00:00,false,N/A,N/A,N/A,false,false,N/A,false,N/A,false,2015-04-20T20:00:12+00:00,false,N/A
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetCredentialReport](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def get_credential_report():
    """
    Gets the most recently generated credentials report about the current account.

    :return: The credentials report.
    """
    try:
        response = iam.meta.client.get_credential_report()
        logger.debug(response["Content"])
    except ClientError:
        logger.exception("Couldn't get credentials report.")
        raise
    else:
        return response["Content"]
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetCredentialReport](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetCredentialReport)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->getcredentialreport( ).
        MESSAGE 'Retrieved credential report.' TYPE 'I'.
      CATCH /aws1/cx_iamcredrptnotpresen00.
        MESSAGE 'Credential report not present.' TYPE 'E'.
      CATCH /aws1/cx_iamcredrptexpiredex.
        MESSAGE 'Credential report expired.' TYPE 'E'.
      CATCH /aws1/cx_iamcredrptnotreadyex.
        MESSAGE 'Credential report not ready.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting credential report.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GetCredentialReport](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `GetGroup` 사용
<a name="iam_example_iam_GetGroup_section"></a>

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

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

**AWS CLI**  
**IAM 그룹 가져오기**  
이 예제는 IAM 그룹 `Admins`에 대한 세부 정보를 반환합니다.  

```
aws iam get-group \
    --group-name Admins
```
출력:  

```
{
    "Group": {
        "Path": "/",
        "CreateDate": "2015-06-16T19:41:48Z",
        "GroupId": "AIDGPMS9RO4H3FEXAMPLE",
        "Arn": "arn:aws:iam::123456789012:group/Admins",
        "GroupName": "Admins"
    },
    "Users": []
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM ID(사용자, 그룹 및 역할)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-group.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 그룹에 속한 모든 IAM 사용자의 모음을 포함하여 IAM 그룹 `Testers`에 대한 세부 정보를 반환합니다.**  

```
$results = Get-IAMGroup -GroupName "Testers"
$results
```
**출력:**  

```
Group                                     IsTruncated           Marker                Users
-----                                     -----------           ------                -----
Amazon.IdentityManagement.Model.Group     False                                       {Theresa, David}
```

```
$results.Group
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : 3RHNZZGQJ7QHMAEXAMPLE1
GroupName  : Testers
Path       : /
```

```
$results.Users
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/Theresa
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : 4OSVDDJJTF4XEEXAMPLE2
UserName         : Theresa

Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE3
UserName         : David
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 그룹에 속한 모든 IAM 사용자의 모음을 포함하여 IAM 그룹 `Testers`에 대한 세부 정보를 반환합니다.**  

```
$results = Get-IAMGroup -GroupName "Testers"
$results
```
**출력:**  

```
Group                                     IsTruncated           Marker                Users
-----                                     -----------           ------                -----
Amazon.IdentityManagement.Model.Group     False                                       {Theresa, David}
```

```
$results.Group
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : 3RHNZZGQJ7QHMAEXAMPLE1
GroupName  : Testers
Path       : /
```

```
$results.Users
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/Theresa
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : 4OSVDDJJTF4XEEXAMPLE2
UserName         : Theresa

Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE3
UserName         : David
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetGroupPolicy` 사용
<a name="iam_example_iam_GetGroupPolicy_section"></a>

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

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

**AWS CLI**  
**IAM 그룹에 연결된 정책에 대한 정보 가져오기**  
다음 `get-group-policy` 명령은 `Test-Group`이라는 그룹에 연결된 지정된 정책에 대한 정보를 가져옵니다.  

```
aws iam get-group-policy \
    --group-name Test-Group \
    --policy-name S3-ReadOnly-Policy
```
출력:  

```
{
    "GroupName": "Test-Group",
    "PolicyDocument": {
        "Statement": [
            {
                "Action": [
                    "s3:Get*",
                    "s3:List*"
                ],
                "Resource": "*",
                "Effect": "Allow"
            }
        ]
    },
    "PolicyName": "S3-ReadOnly-Policy"
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 정책 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-group-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Testers` 그룹에 대해 `PowerUserAccess-Testers`라는 포함된 인라인 정책에 대한 세부 정보를 반환합니다. `PolicyDocument` 속성은 URL로 인코딩됩니다. 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다.**  

```
$results = Get-IAMGroupPolicy -GroupName Testers -PolicyName PowerUserAccess-Testers
$results
```
**출력:**  

```
GroupName     PolicyDocument                                              PolicyName
---------     --------------                                              ----------
Testers       %7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0A%20... PowerUserAccess-Testers

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
  ]
}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Testers` 그룹에 대해 `PowerUserAccess-Testers`라는 포함된 인라인 정책에 대한 세부 정보를 반환합니다. `PolicyDocument` 속성은 URL로 인코딩됩니다. 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다.**  

```
$results = Get-IAMGroupPolicy -GroupName Testers -PolicyName PowerUserAccess-Testers
$results
```
**출력:**  

```
GroupName     PolicyDocument                                              PolicyName
---------     --------------                                              ----------
Testers       %7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0A%20... PowerUserAccess-Testers

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
  ]
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetInstanceProfile` 사용
<a name="iam_example_iam_GetInstanceProfile_section"></a>

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

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

**AWS CLI**  
**인스턴스 프로파일 정보 가져오기**  
다음 `get-instance-profile` 명령은 이름이 `ExampleInstanceProfile`인 인스턴스 프로파일에 대한 정보를 가져옵니다.  

```
aws iam get-instance-profile \
    --instance-profile-name ExampleInstanceProfile
```
출력:  

```
{
    "InstanceProfile": {
        "InstanceProfileId": "AID2MAB8DPLSRHEXAMPLE",
        "Roles": [
            {
                "AssumeRolePolicyDocument": "<URL-encoded-JSON>",
                "RoleId": "AIDGPMS9RO4H3FEXAMPLE",
                "CreateDate": "2013-01-09T06:33:26Z",
                "RoleName": "Test-Role",
                "Path": "/",
                "Arn": "arn:aws:iam::336924118301:role/Test-Role"
            }
        ],
        "CreateDate": "2013-06-12T23:52:02Z",
        "InstanceProfileName": "ExampleInstanceProfile",
        "Path": "/",
        "Arn": "arn:aws:iam::336924118301:instance-profile/ExampleInstanceProfile"
    }
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [인스턴스 프로파일 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-instance-profile.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제`ec2instancerole`는 현재 AWS 계정에 정의된 인스턴스 프로파일의 세부 정보를 반환합니다.**  

```
Get-IAMInstanceProfile -InstanceProfileName ec2instancerole
```
**출력:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제`ec2instancerole`는 현재 AWS 계정에 정의된 인스턴스 프로파일의 세부 정보를 반환합니다.**  

```
Get-IAMInstanceProfile -InstanceProfileName ec2instancerole
```
**출력:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetLoginProfile` 사용
<a name="iam_example_iam_GetLoginProfile_section"></a>

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

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

**AWS CLI**  
**IAM 사용자의 암호 정보 가져오기**  
다음 `get-login-profile` 명령은 이름이 `Bob`인 IAM 사용자의 암호에 대한 정보를 가져옵니다.  

```
aws iam get-login-profile \
    --user-name Bob
```
출력:  

```
{
    "LoginProfile": {
        "UserName": "Bob",
        "CreateDate": "2012-09-21T23:03:39Z"
    }
}
```
`get-login-profile` 명령을 사용하여 IAM 사용자에게 암호가 있는지 확인할 수 있습니다. 사용자에 대해 정의된 암호가 없는 경우 명령은 `NoSuchEntity` 오류를 반환합니다.  
이 명령을 사용해 암호를 볼 수는 없습니다. 암호를 잊어버린 경우 사용자의 암호를 재설정(`update-login-profile`)할 수 있습니다. 또는 사용자의 로그인 프로파일을 삭제(`delete-login-profile`)한 다음 새 프로파일을 생성(`create-login-profile`)할 수 있습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자 암호 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-login-profile.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 암호 생성 날짜와 IAM 사용자 `David`에 대해 암호 재설정이 필요한지 여부를 반환합니다.**  

```
Get-IAMLoginProfile -UserName David
```
**출력:**  

```
CreateDate                   PasswordResetRequired                 UserName
----------                   ---------------------                 --------
12/10/2014 3:39:44 PM        False                                 David
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetLoginProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 암호 생성 날짜와 IAM 사용자 `David`에 대해 암호 재설정이 필요한지 여부를 반환합니다.**  

```
Get-IAMLoginProfile -UserName David
```
**출력:**  

```
CreateDate                   PasswordResetRequired                 UserName
----------                   ---------------------                 --------
12/10/2014 3:39:44 PM        False                                 David
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `GetOpenIdConnectProvider` 사용
<a name="iam_example_iam_GetOpenIdConnectProvider_section"></a>

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

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

**AWS CLI**  
**지정된 OpenID Connect 제공업체에 대한 정보 반환**  
이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/server.example.com`인 OpenID Connect 제공업체에 대한 세부 정보를 반환합니다.  

```
aws iam get-open-id-connect-provider \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/server.example.com
```
출력:  

```
{
    "Url": "server.example.com"
        "CreateDate": "2015-06-16T19:41:48Z",
        "ThumbprintList": [
        "12345abcdefghijk67890lmnopqrst987example"
        ],
        "ClientIDList": [
        "example-application-ID"
        ]
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM에서 OIDC(OpenID Connect) ID 제공업체 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-open-id-connect-provider.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/accounts.google.com`인 OpenID Connect 제공업체에 대한 세부 정보를 반환합니다. `ClientIDList` 속성은 이 제공업체에 대해 정의된 모든 클라이언트 ID를 포함하는 컬렉션입니다.**  

```
Get-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/oidc.example.com
```
**출력:**  

```
ClientIDList         CreateDate                ThumbprintList                               Url
------------         ----------                --------------                               ---
{MyOIDCApp}          2/3/2015 3:00:30 PM       {12345abcdefghijk67890lmnopqrst98765uvwxy}   oidc.example.com
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/accounts.google.com`인 OpenID Connect 제공업체에 대한 세부 정보를 반환합니다. `ClientIDList` 속성은 이 제공업체에 대해 정의된 모든 클라이언트 ID를 포함하는 컬렉션입니다.**  

```
Get-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/oidc.example.com
```
**출력:**  

```
ClientIDList         CreateDate                ThumbprintList                               Url
------------         ----------                --------------                               ---
{MyOIDCApp}          2/3/2015 3:00:30 PM       {12345abcdefghijk67890lmnopqrst98765uvwxy}   oidc.example.com
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [IAM 정책 빌더 API 작업](iam_example_iam_Scenario_IamPolicyBuilder_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// Get information about an IAM policy.
    /// </summary>
    /// <param name="policyArn">The IAM policy to retrieve information for.</param>
    /// <returns>The IAM policy.</returns>
    public async Task<ManagedPolicy> GetPolicyAsync(string policyArn)
    {

        var response = await _IAMService.GetPolicyAsync(new GetPolicyRequest { PolicyArn = policyArn });
        return response.Policy;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [GetPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetPolicy)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::getPolicy(const Aws::String &policyArn,
                            const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::GetPolicyRequest request;
    request.SetPolicyArn(policyArn);

    auto outcome = iam.GetPolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error getting policy " << policyArn << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        const auto &policy = outcome.GetResult().GetPolicy();
        std::cout << "Name: " << policy.GetPolicyName() << std::endl <<
                  "ID: " << policy.GetPolicyId() << std::endl << "Arn: " <<
                  policy.GetArn() << std::endl << "Description: " <<
                  policy.GetDescription() << std::endl << "CreateDate: " <<
                  policy.GetCreateDate().ToGmtString(Aws::Utils::DateFormat::ISO_8601)
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [GetPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/GetPolicy)를 참조하세요.

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

**AWS CLI**  
**지정된 관리형 정책에 대한 정보 검색**  
이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 관리형 정책에 대한 세부 정보를 반환합니다.  

```
aws iam get-policy \
    --policy-arn arn:aws:iam::123456789012:policy/MySamplePolicy
```
출력:  

```
{
    "Policy": {
        "PolicyName": "MySamplePolicy",
        "CreateDate": "2015-06-17T19:23;32Z",
        "AttachmentCount": 0,
        "IsAttachable": true,
        "PolicyId": "Z27SI6FQMGNQ2EXAMPLE1",
        "DefaultVersionId": "v1",
        "Path": "/",
        "Arn": "arn:aws:iam::123456789012:policy/MySamplePolicy",
        "UpdateDate": "2015-06-17T19:23:32Z"
    }
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// GetPolicy gets data about a policy.
func (wrapper PolicyWrapper) GetPolicy(ctx context.Context, policyArn string) (*types.Policy, error) {
	var policy *types.Policy
	result, err := wrapper.IamClient.GetPolicy(ctx, &iam.GetPolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't get policy %v. Here's why: %v\n", policyArn, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [GetPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetPolicy)를 참조하십시오.

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

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

```
import { GetPolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 */
export const getPolicy = (policyArn) => {
  const command = new GetPolicyCommand({
    PolicyArn: policyArn,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-getting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetPolicyCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  PolicyArn: "arn:aws:iam::aws:policy/AWSLambdaExecute",
};

iam.getPolicy(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Policy.Description);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-getting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetPolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/GetPolicy)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun getIAMPolicy(policyArnVal: String?) {
    val request =
        GetPolicyRequest {
            policyArn = policyArnVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.getPolicy(request)
        println("Successfully retrieved policy ${response.policy?.policyName}")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [GetPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function getPolicy($policyArn)
    {
        return $this->customWaiter(function () use ($policyArn) {
            return $this->iamClient->getPolicy(['PolicyArn' => $policyArn]);
        });
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [GetPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/GetPolicy)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 관리형 정책에 대한 세부 정보를 반환합니다.**  

```
Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**출력:**  

```
Arn              : arn:aws:iam::aws:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 2/6/2015 10:40:08 AM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 관리형 정책에 대한 세부 정보를 반환합니다.**  

```
Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**출력:**  

```
Arn              : arn:aws:iam::aws:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 2/6/2015 10:40:08 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetPolicy](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def get_default_policy_statement(policy_arn):
    """
    Gets the statement of the default version of the specified policy.

    :param policy_arn: The ARN of the policy to look up.
    :return: The statement of the default policy version.
    """
    try:
        policy = iam.Policy(policy_arn)
        # To get an attribute of a policy, the SDK first calls get_policy.
        policy_doc = policy.default_version.document
        policy_statement = policy_doc.get("Statement", None)
        logger.info("Got default policy doc for %s.", policy.policy_name)
        logger.info(policy_doc)
    except ClientError:
        logger.exception("Couldn't get default policy statement for %s.", policy_arn)
        raise
    else:
        return policy_statement
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetPolicy)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [GetPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetPolicy)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->getpolicy( iv_policyarn = iv_policy_arn ).
        MESSAGE 'Retrieved policy information.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GetPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func getPolicy(arn: String) async throws -> IAMClientTypes.Policy {
        let input = GetPolicyInput(
            policyArn: arn
        )
        do {
            let output = try await client.getPolicy(input: input)
            guard let policy = output.policy else {
                throw ServiceHandlerError.noSuchPolicy
            }
            return policy
        } catch {
            print("ERROR: getPolicy:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [GetPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/getpolicy(input:))를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 
+  [IAM 정책 빌더 API 작업](iam_example_iam_Scenario_IamPolicyBuilder_section.md) 

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

**AWS CLI**  
**지정된 관리형 정책의 지정된 버전에 대한 정보 검색**  
이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyManagedPolicy`인 정책의 v2 버전에 대한 정책 문서를 반환합니다.  

```
aws iam get-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --version-id v2
```
출력:  

```
{
    "PolicyVersion": {
        "Document": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": "iam:*",
                    "Resource": "*"
                }
            ]
        },
        "VersionId": "v2",
        "IsDefaultVersion": true,
        "CreateDate": "2023-04-11T00:22:54+00:00"
    }
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetPolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-policy-version.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyManagedPolicy`인 정책의 `v2` 버전에 대한 정책 문서를 반환합니다. `Document` 속성의 정책 문서는 URL로 인코딩되며 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다.**  

```
$results = Get-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy -VersionId v2
$results
```
**출력:**  

```
CreateDate             Document                                        IsDefaultVersion     VersionId
----------             --------                                        ----------------     ---------
2/12/2015 9:39:53 AM   %7B%0A%20%20%22Version%22%3A%20%222012-10...    True                 v2

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
$policy = [System.Web.HttpUtility]::UrlDecode($results.Document)
$policy
{
  "Version":"2012-10-17",		 	 	 
  "Statement": 
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetPolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyManagedPolicy`인 정책의 `v2` 버전에 대한 정책 문서를 반환합니다. `Document` 속성의 정책 문서는 URL로 인코딩되며 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다.**  

```
$results = Get-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy -VersionId v2
$results
```
**출력:**  

```
CreateDate             Document                                        IsDefaultVersion     VersionId
----------             --------                                        ----------------     ---------
2/12/2015 9:39:53 AM   %7B%0A%20%20%22Version%22%3A%20%222012-10...    True                 v2

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
$policy = [System.Web.HttpUtility]::UrlDecode($results.Document)
$policy
{
  "Version":"2012-10-17",		 	 	 
  "Statement": 
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetPolicyVersion](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def get_default_policy_statement(policy_arn):
    """
    Gets the statement of the default version of the specified policy.

    :param policy_arn: The ARN of the policy to look up.
    :return: The statement of the default policy version.
    """
    try:
        policy = iam.Policy(policy_arn)
        # To get an attribute of a policy, the SDK first calls get_policy.
        policy_doc = policy.default_version.document
        policy_statement = policy_doc.get("Statement", None)
        logger.info("Got default policy doc for %s.", policy.policy_name)
        logger.info(policy_doc)
    except ClientError:
        logger.exception("Couldn't get default policy statement for %s.", policy_arn)
        raise
    else:
        return policy_statement
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetPolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetPolicyVersion)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Get information about an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to retrieve information
    /// for.</param>
    /// <returns>The IAM role that was retrieved.</returns>
    public async Task<Role> GetRoleAsync(string roleName)
    {
        var response = await _IAMService.GetRoleAsync(new GetRoleRequest
        {
            RoleName = roleName,
        });

        return response.Role;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [GetRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetRole)을 참조하세요.

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

**AWS CLI**  
**IAM 역할 정보 가져오기**  
다음 `get-role` 명령은 이름이 `Test-Role`인 역할에 대한 정보를 가져옵니다.  

```
aws iam get-role \
    --role-name Test-Role
```
출력:  

```
{
    "Role": {
        "Description": "Test Role",
        "AssumeRolePolicyDocument":"<URL-encoded-JSON>",
        "MaxSessionDuration": 3600,
        "RoleId": "AROA1234567890EXAMPLE",
        "CreateDate": "2019-11-13T16:45:56Z",
        "RoleName": "Test-Role",
        "Path": "/",
        "RoleLastUsed": {
            "Region": "us-east-1",
            "LastUsedDate": "2019-11-13T17:14:00Z"
        },
        "Arn": "arn:aws:iam::123456789012:role/Test-Role"
    }
}
```
이 명령은 역할에 연결된 신뢰 정책을 표시합니다. 역할에 연결된 권한 정책을 나열하려면 `list-role-policies` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI  명령 참조의 [GetRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-role.html)을 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// GetRole gets data about a role.
func (wrapper RoleWrapper) GetRole(ctx context.Context, roleName string) (*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.GetRole(ctx,
		&iam.GetRoleInput{RoleName: aws.String(roleName)})
	if err != nil {
		log.Printf("Couldn't get role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [GetRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetRole)을 참조하십시오.

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

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

```
import { GetRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const getRole = (roleName) => {
  const command = new GetRoleCommand({
    RoleName: roleName,
  });

  return client.send(command);
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetRoleCommand)을 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function getRole($roleName)
    {
        return $this->customWaiter(function () use ($roleName) {
            return $this->iamClient->getRole(['RoleName' => $roleName]);
        });
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [GetRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/GetRole)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `lamda_exec_role`의 세부 정보를 반환합니다. 여기에는 이 역할을 수임할 수 있는 사용자를 지정하는 신뢰 정책 문서가 포함됩니다. 정책 문서는 URL로 인코딩되며 .NET `UrlDecode` 메서드를 사용하여 디코딩할 수 있습니다. 이 예제에서는 원래 정책에 업로드되기 전에 모든 공백이 제거됩니다. 역할을 수임한 사람이 수행할 수 있는 작업을 결정하는 권한 정책 문서를 보려면 인라인 정책에는 `Get-IAMRolePolicy`를 사용하고 연결된 관리형 정책에는 `Get-IAMPolicyVersion`을 사용합니다.**  

```
$results = Get-IamRole -RoleName lambda_exec_role
$results | Format-List
```
**출력:**  

```
Arn                      : arn:aws:iam::123456789012:role/lambda_exec_role
AssumeRolePolicyDocument : %7B%22Version%22%3A%222012-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22
                           %3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service
                           %22%3A%22lambda.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole
                           %22%7D%5D%7D
CreateDate               : 4/2/2015 9:16:11 AM
Path                     : /
RoleId                   : 2YBIKAIBHNKB4EXAMPLE1
RoleName                 : lambda_exec_role
```

```
$policy = [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
$policy
```
**출력:**  

```
{"Version":"2012-10-17",		 	 	 "Statement":[{"Sid":"","Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `lamda_exec_role`의 세부 정보를 반환합니다. 여기에는 이 역할을 수임할 수 있는 사용자를 지정하는 신뢰 정책 문서가 포함됩니다. 정책 문서는 URL로 인코딩되며 .NET `UrlDecode` 메서드를 사용하여 디코딩할 수 있습니다. 이 예제에서는 원래 정책에 업로드되기 전에 모든 공백이 제거됩니다. 역할을 수임한 사람이 수행할 수 있는 작업을 결정하는 권한 정책 문서를 보려면 인라인 정책에는 `Get-IAMRolePolicy`를 사용하고 연결된 관리형 정책에는 `Get-IAMPolicyVersion`을 사용합니다.**  

```
$results = Get-IamRole -RoleName lambda_exec_role
$results | Format-List
```
**출력:**  

```
Arn                      : arn:aws:iam::123456789012:role/lambda_exec_role
AssumeRolePolicyDocument : %7B%22Version%22%3A%222012-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22
                           %3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service
                           %22%3A%22lambda.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole
                           %22%7D%5D%7D
CreateDate               : 4/2/2015 9:16:11 AM
Path                     : /
RoleId                   : 2YBIKAIBHNKB4EXAMPLE1
RoleName                 : lambda_exec_role
```

```
$policy = [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
$policy
```
**출력:**  

```
{"Version":"2012-10-17",		 	 	 "Statement":[{"Sid":"","Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetRole](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def get_role(role_name):
    """
    Gets a role by name.

    :param role_name: The name of the role to retrieve.
    :return: The specified role.
    """
    try:
        role = iam.Role(role_name)
        role.load()  # calls GetRole to load attributes
        logger.info("Got role with arn %s.", role.arn)
    except ClientError:
        logger.exception("Couldn't get role named %s.", role_name)
        raise
    else:
        return role
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [GetRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetRole)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Gets data about a role.
  #
  # @param name [String] The name of the role to look up.
  # @return [Aws::IAM::Role] The retrieved role.
  def get_role(name)
    role = @iam_client.get_role({
                                  role_name: name
                                }).role
    puts("Got data for role '#{role.role_name}'. Its ARN is '#{role.arn}'.")
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't get data for role '#{name}' Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    role
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [GetRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetRole)을 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn get_role(
    client: &iamClient,
    role_name: String,
) -> Result<GetRoleOutput, SdkError<GetRoleError>> {
    let response = client.get_role().role_name(role_name).send().await?;
    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [GetRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.get_role)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->getrole( iv_rolename = iv_role_name ).
        MESSAGE 'Retrieved role information.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [GetRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func getRole(name: String) async throws -> IAMClientTypes.Role {
        let input = GetRoleInput(
            roleName: name
        )
        do {
            let output = try await client.getRole(input: input)
            guard let role = output.role else {
                throw ServiceHandlerError.noSuchRole
            }
            return role
        } catch {
            print("ERROR: getRole:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [GetRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/getrole(input:))을 참조하세요.

------

# CLI로 `GetRolePolicy` 사용
<a name="iam_example_iam_GetRolePolicy_section"></a>

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

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

**AWS CLI**  
**IAM 역할에 연결된 정책에 대한 정보 가져오기**  
다음 `get-role-policy` 명령은 `Test-Role`이라는 역할에 연결된 지정된 정책에 대한 정보를 가져옵니다.  

```
aws iam get-role-policy \
    --role-name Test-Role \
    --policy-name ExamplePolicy
```
출력:  

```
{
  "RoleName": "Test-Role",
  "PolicyDocument": {
      "Statement": [
          {
              "Action": [
                  "s3:ListBucket",
                  "s3:Put*",
                  "s3:Get*",
                  "s3:*MultipartUpload*"
              ],
              "Resource": "*",
              "Effect": "Allow",
              "Sid": "1"
          }
      ]
  }
  "PolicyName": "ExamplePolicy"
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-role-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 역할 `lamda_exec_role`에 포함된 `oneClick_lambda_exec_role_policy`라는 정책에 대한 권한 정책 문서를 반환합니다. 결과 정책 문서는 URL로 인코딩됩니다. 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다.**  

```
$results = Get-IAMRolePolicy -RoleName lambda_exec_role -PolicyName oneClick_lambda_exec_role_policy
$results
```
**출력:**  

```
PolicyDocument                                            PolicyName                           UserName
--------------                                            ----------                           --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    oneClick_lambda_exec_role_policy     lambda_exec_role
```

```
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
```
**출력:**  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:*"
      ],
      "Resource": "arn:aws:logs:us-east-1:555555555555:log-group:/aws/lambda/aws-example-function:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/*"
      ]
    }
  ]
}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 역할 `lamda_exec_role`에 포함된 `oneClick_lambda_exec_role_policy`라는 정책에 대한 권한 정책 문서를 반환합니다. 결과 정책 문서는 URL로 인코딩됩니다. 이 예제에서는 `UrlDecode` .NET 메서드를 사용하여 디코딩됩니다.**  

```
$results = Get-IAMRolePolicy -RoleName lambda_exec_role -PolicyName oneClick_lambda_exec_role_policy
$results
```
**출력:**  

```
PolicyDocument                                            PolicyName                           UserName
--------------                                            ----------                           --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    oneClick_lambda_exec_role_policy     lambda_exec_role
```

```
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
```
**출력:**  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:*"
      ],
      "Resource": "arn:aws:logs:us-east-1:555555555555:log-group:/aws/lambda/aws-example-function:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/*"
      ]
    }
  ]
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetSamlProvider` 사용
<a name="iam_example_iam_GetSamlProvider_section"></a>

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

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

**AWS CLI**  
**SAML 제공업체 메타문서 검색**  
이 예제는 ARM이 `arn:aws:iam::123456789012:saml-provider/SAMLADFS`인 SAML 2.0 제공업체에 대한 세부 정보를 검색합니다. 응답에는 AWS SAML 공급자 개체를 생성하기 위해 자격 증명 공급자로부터 받은 메타데이터 문서와 생성 및 만료 날짜가 포함됩니다.  

```
aws iam get-saml-provider \
    --saml-provider-arn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
출력:  

```
{
    "SAMLMetadataDocument": "...SAMLMetadataDocument-XML...",
    "CreateDate": "2017-03-06T22:29:46+00:00",
    "ValidUntil": "2117-03-06T22:29:46.433000+00:00",
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM SAML 자격 증명 공급자 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetSamlProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-saml-provider.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARM이 arn:aws:iam::123456789012:saml-provider/SAMLADFS인 SAML 2.0 제공업체에 대한 세부 정보를 검색합니다. 응답에는 AWS SAML 공급자 개체를 생성하기 위해 자격 증명 공급자로부터 받은 메타데이터 문서와 생성 및 만료 날짜가 포함됩니다.**  

```
Get-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
**출력:**  

```
CreateDate                 SAMLMetadataDocument                                          ValidUntil
----------                 --------------------                                          ----------
12/23/2014 12:16:55 PM    <EntityDescriptor ID="_12345678-1234-5678-9012-example1...    12/23/2114 12:16:54 PM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetSamlProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARM이 arn:aws:iam::123456789012:saml-provider/SAMLADFS인 SAML 2.0 제공업체에 대한 세부 정보를 검색합니다. 응답에는 AWS SAML 공급자 엔터티를 생성하기 위해 자격 증명 공급자로부터 받은 메타데이터 문서와 생성 및 만료 날짜가 포함됩니다.**  

```
Get-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
**출력:**  

```
CreateDate                 SAMLMetadataDocument                                          ValidUntil
----------                 --------------------                                          ----------
12/23/2014 12:16:55 PM    <EntityDescriptor ID="_12345678-1234-5678-9012-example1...    12/23/2114 12:16:54 PM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::getServerCertificate(const Aws::String &certificateName,
                                       const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::GetServerCertificateRequest request;
    request.SetServerCertificateName(certificateName);

    auto outcome = iam.GetServerCertificate(request);
    bool result = true;
    if (!outcome.IsSuccess()) {
        if (outcome.GetError().GetErrorType() != Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
            std::cerr << "Error getting server certificate " << certificateName <<
                      ": " << outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Certificate '" << certificateName
                      << "' not found." << std::endl;
        }
    }
    else {
        const auto &certificate = outcome.GetResult().GetServerCertificate();
        std::cout << "Name: " <<
                  certificate.GetServerCertificateMetadata().GetServerCertificateName()
                  << std::endl << "Body: " << certificate.GetCertificateBody() <<
                  std::endl << "Chain: " << certificate.GetCertificateChain() <<
                  std::endl;
    }

    return result;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [GetServerCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/GetServerCertificate)를 참조하세요.

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

**AWS CLI**  
** AWS 계정의 서버 인증서에 대한 세부 정보를 가져오는 방법**  
다음 `get-server-certificate` 명령은 AWS 계정에서 지정된 서버 인증서에 대한 모든 세부 정보를 검색합니다.  

```
aws iam get-server-certificate \
    --server-certificate-name myUpdatedServerCertificate
```
출력:  

```
{
    "ServerCertificate": {
        "ServerCertificateMetadata": {
            "Path": "/",
            "ServerCertificateName": "myUpdatedServerCertificate",
            "ServerCertificateId": "ASCAEXAMPLE123EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:server-certificate/myUpdatedServerCertificate",
            "UploadDate": "2019-04-22T21:13:44+00:00",
            "Expiration": "2019-10-15T22:23:16+00:00"
        },
        "CertificateBody": "-----BEGIN CERTIFICATE-----
            MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
            VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
            b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
            BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
            MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
            VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
            b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
            YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
            21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
            rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
            Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
            nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
            FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
            NYiytVbZPQUQ5Yaxu2jXnimvrszlaEXAMPLE=-----END CERTIFICATE-----",
        "CertificateChain": "-----BEGIN CERTIFICATE-----\nMIICiTCCAfICCQD6md
            7oRw0uXOjANBgkqhkiG9w0BAqQUFADCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgT
            AldBMRAwDgYDVQQHEwdTZWF0drGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAs
            TC0lBTSBDb25zb2xlMRIwEAYDVsQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQ
            jb20wHhcNMTEwNDI1MjA0NTIxWhtcNMTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBh
            MCVVMxCzAJBgNVBAgTAldBMRAwDgsYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBb
            WF6b24xFDASBgNVBAsTC0lBTSBDb2d5zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMx
            HzAdBgkqhkiG9w0BCQEWEG5vb25lQGfFtYXpvbi5jb20wgZ8wDQYJKoZIhvcNAQE
            BBQADgY0AMIGJAoGBAMaK0dn+a4GmWIgWJ21uUSfwfEvySWtC2XADZ4nB+BLYgVI
            k60CpiwsZ3G93vUEIO3IyNoH/f0wYK8mh9TrDHudUZg3qX4waLG5M43q7Wgc/MbQ
            ITxOUSQv7c7ugFFDzQGBzZswY6786m86gjpEIbb3OhjZnzcvQAaRHhdlQWIMm2nr
            AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCku4nUhVVxYUntneD9+h8Mg9q6q+auN
            KyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0FlkbFFBjvSfpJIlJ00zbhNYS5f6Guo
            EDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjS;TbNYiytVbZPQUQ5Yaxu2jXnimvw
            3rrszlaEWEG5vb25lQGFtsYXpvbiEXAMPLE=\n-----END CERTIFICATE-----"
    }
}
```
 AWS 계정에서 사용할 수 있는 서버 인증서를 나열하려면 `list-server-certificates` 명령을 사용합니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM에서 서버 인증서 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-server-certificate.html)를 참조하세요.

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

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

```
import { GetServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} certName
 * @returns
 */
export const getServerCertificate = async (certName) => {
  const command = new GetServerCertificateCommand({
    ServerCertificateName: certName,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-getting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetServerCertificateCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.getServerCertificate(
  { ServerCertificateName: "CERTIFICATE_NAME" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-getting)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [GetServerCertificate](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/GetServerCertificate)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `MyServerCertificate`라는 서버 인증서에 대한 세부 정보를 검색합니다. `CertificateBody` 및 `ServerCertificateMetadata` 속성에서 인증서 세부 정보를 찾을 수 있습니다.**  

```
$result = Get-IAMServerCertificate -ServerCertificateName MyServerCertificate
$result | format-list
```
**출력:**  

```
CertificateBody           : -----BEGIN CERTIFICATE-----
                            MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                            VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                            b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                            BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                            MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                            VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                            b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                            YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                            21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                            rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                            Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                            nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                            FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                            NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                            -----END CERTIFICATE-----
CertificateChain          : 
ServerCertificateMetadata : Amazon.IdentityManagement.Model.ServerCertificateMetadata
```

```
$result.ServerCertificateMetadata
```
**출력:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `MyServerCertificate`라는 서버 인증서에 대한 세부 정보를 검색합니다. `CertificateBody` 및 `ServerCertificateMetadata` 속성에서 인증서 세부 정보를 찾을 수 있습니다.**  

```
$result = Get-IAMServerCertificate -ServerCertificateName MyServerCertificate
$result | format-list
```
**출력:**  

```
CertificateBody           : -----BEGIN CERTIFICATE-----
                            MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                            VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                            b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                            BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                            MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                            VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                            b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                            YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                            21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                            rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                            Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                            nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                            FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                            NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                            -----END CERTIFICATE-----
CertificateChain          : 
ServerCertificateMetadata : Amazon.IdentityManagement.Model.ServerCertificateMetadata
```

```
$result.ServerCertificateMetadata
```
**출력:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetServiceLastAccessedDetails` 사용
<a name="iam_example_iam_GetServiceLastAccessedDetails_section"></a>

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

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

**AWS CLI**  
**서비스 액세스 보고서 검색**  
다음 `get-service-last-accessed-details` 예제는 IAM 엔터티가 액세스한 서비스를 나열하는 이전에 생성된 보고서를 검색합니다. 보고서를 생성하려면 `generate-service-last-accessed-details` 명령을 사용합니다.  

```
aws iam get-service-last-accessed-details \
    --job-id 2eb6c2b8-7b4c-3xmp-3c13-03b72c8cdfdc
```
출력:  

```
{
    "JobStatus": "COMPLETED",
    "JobCreationDate": "2019-10-01T03:50:35.929Z",
    "ServicesLastAccessed": [
        ...
        {
            "ServiceName": "AWS Lambda",
            "LastAuthenticated": "2019-09-30T23:02:00Z",
            "ServiceNamespace": "lambda",
            "LastAuthenticatedEntity": "arn:aws:iam::123456789012:user/admin",
            "TotalAuthenticatedEntities": 6
        },
    ]
}
```
자세한 내용은 *AWS IAM 사용 설명서*[의 마지막으로 액세스한 정보를 AWS 사용하여에서 권한 구체화를](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetServiceLastAccessedDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-service-last-accessed-details.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예에서는 요청 직접 호출과 연결된 IAM 엔터티(사용자, 그룹, 역할 또는 정책)가 마지막으로 액세스한 서비스에 대한 세부 정보를 제공합니다.**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
**출력:**  

```
f0b7a819-eab0-929b-dc26-ca598911cb9f
```

```
Get-IAMServiceLastAccessedDetail -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예에서는 요청 직접 호출과 연결된 IAM 엔터티(사용자, 그룹, 역할 또는 정책)가 마지막으로 액세스한 서비스에 대한 세부 정보를 제공합니다.**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
**출력:**  

```
f0b7a819-eab0-929b-dc26-ca598911cb9f
```

```
Get-IAMServiceLastAccessedDetail -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `GetServiceLastAccessedDetailsWithEntities` 사용
<a name="iam_example_iam_GetServiceLastAccessedDetailsWithEntities_section"></a>

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

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

**AWS CLI**  
**서비스 세부 정보가 포함된 서비스 액세스 보고서 검색**  
다음 `get-service-last-accessed-details-with-entities` 예제는 지정된 서비스에 액세스한 IAM 사용자와 기타 엔터티에 대한 세부 정보가 포함된 보고서를 검색합니다. 보고서를 생성하려면 `generate-service-last-accessed-details` 명령을 사용합니다. 네임스페이스로 액세스하는 서비스 목록을 가져오려면 `get-service-last-accessed-details`를 사용합니다.  

```
aws iam get-service-last-accessed-details-with-entities \
    --job-id 78b6c2ba-d09e-6xmp-7039-ecde30b26916 \
    --service-namespace lambda
```
출력:  

```
{
    "JobStatus": "COMPLETED",
    "JobCreationDate": "2019-10-01T03:55:41.756Z",
    "JobCompletionDate": "2019-10-01T03:55:42.533Z",
    "EntityDetailsList": [
        {
            "EntityInfo": {
                "Arn": "arn:aws:iam::123456789012:user/admin",
                "Name": "admin",
                "Type": "USER",
                "Id": "AIDAIO2XMPLENQEXAMPLE",
                "Path": "/"
            },
            "LastAuthenticated": "2019-09-30T23:02:00Z"
        },
        {
            "EntityInfo": {
                "Arn": "arn:aws:iam::123456789012:user/developer",
                "Name": "developer",
                "Type": "USER",
                "Id": "AIDAIBEYXMPL2YEXAMPLE",
                "Path": "/"
            },
            "LastAuthenticated": "2019-09-16T19:34:00Z"
        }
    ]
}
```
자세한 내용은 *AWS IAM 사용 설명서*[의 마지막으로 액세스한 정보를 AWS 사용하여에서 권한 구체화를](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetServiceLastAccessedDetailsWithEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-service-last-accessed-details-with-entities.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 해당 IAM 엔터티의 요청에 있는 서비스에 대해 마지막으로 액세스한 타임스탬프를 제공합니다.**  

```
$results = Get-IAMServiceLastAccessedDetailWithEntity -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f -ServiceNamespace ec2
$results
```
**출력:**  

```
EntityDetailsList : {Amazon.IdentityManagement.Model.EntityDetails}
Error             : 
IsTruncated       : False
JobCompletionDate : 12/29/19 11:19:31 AM
JobCreationDate   : 12/29/19 11:19:31 AM
JobStatus         : COMPLETED
Marker            :
```

```
$results.EntityDetailsList
```
**출력:**  

```
EntityInfo                                 LastAuthenticated
----------                                 -----------------
Amazon.IdentityManagement.Model.EntityInfo 11/16/19 3:47:00 PM
```

```
$results.EntityInfo
```
**출력:**  

```
Arn  : arn:aws:iam::123456789012:user/TestUser
Id   : AIDA4NBK5CXF5TZHU1234
Name : TestUser
Path : /
Type : USER
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetServiceLastAccessedDetailsWithEntities](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 해당 IAM 엔터티의 요청에 있는 서비스에 대해 마지막으로 액세스한 타임스탬프를 제공합니다.**  

```
$results = Get-IAMServiceLastAccessedDetailWithEntity -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f -ServiceNamespace ec2
$results
```
**출력:**  

```
EntityDetailsList : {Amazon.IdentityManagement.Model.EntityDetails}
Error             : 
IsTruncated       : False
JobCompletionDate : 12/29/19 11:19:31 AM
JobCreationDate   : 12/29/19 11:19:31 AM
JobStatus         : COMPLETED
Marker            :
```

```
$results.EntityDetailsList
```
**출력:**  

```
EntityInfo                                 LastAuthenticated
----------                                 -----------------
Amazon.IdentityManagement.Model.EntityInfo 11/16/19 3:47:00 PM
```

```
$results.EntityInfo
```
**출력:**  

```
Arn  : arn:aws:iam::123456789012:user/TestUser
Id   : AIDA4NBK5CXF5TZHU1234
Name : TestUser
Path : /
Type : USER
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetServiceLastAccessedDetailsWithEntities](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

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

**AWS CLI**  
**서비스 연결 역할 삭제 요청 상태 확인**  
다음 `get-service-linked-role-deletion-status` 예제에서는 이전 서비스 연결 역할 삭제 요청의 상태를 표시합니다. 삭제 작업은 비동기식으로 이루어집니다. 요청을 하면 이 명령의 파라미터로 제공하는 `DeletionTaskId` 값을 가져옵니다.  

```
aws iam get-service-linked-role-deletion-status \
    --deletion-task-id task/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots/1a2b3c4d-1234-abcd-7890-abcdeEXAMPLE
```
출력:  

```
{
"Status": "SUCCEEDED"
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [서비스 연결 역할 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetServiceLinkedRoleDeletionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-service-linked-role-deletion-status.html)를 참조하세요.

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

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

```
import {
  GetServiceLinkedRoleDeletionStatusCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} deletionTaskId
 */
export const getServiceLinkedRoleDeletionStatus = (deletionTaskId) => {
  const command = new GetServiceLinkedRoleDeletionStatusCommand({
    DeletionTaskId: deletionTaskId,
  });

  return client.send(command);
};
```
+  API 세부 정보는AWS SDK for JavaScript API 참조의 [GetServiceLinkedRoleDeletionStatus](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetServiceLinkedRoleDeletionStatusCommand)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Get information about an IAM user.
    /// </summary>
    /// <param name="userName">The username of the user.</param>
    /// <returns>An IAM user object.</returns>
    public async Task<User> GetUserAsync(string userName)
    {
        var response = await _IAMService.GetUserAsync(new GetUserRequest { UserName = userName });
        return response.User;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [GetUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetUser)을 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_user_exists
#
# This function checks to see if the specified AWS Identity and Access Management (IAM) user already exists.
#
# Parameters:
#       $1 - The name of the IAM user to check.
#
# Returns:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_user_exists() {
  local user_name
  user_name=$1

  # Check whether the IAM user already exists.
  # We suppress all output - we're interested only in the return code.

  local errors
  errors=$(aws iam get-user \
    --user-name "$user_name" 2>&1 >/dev/null)

  local error_code=${?}

  if [[ $error_code -eq 0 ]]; then
    return 0 # 0 in Bash script means true.
  else
    if [[ $errors != *"error"*"(NoSuchEntity)"* ]]; then
      aws_cli_error_log $error_code
      errecho "Error calling iam get-user $errors"
    fi

    return 1 # 1 in Bash script means false.
  fi
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/GetUser)를 참조하세요.

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

**AWS CLI**  
**IAM 사용자 정보 가져오기**  
다음 `get-user` 명령은 이름이 `Paulo`인 IAM 사용자에 대한 정보를 가져옵니다.  

```
aws iam get-user \
    --user-name Paulo
```
출력:  

```
{
    "User": {
        "UserName": "Paulo",
        "Path": "/",
        "CreateDate": "2019-09-21T23:03:13Z",
        "UserId": "AIDA123456789EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:user/Paulo"
    }
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI  명령 참조의 [GetUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-user.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// GetUser gets data about a user.
func (wrapper UserWrapper) GetUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.GetUser(ctx, &iam.GetUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NoSuchEntityException:
				log.Printf("User %v does not exist.\n", userName)
				err = nil
			default:
				log.Printf("Couldn't get user %v. Here's why: %v\n", userName, err)
			}
		}
	} else {
		user = result.User
	}
	return user, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [GetUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetUser)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `David`라는 사용자에 대한 세부 정보를 검색합니다.**  

```
Get-IAMUser -UserName David
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE1
UserName         : David
```
**예제 2: 이 예제는 현재 로그인한 IAM 사용자에 대한 세부 정보를 검색합니다.**  

```
Get-IAMUser
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 10/16/2014 9:03:09 AM
PasswordLastUsed : 3/4/2015 12:12:33 PM
Path             : /
UserId           : 7K3GJEANSKZF2EXAMPLE2
UserName         : Bob
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetUser](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `David`라는 사용자에 대한 세부 정보를 검색합니다.**  

```
Get-IAMUser -UserName David
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE1
UserName         : David
```
**예제 2: 이 예제는 현재 로그인한 IAM 사용자에 대한 세부 정보를 검색합니다.**  

```
Get-IAMUser
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 10/16/2014 9:03:09 AM
PasswordLastUsed : 3/4/2015 12:12:33 PM
Path             : /
UserId           : 7K3GJEANSKZF2EXAMPLE2
UserName         : Bob
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetUser](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Ruby ]

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

```
  # Retrieves a user's details
  #
  # @param user_name [String] The name of the user to retrieve
  # @return [Aws::IAM::Types::User, nil] The user object if found, or nil if an error occurred
  def get_user(user_name)
    response = @iam_client.get_user(user_name: user_name)
    response.user
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("User '#{user_name}' not found.")
    nil
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error retrieving user '#{user_name}': #{e.message}")
    nil
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [GetUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetUser)을 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func getUser(name: String? = nil) async throws -> IAMClientTypes.User {
        let input = GetUserInput(
            userName: name
        )
        do {
            let output = try await iamClient.getUser(input: input)
            guard let user = output.user else {
                throw ServiceHandlerError.noSuchUser
            }
            return user
        } catch {
            print("ERROR: getUser:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [GetUser](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/getuser(input:))를 참조하세요.

------

# CLI로 `GetUserPolicy` 사용
<a name="iam_example_iam_GetUserPolicy_section"></a>

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

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

**AWS CLI**  
**IAM 사용자에 대한 정책 세부 정보 나열**  
다음 `get-user-policy` 명령은 이름이 `Bob`인 IAM 사용자에게 연결된 지정된 정책의 세부 정보를 나열합니다.  

```
aws iam get-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy
```
출력:  

```
{
    "UserName": "Bob",
    "PolicyName": "ExamplePolicy",
    "PolicyDocument": {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Action": "*",
                "Resource": "*",
                "Effect": "Allow"
            }
        ]
    }
}
```
IAM 사용자의 정책 목록을 가져오려면 `list-user-policies` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*에서 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [GetUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-user-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `David`라는 IAM 사용자에게 포함된 `Davids_IAM_Admin_Policy`라는 인라인 정책의 세부 정보를 검색합니다. 정책 문서는 URL로 인코딩됩니다.**  

```
$results = Get-IAMUserPolicy -PolicyName Davids_IAM_Admin_Policy -UserName David
$results
```
**출력:**  

```
PolicyDocument                                            PolicyName                    UserName
--------------                                            ----------                    --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    Davids_IAM_Admin_Policy       David

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:GetUser",
        "iam:ListUsers"
      ],
      "Resource": [
        "arn:aws:iam::111122223333:user/*"
      ]
    }
  ]
}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [GetUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `David`라는 IAM 사용자에게 포함된 `Davids_IAM_Admin_Policy`라는 인라인 정책의 세부 정보를 검색합니다. 정책 문서는 URL로 인코딩됩니다.**  

```
$results = Get-IAMUserPolicy -PolicyName Davids_IAM_Admin_Policy -UserName David
$results
```
**출력:**  

```
PolicyDocument                                            PolicyName                    UserName
--------------                                            ----------                    --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    Davids_IAM_Admin_Policy       David

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:GetUser",
        "iam:ListUsers"
      ],
      "Resource": [
        "arn:aws:iam::111122223333:user/*"
      ]
    }
  ]
}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [GetUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [ 액세스 키 관리](iam_example_iam_Scenario_ManageAccessKeys_section.md) 

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_list_access_keys
#
# This function lists the access keys for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#
# Returns:
#       access_key_ids
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_list_access_keys() {

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_list_access_keys"
    echo "Lists the AWS Identity and Access Management (IAM) access key IDs for the specified user."
    echo "  -u user_name   The name of the IAM user."
    echo ""
  }

  local user_name response
  local option OPTARG # Required to use getopts command in a function.
  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam list-access-keys \
    --user-name "$user_name" \
    --output text \
    --query 'AccessKeyMetadata[].AccessKeyId')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports list-access-keys operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API 세부 정보는  **AWS CLI 명령 참조의 [ListAccessKeys](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/ListAccessKeys)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::listAccessKeys(const Aws::String &userName,
                                 const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListAccessKeysRequest request;
    request.SetUserName(userName);

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListAccessKeys(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list access keys for user " << userName
                      << ": " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(32) << "UserName" <<
                      std::setw(30) << "KeyID" << std::setw(20) << "Status" <<
                      std::setw(20) << "CreateDate" << std::endl;
            header = true;
        }

        const auto &keys = outcome.GetResult().GetAccessKeyMetadata();
        const Aws::String DATE_FORMAT = "%Y-%m-%d";

        for (const auto &key: keys) {
            Aws::String statusString =
                    Aws::IAM::Model::StatusTypeMapper::GetNameForStatusType(
                            key.GetStatus());
            std::cout << std::left << std::setw(32) << key.GetUserName() <<
                      std::setw(30) << key.GetAccessKeyId() << std::setw(20) <<
                      statusString << std::setw(20) <<
                      key.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) << std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [ListAccessKeys](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListAccessKeys)를 참조하세요.

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

**AWS CLI**  
**IAM 사용자의 액세스 키 ID 나열**  
다음 `list-access-keys` 명령은 이름이 `Bob`인 IAM 사용자의 액세스 키 ID를 나열합니다.  

```
aws iam list-access-keys \
    --user-name Bob
```
출력:  

```
{
    "AccessKeyMetadata": [
        {
            "UserName": "Bob",
            "Status": "Active",
            "CreateDate": "2013-06-04T18:17:34Z",
            "AccessKeyId": "AKIAIOSFODNN7EXAMPLE"
        },
        {
            "UserName": "Bob",
            "Status": "Inactive",
            "CreateDate": "2013-06-06T20:42:26Z",
            "AccessKeyId": "AKIAI44QH8DHBEXAMPLE"
        }
    ]
}
```
IAM 사용자의 시크릿 액세스 키는 나열할 수 없습니다. 시크릿 액세스 키를 분실한 경우 `create-access-keys` 명령을 사용하여 새 액세스 키를 생성해야 합니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자의 액세스 키 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)를 참조하세요.  
+  API 세부 정보는  **AWS CLI 명령 참조의 [ListAccessKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-access-keys.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListAccessKeys lists the access keys for the specified user.
func (wrapper UserWrapper) ListAccessKeys(ctx context.Context, userName string) ([]types.AccessKeyMetadata, error) {
	var keys []types.AccessKeyMetadata
	result, err := wrapper.IamClient.ListAccessKeys(ctx, &iam.ListAccessKeysInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list access keys for user %v. Here's why: %v\n", userName, err)
	} else {
		keys = result.AccessKeyMetadata
	}
	return keys, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListAccessKeys](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListAccessKeys)를 참조하십시오.

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

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

```
import software.amazon.awssdk.services.iam.model.AccessKeyMetadata;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListAccessKeysRequest;
import software.amazon.awssdk.services.iam.model.ListAccessKeysResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;

/**
 * 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 ListAccessKeys {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <userName>\s

                Where:
                    userName - The name of the user for which access keys are retrieved.\s
                """;

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

        String userName = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listKeys(iam, userName);
        System.out.println("Done");
        iam.close();
    }

    public static void listKeys(IamClient iam, String userName) {
        try {
            boolean done = false;
            String newMarker = null;

            while (!done) {
                ListAccessKeysResponse response;

                if (newMarker == null) {
                    ListAccessKeysRequest request = ListAccessKeysRequest.builder()
                            .userName(userName)
                            .build();

                    response = iam.listAccessKeys(request);

                } else {
                    ListAccessKeysRequest request = ListAccessKeysRequest.builder()
                            .userName(userName)
                            .marker(newMarker)
                            .build();

                    response = iam.listAccessKeys(request);
                }

                for (AccessKeyMetadata metadata : response.accessKeyMetadata()) {
                    System.out.format("Retrieved access key %s", metadata.accessKeyId());
                }

                if (!response.isTruncated()) {
                    done = true;
                } else {
                    newMarker = response.marker();
                }
            }

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [ListAccessKeys](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListAccessKeys)를 참조하십시오.

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

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

```
import { ListAccessKeysCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 * @param {string} userName
 */
export async function* listAccessKeys(userName) {
  const command = new ListAccessKeysCommand({
    MaxItems: 5,
    UserName: userName,
  });

  /**
   * @type {import("@aws-sdk/client-iam").ListAccessKeysCommandOutput | undefined}
   */
  let response = await client.send(command);

  while (response?.AccessKeyMetadata?.length) {
    for (const key of response.AccessKeyMetadata) {
      yield key;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListAccessKeysCommand({
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-listing)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListAccessKeys](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListAccessKeysCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  MaxItems: 5,
  UserName: "IAM_USER_NAME",
};

iam.listAccessKeys(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iiam-examples-managing-access-keys-listing)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListAccessKeys](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListAccessKeys)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun listKeys(userNameVal: String?) {
    val request =
        ListAccessKeysRequest {
            userName = userNameVal
        }
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAccessKeys(request)
        response.accessKeyMetadata?.forEach { md ->
            println("Retrieved access key ${md.accessKeyId}")
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [ListAccessKeys](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 `Bob`이라는 IAM 사용자의 액세스 키를 나열합니다. IAM 사용자의 시크릿 액세스 키는 나열할 수 없습니다. 시크릿 액세스 키를 분실한 경우 `New-IAMAccessKey` cmdlet을 사용하여 새 액세스 키를 생성해야 합니다.**  

```
Get-IAMAccessKey -UserName "Bob"
```
**출력:**  

```
AccessKeyId                CreateDate                   Status              UserName
-----------                ----------                   ------              --------
AKIAIOSFODNN7EXAMPLE       12/3/2014 10:53:41 AM        Active              Bob
AKIAI44QH8DHBEXAMPLE       6/6/2013 8:42:26 PM          Inactive            Bob
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListAccessKeys](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 `Bob`이라는 IAM 사용자의 액세스 키를 나열합니다. IAM 사용자의 시크릿 액세스 키는 나열할 수 없습니다. 시크릿 액세스 키를 분실한 경우 `New-IAMAccessKey` cmdlet을 사용하여 새 액세스 키를 생성해야 합니다.**  

```
Get-IAMAccessKey -UserName "Bob"
```
**출력:**  

```
AccessKeyId                CreateDate                   Status              UserName
-----------                ----------                   ------              --------
AKIAIOSFODNN7EXAMPLE       12/3/2014 10:53:41 AM        Active              Bob
AKIAI44QH8DHBEXAMPLE       6/6/2013 8:42:26 PM          Inactive            Bob
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListAccessKeys](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_keys(user_name):
    """
    Lists the keys owned by the specified user.

    :param user_name: The name of the user.
    :return: The list of keys owned by the user.
    """
    try:
        keys = list(iam.User(user_name).access_keys.all())
        logger.info("Got %s access keys for %s.", len(keys), user_name)
    except ClientError:
        logger.exception("Couldn't get access keys for %s.", user_name)
        raise
    else:
        return keys
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListAccessKeys](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAccessKeys)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 액세스 키를 나열, 생성, 비활성화 및 삭제합니다.  

```
# Manages access keys for IAM users
class AccessKeyManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'AccessKeyManager'
  end

  # Lists access keys for a user
  #
  # @param user_name [String] The name of the user.
  def list_access_keys(user_name)
    response = @iam_client.list_access_keys(user_name: user_name)
    if response.access_key_metadata.empty?
      @logger.info("No access keys found for user '#{user_name}'.")
    else
      response.access_key_metadata.map(&:access_key_id)
    end
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Error listing access keys: cannot find user '#{user_name}'.")
    []
  rescue StandardError => e
    @logger.error("Error listing access keys: #{e.message}")
    []
  end

  # Creates an access key for a user
  #
  # @param user_name [String] The name of the user.
  # @return [Boolean]
  def create_access_key(user_name)
    response = @iam_client.create_access_key(user_name: user_name)
    access_key = response.access_key
    @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}")
    access_key
  rescue Aws::IAM::Errors::LimitExceeded
    @logger.error('Error creating access key: limit exceeded. Cannot create more.')
    nil
  rescue StandardError => e
    @logger.error("Error creating access key: #{e.message}")
    nil
  end

  # Deactivates an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def deactivate_access_key(user_name, access_key_id)
    @iam_client.update_access_key(
      user_name: user_name,
      access_key_id: access_key_id,
      status: 'Inactive'
    )
    true
  rescue StandardError => e
    @logger.error("Error deactivating access key: #{e.message}")
    false
  end

  # Deletes an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def delete_access_key(user_name, access_key_id)
    @iam_client.delete_access_key(
      user_name: user_name,
      access_key_id: access_key_id
    )
    true
  rescue StandardError => e
    @logger.error("Error deleting access key: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListAccessKeys](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListAccessKeys)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listaccesskeys(
          iv_username = iv_user_name ).
        MESSAGE 'Retrieved access key list.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListAccessKeys](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [계정 관리](iam_example_iam_Scenario_AccountManagement_section.md) 

------
#### [ C\$1\$1 ]

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

```
bool
AwsDoc::IAM::listAccountAliases(const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListAccountAliasesRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListAccountAliases(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list account aliases: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        const auto &aliases = outcome.GetResult().GetAccountAliases();
        if (!header) {
            if (aliases.size() == 0) {
                std::cout << "Account has no aliases" << std::endl;
                break;
            }
            std::cout << std::left << std::setw(32) << "Alias" << std::endl;
            header = true;
        }

        for (const auto &alias: aliases) {
            std::cout << std::left << std::setw(32) << alias << std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [ListAccountAliases](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListAccountAliases)를 참조하세요.

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

**AWS CLI**  
**계정 별칭 나열**  
다음 `list-account-aliases` 명령은 현재 계정의 별칭을 나열합니다.  

```
aws iam list-account-aliases
```
출력:  

```
{
    "AccountAliases": [
    "mycompany"
    ]
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [AWS 계정 ID 및 별칭](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListAccountAliases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-account-aliases.html)를 참조하세요.

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

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

```
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListAccountAliasesResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;

/**
 * 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 ListAccountAliases {
    public static void main(String[] args) {
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listAliases(iam);
        System.out.println("Done");
        iam.close();
    }

    public static void listAliases(IamClient iam) {
        try {
            ListAccountAliasesResponse response = iam.listAccountAliases();
            for (String alias : response.accountAliases()) {
                System.out.printf("Retrieved account alias %s", alias);
            }

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [ListAccountAliases](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListAccountAliases)를 참조하십시오.

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

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

```
import { ListAccountAliasesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 */
export async function* listAccountAliases() {
  const command = new ListAccountAliasesCommand({ MaxItems: 5 });

  let response = await client.send(command);

  while (response.AccountAliases?.length) {
    for (const alias of response.AccountAliases) {
      yield alias;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListAccountAliasesCommand({
          Marker: response.Marker,
          MaxItems: 5,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-listing)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListAccountAliases](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListAccountAliasesCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.listAccountAliases({ MaxItems: 10 }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-listing)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListAccountAliases](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListAccountAliases)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun listAliases() {
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAccountAliases(ListAccountAliasesRequest {})
        response.accountAliases?.forEach { alias ->
            println("Retrieved account alias $alias")
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [ListAccountAliases](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 AWS 계정에 대한 계정 별칭을 반환합니다.**  

```
Get-IAMAccountAlias
```
**출력:**  

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

**Tools for PowerShell V5**  
**예제 1: 이 명령은 AWS 계정에 대한 계정 별칭을 반환합니다.**  

```
Get-IAMAccountAlias
```
**출력:**  

```
ExampleCo
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListAccountAliases](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_aliases():
    """
    Gets the list of aliases for the current account. An account has at most one alias.

    :return: The list of aliases for the account.
    """
    try:
        response = iam.meta.client.list_account_aliases()
        aliases = response["AccountAliases"]
        if len(aliases) > 0:
            logger.info("Got aliases for your account: %s.", ",".join(aliases))
        else:
            logger.info("Got no aliases for your account.")
    except ClientError:
        logger.exception("Couldn't list aliases for your account.")
        raise
    else:
        return response["AccountAliases"]
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListAccountAliases](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAccountAliases)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
계정 별칭을 나열하고, 생성하고, 삭제합니다.  

```
class IAMAliasManager
  # Initializes the IAM client and logger
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists available AWS account aliases.
  def list_aliases
    response = @iam_client.list_account_aliases

    if response.account_aliases.count.positive?
      @logger.info('Account aliases are:')
      response.account_aliases.each { |account_alias| @logger.info("  #{account_alias}") }
    else
      @logger.info('No account aliases found.')
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing account aliases: #{e.message}")
  end

  # Creates an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to create.
  # @return [Boolean] true if the account alias was created; otherwise, false.
  def create_account_alias(account_alias)
    @iam_client.create_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating account alias: #{e.message}")
    false
  end

  # Deletes an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to delete.
  # @return [Boolean] true if the account alias was deleted; otherwise, false.
  def delete_account_alias(account_alias)
    @iam_client.delete_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting account alias: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListAccountAliases](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListAccountAliases)를 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listaccountaliases( ).
        MESSAGE 'Retrieved account alias list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing account aliases.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *SAP ABAP용AWS SDK API 참조*의 [ListAccountAliases](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

# CLI로 `ListAttachedGroupPolicies` 사용
<a name="iam_example_iam_ListAttachedGroupPolicies_section"></a>

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

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

**AWS CLI**  
**지정된 그룹에 연결된 모든 관리형 정책 나열**  
이 예제에서는 AWS 계정에서 라는 IAM 그룹에 연결된 관리형 정책의 이름과 ARNs`Admins`을 반환합니다.  

```
aws iam list-attached-group-policies \
    --group-name Admins
```
출력:  

```
{
    "AttachedPolicies": [
        {
            "PolicyName": "AdministratorAccess",
            "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
        },
        {
            "PolicyName": "SecurityAudit",
            "PolicyArn": "arn:aws:iam::aws:policy/SecurityAudit"
        }
    ],
    "IsTruncated": false
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListAttachedGroupPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-attached-group-policies.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 명령은 AWS 계정에서 라는 IAM 그룹에 연결된 관리형 정책의 이름과 ARNs`Admins`을 반환합니다. 그룹에 포함된 인라인 정책의 목록을 보려면 `Get-IAMGroupPolicyList` 명령을 사용합니다.**  

```
Get-IAMAttachedGroupPolicyList -GroupName "Admins"
```
**출력:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
arn:aws:iam::aws:policy/AdministratorAccess               AdministratorAccess
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListAttachedGroupPolicies](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 명령은 AWS 계정에서 라는 IAM 그룹에 연결된 관리형 정책의 이름과 ARNs`Admins`을 반환합니다. 그룹에 포함된 인라인 정책의 목록을 보려면 `Get-IAMGroupPolicyList` 명령을 사용합니다.**  

```
Get-IAMAttachedGroupPolicyList -GroupName "Admins"
```
**출력:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
arn:aws:iam::aws:policy/AdministratorAccess               AdministratorAccess
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListAttachedGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// List the IAM role policies that are attached to an IAM role.
    /// </summary>
    /// <param name="roleName">The IAM role to list IAM policies for.</param>
    /// <returns>A list of the IAM policies attached to the IAM role.</returns>
    public async Task<List<AttachedPolicyType>> ListAttachedRolePoliciesAsync(string roleName)
    {
        var attachedPolicies = new List<AttachedPolicyType>();
        var attachedRolePoliciesPaginator = _IAMService.Paginators.ListAttachedRolePolicies(new ListAttachedRolePoliciesRequest { RoleName = roleName });

        await foreach (var response in attachedRolePoliciesPaginator.Responses)
        {
            attachedPolicies.AddRange(response.AttachedPolicies);
        }

        return attachedPolicies;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListAttachedRolePolicies)를 참조하세요.

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

**AWS CLI**  
**지정된 IAM 역할에 연결된 모든 관리형 정책 나열**  
이 명령은 AWS 계정에서 라는 IAM 역할에 연결된 관리형 정책의 이름과 ARNs`SecurityAuditRole`을 반환합니다.  

```
aws iam list-attached-role-policies \
    --role-name SecurityAuditRole
```
출력:  

```
{
    "AttachedPolicies": [
        {
            "PolicyName": "SecurityAudit",
            "PolicyArn": "arn:aws:iam::aws:policy/SecurityAudit"
        }
    ],
    "IsTruncated": false
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListAttachedRolePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-attached-role-policies.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// ListAttachedRolePolicies lists the policies that are attached to the specified role.
func (wrapper RoleWrapper) ListAttachedRolePolicies(ctx context.Context, roleName string) ([]types.AttachedPolicy, error) {
	var policies []types.AttachedPolicy
	result, err := wrapper.IamClient.ListAttachedRolePolicies(ctx, &iam.ListAttachedRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list attached policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.AttachedPolicies
	}
	return policies, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListAttachedRolePolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListAttachedRolePolicies)를 참조하십시오.

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

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

```
import {
  ListAttachedRolePoliciesCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 * @param {string} roleName
 */
export async function* listAttachedRolePolicies(roleName) {
  const command = new ListAttachedRolePoliciesCommand({
    RoleName: roleName,
  });

  let response = await client.send(command);

  while (response.AttachedPolicies?.length) {
    for (const policy of response.AttachedPolicies) {
      yield policy;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListAttachedRolePoliciesCommand({
          RoleName: roleName,
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListAttachedRolePolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListAttachedRolePoliciesCommand)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function listAttachedRolePolicies($roleName, $pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listAttachRolePoliciesArguments = ['RoleName' => $roleName];
        if ($pathPrefix) {
            $listAttachRolePoliciesArguments['PathPrefix'] = $pathPrefix;
        }
        if ($marker) {
            $listAttachRolePoliciesArguments['Marker'] = $marker;
        }
        if ($maxItems) {
            $listAttachRolePoliciesArguments['MaxItems'] = $maxItems;
        }
        return $this->iamClient->listAttachedRolePolicies($listAttachRolePoliciesArguments);
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListAttachedRolePolicies)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 명령은 AWS 계정의 이름이 `SecurityAuditRole`인 IAM 역할에 연결된 관리형 정책의 이름과 ARN을 반환합니다. 역할에 포함된 인라인 정책의 목록을 보려면 `Get-IAMRolePolicyList` 명령을 사용합니다.**  

```
Get-IAMAttachedRolePolicyList -RoleName "SecurityAuditRole"
```
**출력:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [ListAttachedRolePolicies](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 명령은 AWS 계정의 이름이 `SecurityAuditRole`인 IAM 역할에 연결된 관리형 정책의 이름과 ARN을 반환합니다. 역할에 포함된 인라인 정책의 목록을 보려면 `Get-IAMRolePolicyList` 명령을 사용합니다.**  

```
Get-IAMAttachedRolePolicyList -RoleName "SecurityAuditRole"
```
**출력:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListAttachedRolePolicies](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_attached_policies(role_name):
    """
    Lists policies attached to a role.

    :param role_name: The name of the role to query.
    """
    try:
        role = iam.Role(role_name)
        for policy in role.attached_policies.all():
            logger.info("Got policy %s.", policy.arn)
    except ClientError:
        logger.exception("Couldn't list attached policies for %s.", role_name)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAttachedRolePolicies)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 역할 정책을 나열, 생성, 연결 및 분리합니다.  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListAttachedRolePolicies)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn list_attached_role_policies(
    client: &iamClient,
    role_name: String,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListAttachedRolePoliciesOutput, SdkError<ListAttachedRolePoliciesError>> {
    let response = client
        .list_attached_role_policies()
        .role_name(role_name)
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;

    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListAttachedRolePolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_attached_role_policies)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listattachedrolepolicies(
          iv_rolename = iv_role_name ).
        MESSAGE 'Retrieved attached policy list for role.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListAttachedRolePolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3



    /// Returns a list of AWS Identity and Access Management (IAM) policies
    /// that are attached to the role.
    ///
    /// - Parameter role: The IAM role to return the policy list for.
    ///
    /// - Returns: An array of `IAMClientTypes.AttachedPolicy` objects
    ///   describing each managed policy that's attached to the role.
    public func listAttachedRolePolicies(role: String) async throws -> [IAMClientTypes.AttachedPolicy] {
        var policyList: [IAMClientTypes.AttachedPolicy] = []

        // Use "Paginated" to get all the attached role polices.
        // This lets the SDK handle the 'isTruncated' in "ListAttachedRolePoliciesOutput".
        let input = ListAttachedRolePoliciesInput(
            roleName: role
        )
        let output = client.listAttachedRolePoliciesPaginated(input: input)

        do {
            for try await page in output {
                guard let attachedPolicies = page.attachedPolicies else {
                    print("Error: no attached policies returned.")
                    continue
                }
                for attachedPolicy in attachedPolicies {
                    policyList.append(attachedPolicy)
                }
            }
        } catch {
            print("ERROR: listAttachedRolePolicies:", dump(error))
            throw error
        }

        return policyList
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [ListAttachedRolePolicies](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listattachedrolepolicies(input:))를 참조하세요.

------

# CLI로 `ListAttachedUserPolicies` 사용
<a name="iam_example_iam_ListAttachedUserPolicies_section"></a>

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

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

**AWS CLI**  
**지정된 사용자에게 연결된 모든 관리형 정책 나열**  
이 명령은 AWS 계정에 이름이 지정된 IAM 사용자에 대한 관리형 정책의 이름과 ARNs`Bob`을 반환합니다.  

```
aws iam list-attached-user-policies \
    --user-name Bob
```
출력:  

```
{
    "AttachedPolicies": [
        {
            "PolicyName": "AdministratorAccess",
            "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
        },
        {
            "PolicyName": "SecurityAudit",
            "PolicyArn": "arn:aws:iam::aws:policy/SecurityAudit"
        }
    ],
    "IsTruncated": false
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListAttachedUserPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-attached-user-policies.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 명령은 AWS 계정에서 이름이 인 IAM 사용자`Bob`에 대한 관리형 정책의 이름과 ARNs을 반환합니다. IAM 사용자에게 포함된 인라인 정책의 목록을 보려면 `Get-IAMUserPolicyList` 명령을 사용합니다.**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**출력:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListAttachedUserPolicies](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 명령은 AWS 계정에 이름이 지정된 IAM 사용자의 관리형 정책의 이름과 ARNs`Bob`을 반환합니다. IAM 사용자에게 포함된 인라인 정책의 목록을 보려면 `Get-IAMUserPolicyList` 명령을 사용합니다.**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**출력:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListAttachedUserPolicies](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListEntitiesForPolicy` 사용
<a name="iam_example_iam_ListEntitiesForPolicy_section"></a>

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

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

**AWS CLI**  
**지정된 관리형 정책이 연결된 모든 사용자, 그룹 및 역할 나열**  
이 예제는 `arn:aws:iam::123456789012:policy/TestPolicy` 정책이 연결된 IAM 그룹, 역할 및 사용자 목록을 반환합니다.  

```
aws iam list-entities-for-policy \
    --policy-arn arn:aws:iam::123456789012:policy/TestPolicy
```
출력:  

```
{
    "PolicyGroups": [
        {
            "GroupName": "Admins",
            "GroupId": "AGPACKCEVSQ6C2EXAMPLE"
        }
    ],
    "PolicyUsers": [
        {
            "UserName": "Alice",
            "UserId": "AIDACKCEVSQ6C2EXAMPLE"
        }
    ],
    "PolicyRoles": [
        {
            "RoleName": "DevRole",
            "RoleId": "AROADBQP57FF2AEXAMPLE"
        }
    ],
    "IsTruncated": false
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListEntitiesForPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-entities-for-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `arn:aws:iam::123456789012:policy/TestPolicy` 정책이 연결된 IAM 그룹, 역할 및 사용자 목록을 반환합니다.**  

```
Get-IAMEntitiesForPolicy -PolicyArn "arn:aws:iam::123456789012:policy/TestPolicy"
```
**출력:**  

```
IsTruncated  : False
Marker       : 
PolicyGroups : {}
PolicyRoles  : {testRole}
PolicyUsers  : {Bob, Theresa}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListEntitiesForPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `arn:aws:iam::123456789012:policy/TestPolicy` 정책이 연결된 IAM 그룹, 역할 및 사용자 목록을 반환합니다.**  

```
Get-IAMEntitiesForPolicy -PolicyArn "arn:aws:iam::123456789012:policy/TestPolicy"
```
**출력:**  

```
IsTruncated  : False
Marker       : 
PolicyGroups : {}
PolicyRoles  : {testRole}
PolicyUsers  : {Bob, Theresa}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListEntitiesForPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListGroupPolicies` 사용
<a name="iam_example_iam_ListGroupPolicies_section"></a>

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

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

**AWS CLI**  
**지정된 그룹에 연결된 모든 인라인 정책 나열**  
다음 `list-group-policies` 명령은 현재 계정에서 `Admins`라는 IAM 그룹에 연결된 인라인 정책의 이름을 나열합니다.  

```
aws iam list-group-policies \
    --group-name Admins
```
출력:  

```
{
    "PolicyNames": [
        "AdminRoot",
        "ExamplePolicy"
    ]
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 정책 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListGroupPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-group-policies.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 그룹 `Testers`에 포함된 인라인 정책의 목록을 반환합니다. 그룹에 연결된 관리형 정책을 가져오려면 `Get-IAMAttachedGroupPolicyList` 명령을 사용합니다.**  

```
Get-IAMGroupPolicyList -GroupName Testers
```
**출력:**  

```
Deny-Assume-S3-Role-In-Production
PowerUserAccess-Testers
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListGroupPolicies](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 그룹 `Testers`에 포함된 인라인 정책의 목록을 반환합니다. 그룹에 연결된 관리형 정책을 가져오려면 `Get-IAMAttachedGroupPolicyList` 명령을 사용합니다.**  

```
Get-IAMGroupPolicyList -GroupName Testers
```
**출력:**  

```
Deny-Assume-S3-Role-In-Production
PowerUserAccess-Testers
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// List IAM groups.
    /// </summary>
    /// <returns>A list of IAM groups.</returns>
    public async Task<List<Group>> ListGroupsAsync()
    {
        var groupsPaginator = _IAMService.Paginators.ListGroups(new ListGroupsRequest());
        var groups = new List<Group>();

        await foreach (var response in groupsPaginator.Responses)
        {
            groups.AddRange(response.Groups);
        }

        return groups;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListGroups)를 참조하세요.

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

**AWS CLI**  
**현재 계정의 IAM 그룹 나열**  
다음 `list-groups` 명령은 현재 계정의 IAM 그룹을 나열합니다.  

```
aws iam list-groups
```
출력:  

```
{
    "Groups": [
        {
            "Path": "/",
            "CreateDate": "2013-06-04T20:27:27.972Z",
            "GroupId": "AIDACKCEVSQ6C2EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/Admins",
            "GroupName": "Admins"
        },
        {
            "Path": "/",
            "CreateDate": "2013-04-16T20:30:42Z",
            "GroupId": "AIDGPMS9RO4H3FEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/S3-Admins",
            "GroupName": "S3-Admins"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 그룹 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-groups.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// GroupWrapper encapsulates AWS Identity and Access Management (IAM) group actions
// used in the examples.
// It contains an IAM service client that is used to perform group actions.
type GroupWrapper struct {
	IamClient *iam.Client
}



// ListGroups lists up to maxGroups number of groups.
func (wrapper GroupWrapper) ListGroups(ctx context.Context, maxGroups int32) ([]types.Group, error) {
	var groups []types.Group
	result, err := wrapper.IamClient.ListGroups(ctx, &iam.ListGroupsInput{
		MaxItems: aws.Int32(maxGroups),
	})
	if err != nil {
		log.Printf("Couldn't list groups. Here's why: %v\n", err)
	} else {
		groups = result.Groups
	}
	return groups, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListGroups](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListGroups)를 참조하십시오.

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

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

```
import { ListGroupsCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 */
export async function* listGroups() {
  const command = new ListGroupsCommand({
    MaxItems: 10,
  });

  let response = await client.send(command);

  while (response.Groups?.length) {
    for (const group of response.Groups) {
      yield group;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListGroupsCommand({
          Marker: response.Marker,
          MaxItems: 10,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListGroupsCommand)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function listGroups($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listGroupsArguments = [];
        if ($pathPrefix) {
            $listGroupsArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listGroupsArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listGroupsArguments["MaxItems"] = $maxItems;
        }

        return $this->iamClient->listGroups($listGroupsArguments);
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [ListGroups](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListGroups)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제는 현재에 정의된 모든 IAM 그룹의 모음을 반환합니다 AWS 계정.**  

```
Get-IAMGroupList
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /

Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE2
GroupName  : Developers
Path       : /

Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE3
GroupName  : Testers
Path       : /
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListGroups](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제는 현재에 정의된 모든 IAM 그룹의 모음을 반환합니다 AWS 계정.**  

```
Get-IAMGroupList
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /

Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE2
GroupName  : Developers
Path       : /

Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE3
GroupName  : Testers
Path       : /
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListGroups](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_groups(count):
    """
    Lists the specified number of groups for the account.

    :param count: The number of groups to list.
    """
    try:
        for group in iam.groups.limit(count):
            logger.info("Group: %s", group.name)
    except ClientError:
        logger.exception("Couldn't list groups for the account.")
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListGroups](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListGroups)를 참조하십시오.

------
#### [ Ruby ]

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

```
# A class to manage IAM operations via the AWS SDK client
class IamGroupManager
  # Initializes the IamGroupManager class
  # @param iam_client [Aws::IAM::Client] An instance of the IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists up to a specified number of groups for the account.
  # @param count [Integer] The maximum number of groups to list.
  # @return [Aws::IAM::Client::Response]
  def list_groups(count)
    response = @iam_client.list_groups(max_items: count)
    response.groups.each do |group|
      @logger.info("\t#{group.group_name}")
    end
    response
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't list groups for the account. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListGroups](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListGroups)를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn list_groups(
    client: &iamClient,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListGroupsOutput, SdkError<ListGroupsError>> {
    let response = client
        .list_groups()
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;

    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListGroups](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_groups)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listgroups( ).
        MESSAGE 'Retrieved group list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing groups.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는AWS *SDK for SAP ABAP API*의 [ListGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)르 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func listGroups() async throws -> [String] {
        var groupList: [String] = []

        // Use "Paginated" to get all the groups.
        // This lets the SDK handle the 'isTruncated' property in "ListGroupsOutput".
        let input = ListGroupsInput()

        let pages = client.listGroupsPaginated(input: input)
        do {
            for try await page in pages {
                guard let groups = page.groups else {
                    print("Error: no groups returned.")
                    continue
                }

                for group in groups {
                    if let name = group.groupName {
                        groupList.append(name)
                    }
                }
            }
        } catch {
            print("ERROR: listGroups:", dump(error))
            throw error
        }
        return groupList
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [ListGroups](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listgroups(input:))을 참조하세요.

------

# CLI로 `ListGroupsForUser` 사용
<a name="iam_example_iam_ListGroupsForUser_section"></a>

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

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

**AWS CLI**  
**IAM 사용자가 속한 그룹 나열**  
다음 `list-groups-for-user` 명령은 `Bob`이라는 IAM 사용자가 속한 그룹을 표시합니다.  

```
aws iam list-groups-for-user \
    --user-name Bob
```
출력:  

```
{
    "Groups": [
        {
            "Path": "/",
            "CreateDate": "2013-05-06T01:18:08Z",
            "GroupId": "AKIAIOSFODNN7EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/Admin",
            "GroupName": "Admin"
        },
        {
            "Path": "/",
            "CreateDate": "2013-05-06T01:37:28Z",
            "GroupId": "AKIAI44QH8DHBEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/s3-Users",
            "GroupName": "s3-Users"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 그룹 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListGroupsForUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-groups-for-user.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 사용자 `David`가 속한 IAM 그룹 목록을 반환합니다.**  

```
Get-IAMGroupForUser -UserName David
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE2
GroupName  : Testers
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE3
GroupName  : Developers
Path       : /
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListGroupsForUser](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 사용자 `David`가 속한 IAM 그룹 목록을 반환합니다.**  

```
Get-IAMGroupForUser -UserName David
```
**출력:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE2
GroupName  : Testers
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE3
GroupName  : Developers
Path       : /
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListGroupsForUser](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListInstanceProfiles` 사용
<a name="iam_example_iam_ListInstanceProfiles_section"></a>

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

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

**AWS CLI**  
**계정의 인스턴스 프로파일 나열**  
다음 `list-instance-profiles` 명령은 현재 계정과 연결된 인스턴스 프로파일을 나열합니다.  

```
aws iam list-instance-profiles
```
출력:  

```
{
    "InstanceProfiles": [
        {
            "Path": "/",
            "InstanceProfileName": "example-dev-role",
            "InstanceProfileId": "AIPAIXEU4NUHUPEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:instance-profile/example-dev-role",
            "CreateDate": "2023-09-21T18:17:41+00:00",
            "Roles": [
                {
                    "Path": "/",
                    "RoleName": "example-dev-role",
                    "RoleId": "AROAJ52OTH4H7LEXAMPLE",
                    "Arn": "arn:aws:iam::123456789012:role/example-dev-role",
                    "CreateDate": "2023-09-21T18:17:40+00:00",
                    "AssumeRolePolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": "ec2.amazonaws.com"
                                },
                                "Action": "sts:AssumeRole"
                            }
                        ]
                    }
                }
            ]
        },
        {
            "Path": "/",
            "InstanceProfileName": "example-s3-role",
            "InstanceProfileId": "AIPAJVJVNRIQFREXAMPLE",
            "Arn": "arn:aws:iam::123456789012:instance-profile/example-s3-role",
            "CreateDate": "2023-09-21T18:18:50+00:00",
            "Roles": [
                {
                    "Path": "/",
                    "RoleName": "example-s3-role",
                    "RoleId": "AROAINUBC5O7XLEXAMPLE",
                    "Arn": "arn:aws:iam::123456789012:role/example-s3-role",
                    "CreateDate": "2023-09-21T18:18:49+00:00",
                    "AssumeRolePolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": "ec2.amazonaws.com"
                                },
                                "Action": "sts:AssumeRole"
                            }
                        ]
                    }
                }
            ]
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [인스턴스 프로파일 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListInstanceProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-instance-profiles.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제는 현재에 정의된 인스턴스 프로파일의 컬렉션을 반환합니다 AWS 계정.**  

```
Get-IAMInstanceProfileList
```
**출력:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListInstanceProfiles](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제는 현재에 정의된 인스턴스 프로파일의 컬렉션을 반환합니다 AWS 계정.**  

```
Get-IAMInstanceProfileList
```
**출력:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListInstanceProfiles](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListInstanceProfilesForRole` 사용
<a name="iam_example_iam_ListInstanceProfilesForRole_section"></a>

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

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

**AWS CLI**  
**IAM 역할에 대한 인스턴스 프로파일 나열**  
다음 `list-instance-profiles-for-role` 명령은 `Test-Role` 역할과 연결된 인스턴스 프로파일을 나열합니다.  

```
aws iam list-instance-profiles-for-role \
    --role-name Test-Role
```
출력:  

```
{
    "InstanceProfiles": [
        {
            "InstanceProfileId": "AIDGPMS9RO4H3FEXAMPLE",
            "Roles": [
                {
                    "AssumeRolePolicyDocument": "<URL-encoded-JSON>",
                    "RoleId": "AIDACKCEVSQ6C2EXAMPLE",
                    "CreateDate": "2013-06-07T20:42:15Z",
                    "RoleName": "Test-Role",
                    "Path": "/",
                    "Arn": "arn:aws:iam::123456789012:role/Test-Role"
                }
            ],
            "CreateDate": "2013-06-07T21:05:24Z",
            "InstanceProfileName": "ExampleInstanceProfile",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:instance-profile/ExampleInstanceProfile"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [인스턴스 프로파일 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListInstanceProfilesForRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-instance-profiles-for-role.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `ec2instancerole` 역할과 연결된 인스턴스 프로파일의 세부 정보를 반환합니다.**  

```
Get-IAMInstanceProfileForRole -RoleName ec2instancerole
```
**출력:**  

```
      Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
      CreateDate          : 2/17/2015 2:49:04 PM
      InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
      InstanceProfileName : ec2instancerole
      Path                : /
      Roles               : {ec2instancerole}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListInstanceProfilesForRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `ec2instancerole` 역할과 연결된 인스턴스 프로파일의 세부 정보를 반환합니다.**  

```
Get-IAMInstanceProfileForRole -RoleName ec2instancerole
```
**출력:**  

```
      Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
      CreateDate          : 2/17/2015 2:49:04 PM
      InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
      InstanceProfileName : ec2instancerole
      Path                : /
      Roles               : {ec2instancerole}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListInstanceProfilesForRole](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `ListMfaDevices` 사용
<a name="iam_example_iam_ListMfaDevices_section"></a>

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

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

**AWS CLI**  
**지정된 사용자의 모든 MFA 디바이스 나열**  
이 예제는 IAM 사용자 `Bob`에게 할당된 MFA 디바이스에 대한 세부 정보를 반환합니다.  

```
aws iam list-mfa-devices \
    --user-name Bob
```
출력:  

```
{
    "MFADevices": [
        {
            "UserName": "Bob",
            "SerialNumber": "arn:aws:iam::123456789012:mfa/Bob",
            "EnableDate": "2019-10-28T20:37:09+00:00"
        },
        {
            "UserName": "Bob",
            "SerialNumber": "GAKT12345678",
            "EnableDate": "2023-02-18T21:44:42+00:00"
        },
        {
            "UserName": "Bob",
            "SerialNumber": "arn:aws:iam::123456789012:u2f/user/Bob/fidosecuritykey1-7XNL7NFNLZ123456789EXAMPLE",
            "EnableDate": "2023-09-19T02:25:35+00:00"
        },
        {
            "UserName": "Bob",
            "SerialNumber": "arn:aws:iam::123456789012:u2f/user/Bob/fidosecuritykey2-VDRQTDBBN5123456789EXAMPLE",
            "EnableDate": "2023-09-19T01:49:18+00:00"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [AWS에서 다중 인증(MFA) 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListMfaDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-mfa-devices.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 사용자 `David`에게 할당된 MFA 디바이스에 대한 세부 정보를 반환합니다. 이 예제에서는 `SerialNumber`가 물리적 디바이스의 실제 일련 번호가 아닌 ARN이므로 가상 장치임을 알 수 있습니다.**  

```
Get-IAMMFADevice -UserName David
```
**출력:**  

```
EnableDate                  SerialNumber                           UserName
----------                  ------------                           --------
4/8/2015 9:41:10 AM         arn:aws:iam::123456789012:mfa/David    David
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListMfaDevices](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 사용자 `David`에게 할당된 MFA 디바이스에 대한 세부 정보를 반환합니다. 이 예제에서는 `SerialNumber`가 물리적 디바이스의 실제 일련 번호가 아닌 ARN이므로 가상 장치임을 알 수 있습니다.**  

```
Get-IAMMFADevice -UserName David
```
**출력:**  

```
EnableDate                  SerialNumber                           UserName
----------                  ------------                           --------
4/8/2015 9:41:10 AM         arn:aws:iam::123456789012:mfa/David    David
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `ListOpenIdConnectProviders` 사용
<a name="iam_example_iam_ListOpenIdConnectProviders_section"></a>

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

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

**AWS CLI**  
** AWS 계정의 OpenID Connect 공급자에 대한 정보를 나열하려면**  
이 예제에서는 현재 AWS 계정에 정의된 모든 OpenID Connect 공급자의 ARNS 목록을 반환합니다.  

```
aws iam list-open-id-connect-providers
```
출력:  

```
{
    "OpenIDConnectProviderList": [
        {
            "Arn": "arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com"
        }
    ]
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM에서 OIDC(OpenID Connect) ID 제공업체 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListOpenIdConnectProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-open-id-connect-providers.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 현재 AWS 계정에 정의된 모든 OpenID Connect 제공업체의 ARNS 목록을 반환합니다.**  

```
Get-IAMOpenIDConnectProviderList
```
**출력:**  

```
Arn
---
arn:aws:iam::123456789012:oidc-provider/server.example.com
arn:aws:iam::123456789012:oidc-provider/another.provider.com
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListOpenIdConnectProviders](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 현재 AWS 계정에 정의된 모든 OpenID Connect 제공업체의 ARNS 목록을 반환합니다.**  

```
Get-IAMOpenIDConnectProviderList
```
**출력:**  

```
Arn
---
arn:aws:iam::123456789012:oidc-provider/server.example.com
arn:aws:iam::123456789012:oidc-provider/another.provider.com
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListOpenIdConnectProviders](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// List IAM policies.
    /// </summary>
    /// <returns>A list of the IAM policies.</returns>
    public async Task<List<ManagedPolicy>> ListPoliciesAsync()
    {
        var listPoliciesPaginator = _IAMService.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        return policies;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListPolicies)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::listPolicies(const Aws::Client::ClientConfiguration &clientConfig) {
    const Aws::String DATE_FORMAT("%Y-%m-%d");
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListPoliciesRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListPolicies(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list iam policies: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(55) << "Name" <<
                      std::setw(30) << "ID" << std::setw(80) << "Arn" <<
                      std::setw(64) << "Description" << std::setw(12) <<
                      "CreateDate" << std::endl;
            header = true;
        }

        const auto &policies = outcome.GetResult().GetPolicies();
        for (const auto &policy: policies) {
            std::cout << std::left << std::setw(55) <<
                      policy.GetPolicyName() << std::setw(30) <<
                      policy.GetPolicyId() << std::setw(80) << policy.GetArn() <<
                      std::setw(64) << policy.GetDescription() << std::setw(12) <<
                      policy.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) <<
                      std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListPolicies)를 참조하세요.

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

**AWS CLI**  
** AWS 계정에서 사용할 수 있는 관리형 정책을 나열하려면**  
이 예제에서는 현재 AWS 계정에서 사용할 수 있는 처음 두 개의 관리형 정책 모음을 반환합니다.  

```
aws iam list-policies \
    --max-items 3
```
출력:  

```
{
    "Policies": [
        {
            "PolicyName": "AWSCloudTrailAccessPolicy",
            "PolicyId": "ANPAXQE2B5PJ7YEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:policy/AWSCloudTrailAccessPolicy",
            "Path": "/",
            "DefaultVersionId": "v1",
            "AttachmentCount": 0,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2019-09-04T17:43:42+00:00",
            "UpdateDate": "2019-09-04T17:43:42+00:00"
        },
        {
            "PolicyName": "AdministratorAccess",
            "PolicyId": "ANPAIWMBCKSKIEE64ZLYK",
            "Arn": "arn:aws:iam::aws:policy/AdministratorAccess",
            "Path": "/",
            "DefaultVersionId": "v1",
            "AttachmentCount": 6,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2015-02-06T18:39:46+00:00",
            "UpdateDate": "2015-02-06T18:39:46+00:00"
        },
        {
            "PolicyName": "PowerUserAccess",
            "PolicyId": "ANPAJYRXTHIB4FOVS3ZXS",
            "Arn": "arn:aws:iam::aws:policy/PowerUserAccess",
            "Path": "/",
            "DefaultVersionId": "v5",
            "AttachmentCount": 1,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2015-02-06T18:39:47+00:00",
            "UpdateDate": "2023-07-06T22:04:00+00:00"
        }
    ],
    "NextToken": "EXAMPLErZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiA4fQ=="
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-policies.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// ListPolicies gets up to maxPolicies policies.
func (wrapper PolicyWrapper) ListPolicies(ctx context.Context, maxPolicies int32) ([]types.Policy, error) {
	var policies []types.Policy
	result, err := wrapper.IamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPolicies),
	})
	if err != nil {
		log.Printf("Couldn't list policies. Here's why: %v\n", err)
	} else {
		policies = result.Policies
	}
	return policies, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListPolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListPolicies)를 참조하십시오.

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

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

```
import { ListPoliciesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 */
export async function* listPolicies() {
  const command = new ListPoliciesCommand({
    MaxItems: 10,
    OnlyAttached: false,
    // List only the customer managed policies in your Amazon Web Services account.
    Scope: "Local",
  });

  let response = await client.send(command);

  while (response.Policies?.length) {
    for (const policy of response.Policies) {
      yield policy;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListPoliciesCommand({
          Marker: response.Marker,
          MaxItems: 10,
          OnlyAttached: false,
          Scope: "Local",
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListPolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListPoliciesCommand)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function listPolicies($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listPoliciesArguments = [];
        if ($pathPrefix) {
            $listPoliciesArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listPoliciesArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listPoliciesArguments["MaxItems"] = $maxItems;
        }

        return $this->iamClient->listPolicies($listPoliciesArguments);
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListPolicies)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제는 현재 AWS 계정에서 사용 가능한 처음 3개의 관리형 정책 모음을 반환합니다. `-scope`는 지정되지 않았으므로 기본값은 `all` 이며 AWS 관리형 정책과 고객 관리형 정책을 모두 포함합니다.**  

```
Get-IAMPolicyList -MaxItem 3
```
**출력:**  

```
Arn              : arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : AWSDirectConnectReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:08 AM
      
Arn              : arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:27 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : NJKMU274MET4EEXAMPLE2
PolicyName       : AmazonGlacierReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:27 AM
      
Arn              : arn:aws:iam::aws:policy/AWSMarketplaceFullAccess
AttachmentCount  : 0
CreateDate       : 2/11/2015 9:21:45 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : 5ULJSO2FYVPYGEXAMPLE3
PolicyName       : AWSMarketplaceFullAccess
UpdateDate       : 2/11/2015 9:21:45 AM
```
**예제 2:이 예제는 현재 AWS 계정에서 사용할 수 있는 처음 두 개의 고객 관리형 정책 모음을 반환합니다. `-Scope local`을 사용하여 고객 관리형 정책으로만 출력을 제한합니다. **   

```
Get-IAMPolicyList -Scope local -MaxItem 2
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:policy/MyLocalPolicy
AttachmentCount  : 0
CreateDate       : 2/12/2015 9:39:09 AM
DefaultVersionId : v2
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : SQVCBLC4VAOUCEXAMPLE4
PolicyName       : MyLocalPolicy
UpdateDate       : 2/12/2015 9:39:53 AM

Arn              : arn:aws:iam::123456789012:policy/policyforec2instancerole
AttachmentCount  : 1
CreateDate       : 2/17/2015 2:51:38 PM
DefaultVersionId : v11
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : X5JPBLJH2Z2SOEXAMPLE5
PolicyName       : policyforec2instancerole
UpdateDate       : 2/18/2015 8:52:31 AM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListPolicies](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제는 현재 AWS 계정에서 사용 가능한 처음 3개의 관리형 정책 모음을 반환합니다. `-scope`는 지정되지 않았으므로 기본값은 `all` 이며 AWS 관리형 정책과 고객 관리형 정책을 모두 포함합니다.**  

```
Get-IAMPolicyList -MaxItem 3
```
**출력:**  

```
Arn              : arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : AWSDirectConnectReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:08 AM
      
Arn              : arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:27 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : NJKMU274MET4EEXAMPLE2
PolicyName       : AmazonGlacierReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:27 AM
      
Arn              : arn:aws:iam::aws:policy/AWSMarketplaceFullAccess
AttachmentCount  : 0
CreateDate       : 2/11/2015 9:21:45 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : 5ULJSO2FYVPYGEXAMPLE3
PolicyName       : AWSMarketplaceFullAccess
UpdateDate       : 2/11/2015 9:21:45 AM
```
**예제 2:이 예제는 현재 AWS 계정에서 사용할 수 있는 처음 두 개의 고객 관리형 정책 모음을 반환합니다. `-Scope local`을 사용하여 고객 관리형 정책으로만 출력을 제한합니다. **   

```
Get-IAMPolicyList -Scope local -MaxItem 2
```
**출력:**  

```
Arn              : arn:aws:iam::123456789012:policy/MyLocalPolicy
AttachmentCount  : 0
CreateDate       : 2/12/2015 9:39:09 AM
DefaultVersionId : v2
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : SQVCBLC4VAOUCEXAMPLE4
PolicyName       : MyLocalPolicy
UpdateDate       : 2/12/2015 9:39:53 AM

Arn              : arn:aws:iam::123456789012:policy/policyforec2instancerole
AttachmentCount  : 1
CreateDate       : 2/17/2015 2:51:38 PM
DefaultVersionId : v11
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : X5JPBLJH2Z2SOEXAMPLE5
PolicyName       : policyforec2instancerole
UpdateDate       : 2/18/2015 8:52:31 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListPolicies](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_policies(scope):
    """
    Lists the policies in the current account.

    :param scope: Limits the kinds of policies that are returned. For example,
                  'Local' specifies that only locally managed policies are returned.
    :return: The list of policies.
    """
    try:
        policies = list(iam.policies.filter(Scope=scope))
        logger.info("Got %s policies in scope '%s'.", len(policies), scope)
    except ClientError:
        logger.exception("Couldn't get policies for scope '%s'.", scope)
        raise
    else:
        return policies
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListPolicies)를 참조하십시오.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
이 예시 모듈은 역할 정책을 나열, 생성, 연결 및 분리합니다.  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListPolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListPolicies)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn list_policies(
    client: iamClient,
    path_prefix: String,
) -> Result<Vec<String>, SdkError<ListPoliciesError>> {
    let list_policies = client
        .list_policies()
        .path_prefix(path_prefix)
        .scope(PolicyScopeType::Local)
        .into_paginator()
        .items()
        .send()
        .try_collect()
        .await?;

    let policy_names = list_policies
        .into_iter()
        .map(|p| {
            let name = p
                .policy_name
                .unwrap_or_else(|| "Missing Policy Name".to_string());
            println!("{}", name);
            name
        })
        .collect();

    Ok(policy_names)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListPolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_policies)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listpolicies( iv_scope = iv_scope ).
        MESSAGE 'Retrieved policy list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing policies.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListPolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func listPolicies() async throws -> [MyPolicyRecord] {
        var policyList: [MyPolicyRecord] = []

        // Use "Paginated" to get all the policies.
        // This lets the SDK handle the 'isTruncated' in "ListPoliciesOutput".
        let input = ListPoliciesInput()
        let output = client.listPoliciesPaginated(input: input)

        do {
            for try await page in output {
                guard let policies = page.policies else {
                    print("Error: no policies returned.")
                    continue
                }

                for policy in policies {
                    guard let name = policy.policyName,
                          let id = policy.policyId,
                          let arn = policy.arn
                    else {
                        throw ServiceHandlerError.noSuchPolicy
                    }
                    policyList.append(MyPolicyRecord(name: name, id: id, arn: arn))
                }
            }
        } catch {
            print("ERROR: listPolicies:", dump(error))
            throw error
        }

        return policyList
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [ListPolicies](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listpolicies(input:))를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 
+  [정책 버전 롤백](iam_example_iam_Scenario_RollbackPolicyVersion_section.md) 

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

**AWS CLI**  
**지정된 관리형 정책의 버전에 대한 정보 나열**  
이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MySamplePolicy`인 정책의 사용 가능한 버전 목록을 반환합니다.  

```
aws iam list-policy-versions \
    --policy-arn arn:aws:iam::123456789012:policy/MySamplePolicy
```
출력:  

```
{
    "IsTruncated": false,
    "Versions": [
        {
        "VersionId": "v2",
        "IsDefaultVersion": true,
        "CreateDate": "2015-06-02T23:19:44Z"
        },
        {
        "VersionId": "v1",
        "IsDefaultVersion": false,
        "CreateDate": "2015-06-02T22:30:47Z"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListPolicyVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-policy-versions.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyManagedPolicy`인 정책의 사용 가능한 버전 목록을 반환합니다. 특정 버전에 대한 정책 문서를 가져오려면 `Get-IAMPolicyVersion` 명령을 사용하고 원하는 버전의 `VersionId`를 지정합니다.**  

```
Get-IAMPolicyVersionList -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy
```
**출력:**  

```
CreateDate                   Document                 IsDefaultVersion                  VersionId
----------                   --------                 ----------------                  ---------
2/12/2015 9:39:53 AM                                  True                              v2
2/12/2015 9:39:09 AM                                  False                             v1
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListPolicyVersions](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyManagedPolicy`인 정책의 사용 가능한 버전 목록을 반환합니다. 특정 버전에 대한 정책 문서를 가져오려면 `Get-IAMPolicyVersion` 명령을 사용하고 원하는 버전의 `VersionId`를 지정합니다.**  

```
Get-IAMPolicyVersionList -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy
```
**출력:**  

```
CreateDate                   Document                 IsDefaultVersion                  VersionId
----------                   --------                 ----------------                  ---------
2/12/2015 9:39:53 AM                                  True                              v2
2/12/2015 9:39:09 AM                                  False                             v1
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListPolicyVersions](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_iam->listpolicyversions(
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Retrieved policy versions list.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing policy versions.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListPolicyVersions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// List IAM role policies.
    /// </summary>
    /// <param name="roleName">The IAM role for which to list IAM policies.</param>
    /// <returns>A list of IAM policy names.</returns>
    public async Task<List<string>> ListRolePoliciesAsync(string roleName)
    {
        var listRolePoliciesPaginator = _IAMService.Paginators.ListRolePolicies(new ListRolePoliciesRequest { RoleName = roleName });
        var policyNames = new List<string>();

        await foreach (var response in listRolePoliciesPaginator.Responses)
        {
            policyNames.AddRange(response.PolicyNames);
        }

        return policyNames;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListRolePolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListRolePolicies)를 참조하세요.

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

**AWS CLI**  
****IAM 역할에 연결된 정책 나열  
다음 `list-role-policies` 명령은 지정된 IAM 역할의 권한 정책 이름을 나열합니다.  

```
aws iam list-role-policies \
    --role-name Test-Role
```
출력:  

```
{
    "PolicyNames": [
        "ExamplePolicy"
    ]
}
```
역할에 연결된 신뢰 정책을 보려면 `get-role` 명령을 사용합니다. 권한 정책의 세부 정보를 보려면 `get-role-policy` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListRolePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-role-policies.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// ListRolePolicies lists the inline policies for a role.
func (wrapper RoleWrapper) ListRolePolicies(ctx context.Context, roleName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListRolePolicies(ctx, &iam.ListRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListRolePolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListRolePolicies)를 참조하십시오.

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

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

```
import { ListRolePoliciesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 * @param {string} roleName
 */
export async function* listRolePolicies(roleName) {
  const command = new ListRolePoliciesCommand({
    RoleName: roleName,
    MaxItems: 10,
  });

  let response = await client.send(command);

  while (response.PolicyNames?.length) {
    for (const policyName of response.PolicyNames) {
      yield policyName;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListRolePoliciesCommand({
          RoleName: roleName,
          MaxItems: 10,
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListRolePolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListRolePoliciesCommand)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function listRolePolicies($roleName, $marker = "", $maxItems = 0)
    {
        $listRolePoliciesArguments = ['RoleName' => $roleName];
        if ($marker) {
            $listRolePoliciesArguments['Marker'] = $marker;
        }
        if ($maxItems) {
            $listRolePoliciesArguments['MaxItems'] = $maxItems;
        }
        return $this->customWaiter(function () use ($listRolePoliciesArguments) {
            return $this->iamClient->listRolePolicies($listRolePoliciesArguments);
        });
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [ListRolePolicies](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListRolePolicies)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 역할 `lamda_exec_role`에 포함된 인라인 정책 이름의 목록을 반환합니다. 인라인 정책의 세부 정보를 보려면 `Get-IAMRolePolicy` 명령을 사용합니다.**  

```
Get-IAMRolePolicyList -RoleName lambda_exec_role
```
**출력:**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 역할 `lamda_exec_role`에 포함된 인라인 정책 이름의 목록을 반환합니다. 인라인 정책의 세부 정보를 보려면 `Get-IAMRolePolicy` 명령을 사용합니다.**  

```
Get-IAMRolePolicyList -RoleName lambda_exec_role
```
**출력:**  

```
oneClick_lambda_exec_role_policy
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListRolePolicies](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_policies(role_name):
    """
    Lists inline policies for a role.

    :param role_name: The name of the role to query.
    """
    try:
        role = iam.Role(role_name)
        for policy in role.policies.all():
            logger.info("Got inline policy %s.", policy.name)
    except ClientError:
        logger.exception("Couldn't list inline policies for %s.", role_name)
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListRolePolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListRolePolicies)를 참조하세요.

------
#### [ Ruby ]

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

```
  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListRolePolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListRolePolicies)를 참조하세요.

------
#### [ Rust ]

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

```
pub async fn list_role_policies(
    client: &iamClient,
    role_name: &str,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListRolePoliciesOutput, SdkError<ListRolePoliciesError>> {
    let response = client
        .list_role_policies()
        .role_name(role_name)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;

    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListRolePolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_role_policies)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listrolepolicies(
          iv_rolename = iv_role_name ).
        MESSAGE 'Retrieved inline policy list for role.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListRolePolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func listRolePolicies(role: String) async throws -> [String] {
        var policyList: [String] = []

        // Use "Paginated" to get all the role policies.
        // This lets the SDK handle the 'isTruncated' in "ListRolePoliciesOutput".
        let input = ListRolePoliciesInput(
            roleName: role
        )
        let pages = client.listRolePoliciesPaginated(input: input)

        do {
            for try await page in pages {
                guard let policies = page.policyNames else {
                    print("Error: no role policies returned.")
                    continue
                }

                for policy in policies {
                    policyList.append(policy)
                }
            }
        } catch {
            print("ERROR: listRolePolicies:", dump(error))
            throw error
        }
        return policyList
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [ListRolePolicies](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listrolepolicies(input:))를 참조하세요.

------

# CLI로 `ListRoleTags` 사용
<a name="iam_example_iam_ListRoleTags_section"></a>

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

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

**AWS CLI**  
**역할에 연결된 태그 나열**  
다음 `list-role-tags` 명령은 지정된 역할과 연결된 태그 목록을 검색합니다.  

```
aws iam list-role-tags \
    --role-name production-role
```
출력:  

```
{
    "Tags": [
        {
            "Key": "Department",
            "Value": "Accounting"
        },
        {
            "Key": "DeptID",
            "Value": "12345"
        }
    ],
    "IsTruncated": false
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 리소스 태그 지정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListRoleTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-role-tags.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 역할과 연결된 태그를 가져옵니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 역할과 연결된 태그를 가져옵니다.**  

```
Get-IAMRoleTagList -RoleName MyRoleName
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListRoleTags](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// List IAM roles.
    /// </summary>
    /// <returns>A list of IAM roles.</returns>
    public async Task<List<Role>> ListRolesAsync()
    {
        var listRolesPaginator = _IAMService.Paginators.ListRoles(new ListRolesRequest());
        var roles = new List<Role>();

        await foreach (var response in listRolesPaginator.Responses)
        {
            roles.AddRange(response.Roles);
        }

        return roles;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListRoles](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListRoles)를 참조하세요.

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

**AWS CLI**  
**현재 계정의 IAM 역할 나열**  
다음 `list-roles` 명령은 현재 계정의 IAM 역할을 나열합니다.  

```
aws iam list-roles
```
출력:  

```
{
    "Roles": [
        {
            "Path": "/",
            "RoleName": "ExampleRole",
            "RoleId": "AROAJ52OTH4H7LEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:role/ExampleRole",
            "CreateDate": "2017-09-12T19:23:36+00:00",
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "MaxSessionDuration": 3600
        },
        {
            "Path": "/example_path/",
            "RoleName": "ExampleRoleWithPath",
            "RoleId": "AROAI4QRP7UFT7EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:role/example_path/ExampleRoleWithPath",
            "CreateDate": "2023-09-21T20:29:38+00:00",
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "MaxSessionDuration": 3600
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListRoles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-roles.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// ListRoles gets up to maxRoles roles.
func (wrapper RoleWrapper) ListRoles(ctx context.Context, maxRoles int32) ([]types.Role, error) {
	var roles []types.Role
	result, err := wrapper.IamClient.ListRoles(ctx,
		&iam.ListRolesInput{MaxItems: aws.Int32(maxRoles)},
	)
	if err != nil {
		log.Printf("Couldn't list roles. Here's why: %v\n", err)
	} else {
		roles = result.Roles
	}
	return roles, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListRoles](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListRoles)를 참조하십시오.

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

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

```
import { ListRolesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 */
export async function* listRoles() {
  const command = new ListRolesCommand({
    MaxItems: 10,
  });

  /**
   * @type {import("@aws-sdk/client-iam").ListRolesCommandOutput | undefined}
   */
  let response = await client.send(command);

  while (response?.Roles?.length) {
    for (const role of response.Roles) {
      yield role;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListRolesCommand({
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListRoles](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListRolesCommand)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    /**
     * @param string $pathPrefix
     * @param string $marker
     * @param int $maxItems
     * @return Result
     * $roles = $service->listRoles();
     */
    public function listRoles($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listRolesArguments = [];
        if ($pathPrefix) {
            $listRolesArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listRolesArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listRolesArguments["MaxItems"] = $maxItems;
        }
        return $this->iamClient->listRoles($listRolesArguments);
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [ListRoles](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListRoles)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 AWS 계정의 모든 IAM 역할 목록을 검색합니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 AWS 계정의 모든 IAM 역할 목록을 검색합니다.**  

```
Get-IAMRoleList
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListRoles](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_roles(count):
    """
    Lists the specified number of roles for the account.

    :param count: The number of roles to list.
    """
    try:
        roles = list(iam.roles.limit(count=count))
        for role in roles:
            logger.info("Role: %s", role.name)
    except ClientError:
        logger.exception("Couldn't list roles for the account.")
        raise
    else:
        return roles
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListRoles](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListRoles)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Lists IAM roles up to a specified count.
  # @param count [Integer] the maximum number of roles to list.
  # @return [Array<String>] the names of the roles.
  def list_roles(count)
    role_names = []
    roles_counted = 0

    @iam_client.list_roles.each_page do |page|
      page.roles.each do |role|
        break if roles_counted >= count

        @logger.info("\t#{roles_counted + 1}: #{role.role_name}")
        role_names << role.role_name
        roles_counted += 1
      end
      break if roles_counted >= count
    end

    role_names
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't list roles for the account. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListRoles](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListRoles)를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn list_roles(
    client: &iamClient,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListRolesOutput, SdkError<ListRolesError>> {
    let response = client
        .list_roles()
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;
    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListRoles](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_roles)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listroles( ).
        MESSAGE 'Retrieved role list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing roles.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListRoles](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func listRoles() async throws -> [String] {
        var roleList: [String] = []

        // Use "Paginated" to get all the roles.
        // This lets the SDK handle the 'isTruncated' in "ListRolesOutput".
        let input = ListRolesInput()
        let pages = client.listRolesPaginated(input: input)

        do {
            for try await page in pages {
                guard let roles = page.roles else {
                    print("Error: no roles returned.")
                    continue
                }

                for role in roles {
                    if let name = role.roleName {
                        roleList.append(name)
                    }
                }
            }
        } catch {
            print("ERROR: listRoles:", dump(error))
            throw error
        }
        return roleList
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [ListRoles](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listroles(input:))을 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// List SAML authentication providers.
    /// </summary>
    /// <returns>A list of SAML providers.</returns>
    public async Task<List<SAMLProviderListEntry>> ListSAMLProvidersAsync()
    {
        var response = await _IAMService.ListSAMLProvidersAsync(new ListSAMLProvidersRequest());
        return response.SAMLProviderList;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListSAMLProviders](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListSAMLProviders)를 참조하세요.

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

**AWS CLI**  
** AWS 계정의 SAML 공급자를 나열하려면**  
이 예제에서는 현재 AWS 계정에서 생성된 SAML 2.0 공급자 목록을 검색합니다.  

```
aws iam list-saml-providers
```
출력:  

```
{
    "SAMLProviderList": [
        {
            "Arn": "arn:aws:iam::123456789012:saml-provider/SAML-ADFS",
            "ValidUntil": "2015-06-05T22:45:14Z",
            "CreateDate": "2015-06-05T22:45:14Z"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM SAML 자격 증명 공급자 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListSAMLProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-saml-providers.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// ListSAMLProviders gets the SAML providers for the account.
func (wrapper AccountWrapper) ListSAMLProviders(ctx context.Context) ([]types.SAMLProviderListEntry, error) {
	var providers []types.SAMLProviderListEntry
	result, err := wrapper.IamClient.ListSAMLProviders(ctx, &iam.ListSAMLProvidersInput{})
	if err != nil {
		log.Printf("Couldn't list SAML providers. Here's why: %v\n", err)
	} else {
		providers = result.SAMLProviderList
	}
	return providers, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListSAMLProviders](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListSAMLProviders)를 참조하십시오.

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

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

```
import { ListSAMLProvidersCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const listSamlProviders = async () => {
  const command = new ListSAMLProvidersCommand({});

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListSAMLProviders](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListSAMLProvidersCommand)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function listSAMLProviders()
    {
        return $this->iamClient->listSAMLProviders();
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [ListSAMLProviders](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListSAMLProviders)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 현재 AWS 계정에서 생성된 SAML 2.0 제공업체 목록을 검색합니다. 각 SAML 제공업체의 ARN, 생성 날짜 및 만료 날짜를 반환합니다.**  

```
Get-IAMSAMLProviderList
```
**출력:**  

```
Arn                                                 CreateDate                      ValidUntil
---                                                 ----------                      ----------
arn:aws:iam::123456789012:saml-provider/SAMLADFS    12/23/2014 12:16:55 PM          12/23/2114 12:16:54 PM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListSAMLProviders](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 현재 AWS 계정에서 생성된 SAML 2.0 제공업체 목록을 검색합니다. 각 SAML 제공업체의 ARN, 생성 날짜 및 만료 날짜를 반환합니다.**  

```
Get-IAMSAMLProviderList
```
**출력:**  

```
Arn                                                 CreateDate                      ValidUntil
---                                                 ----------                      ----------
arn:aws:iam::123456789012:saml-provider/SAMLADFS    12/23/2014 12:16:55 PM          12/23/2114 12:16:54 PM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListSAMLProviders](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_saml_providers(count):
    """
    Lists the SAML providers for the account.

    :param count: The maximum number of providers to list.
    """
    try:
        found = 0
        for provider in iam.saml_providers.limit(count):
            logger.info("Got SAML provider %s.", provider.arn)
            found += 1
        if found == 0:
            logger.info("Your account has no SAML providers.")
    except ClientError:
        logger.exception("Couldn't list SAML providers.")
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListSAMLProviders](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListSAMLProviders)를 참조하십시오.

------
#### [ Ruby ]

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

```
class SamlProviderLister
  # Initializes the SamlProviderLister with IAM client and a logger.
  # @param iam_client [Aws::IAM::Client] The IAM client object.
  # @param logger [Logger] The logger object for logging output.
  def initialize(iam_client, logger = Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists up to a specified number of SAML providers for the account.
  # @param count [Integer] The maximum number of providers to list.
  # @return [Aws::IAM::Client::Response]
  def list_saml_providers(count)
    response = @iam_client.list_saml_providers
    response.saml_provider_list.take(count).each do |provider|
      @logger.info("\t#{provider.arn}")
    end
    response
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't list SAML providers. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListSAMLProviders](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListSAMLProviders)를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn list_saml_providers(
    client: &Client,
) -> Result<ListSamlProvidersOutput, SdkError<ListSAMLProvidersError>> {
    let response = client.list_saml_providers().send().await?;

    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListSAMLProviders](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_saml_providers)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listsamlproviders( ).
        MESSAGE 'Retrieved SAML provider list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing SAML providers.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API 참조*의 [ListSAMLProviders](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------

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

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

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::listServerCertificates(
        const Aws::Client::ClientConfiguration &clientConfig) {
    const Aws::String DATE_FORMAT = "%Y-%m-%d";

    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListServerCertificatesRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListServerCertificates(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list server certificates: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(55) << "Name" <<
                      std::setw(30) << "ID" << std::setw(80) << "Arn" <<
                      std::setw(14) << "UploadDate" << std::setw(14) <<
                      "ExpirationDate" << std::endl;
            header = true;
        }

        const auto &certificates =
                outcome.GetResult().GetServerCertificateMetadataList();

        for (const auto &certificate: certificates) {
            std::cout << std::left << std::setw(55) <<
                      certificate.GetServerCertificateName() << std::setw(30) <<
                      certificate.GetServerCertificateId() << std::setw(80) <<
                      certificate.GetArn() << std::setw(14) <<
                      certificate.GetUploadDate().ToGmtString(DATE_FORMAT.c_str()) <<
                      std::setw(14) <<
                      certificate.GetExpiration().ToGmtString(DATE_FORMAT.c_str()) <<
                      std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [ListServerCertificates](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListServerCertificates)를 참조하세요.

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

**AWS CLI**  
** AWS 계정의 서버 인증서를 나열하려면**  
다음 `list-server-certificates` 명령은 AWS 계정에서 저장되고 사용할 수 있는 모든 서버 인증서를 나열합니다.  

```
aws iam list-server-certificates
```
출력:  

```
{
    "ServerCertificateMetadataList": [
        {
            "Path": "/",
            "ServerCertificateName": "myUpdatedServerCertificate",
            "ServerCertificateId": "ASCAEXAMPLE123EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:server-certificate/myUpdatedServerCertificate",
            "UploadDate": "2019-04-22T21:13:44+00:00",
            "Expiration": "2019-10-15T22:23:16+00:00"
        },
        {
            "Path": "/cloudfront/",
            "ServerCertificateName": "MyTestCert",
            "ServerCertificateId": "ASCAEXAMPLE456EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyTestCert",
            "UploadDate": "2015-04-21T18:14:16+00:00",
            "Expiration": "2018-01-14T17:52:36+00:00"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM에서 서버 인증서 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListServerCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-server-certificates.html)를 참조하세요.

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

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

```
import { ListServerCertificatesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 */
export async function* listServerCertificates() {
  const command = new ListServerCertificatesCommand({});
  let response = await client.send(command);

  while (response.ServerCertificateMetadataList?.length) {
    for await (const cert of response.ServerCertificateMetadataList) {
      yield cert;
    }

    if (response.IsTruncated) {
      response = await client.send(new ListServerCertificatesCommand({}));
    } else {
      break;
    }
  }
}
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-listing)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListServerCertificates](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListServerCertificatesCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.listServerCertificates({}, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-listing)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListServerCertificates](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListServerCertificates)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 현재 AWS 계정에 업로드된 서버 인증서 목록을 검색합니다.**  

```
Get-IAMServerCertificateList
```
**출력:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListServerCertificates](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 현재 AWS 계정에 업로드된 서버 인증서 목록을 검색합니다.**  

```
Get-IAMServerCertificateList
```
**출력:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListServerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
서버 인증서를 나열하고, 업데이트하고, 삭제합니다.  

```
class ServerCertificateManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'ServerCertificateManager'
  end

  # Creates a new server certificate.
  # @param name [String] the name of the server certificate
  # @param certificate_body [String] the contents of the certificate
  # @param private_key [String] the private key contents
  # @return [Boolean] returns true if the certificate was successfully created
  def create_server_certificate(name, certificate_body, private_key)
    @iam_client.upload_server_certificate({
                                            server_certificate_name: name,
                                            certificate_body: certificate_body,
                                            private_key: private_key
                                          })
    true
  rescue Aws::IAM::Errors::ServiceError => e
    puts "Failed to create server certificate: #{e.message}"
    false
  end

  # Lists available server certificate names.
  def list_server_certificate_names
    response = @iam_client.list_server_certificates

    if response.server_certificate_metadata_list.empty?
      @logger.info('No server certificates found.')
      return
    end

    response.server_certificate_metadata_list.each do |certificate_metadata|
      @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}")
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing server certificates: #{e.message}")
  end

  # Updates the name of a server certificate.
  def update_server_certificate_name(current_name, new_name)
    @iam_client.update_server_certificate(
      server_certificate_name: current_name,
      new_server_certificate_name: new_name
    )
    @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error updating server certificate name: #{e.message}")
    false
  end

  # Deletes a server certificate.
  def delete_server_certificate(name)
    @iam_client.delete_server_certificate(server_certificate_name: name)
    @logger.info("Server certificate '#{name}' deleted.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting server certificate: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListServerCertificates](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListServerCertificates)를 참조하세요.

------

# CLI로 `ListSigningCertificates` 사용
<a name="iam_example_iam_ListSigningCertificates_section"></a>

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

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

**AWS CLI**  
**IAM 사용자의 서명 인증서 나열**  
다음 `list-signing-certificates` 명령은 `Bob`이라는 IAM 사용자의 서명 인증서를 나열합니다.  

```
aws iam list-signing-certificates \
    --user-name Bob
```
출력:  

```
{
    "Certificates": [
        {
            "UserName": "Bob",
            "Status": "Inactive",
            "CertificateBody": "-----BEGIN CERTIFICATE-----<certificate-body>-----END CERTIFICATE-----",
            "CertificateId": "TA7SMP42TDN5Z26OBPJE7EXAMPLE",
            "UploadDate": "2013-06-06T21:40:08Z"
        }
    ]
}
```
자세한 내용은 **Amazon EC2 사용 설명서의 [서명 인증서 관리](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-up-ami-tools.html#ami-tools-managing-certs)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListSigningCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-signing-certificates.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 사용자와 연결된 서명 인증서에 대한 세부 정보를 검색합니다.**  

```
Get-IAMSigningCertificate -UserName Bob
```
**출력:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListSigningCertificates](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 사용자와 연결된 서명 인증서에 대한 세부 정보를 검색합니다.**  

```
Get-IAMSigningCertificate -UserName Bob
```
**출력:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListSigningCertificates](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

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

**AWS CLI**  
**IAM 사용자에 대한 정책 나열**  
다음 `list-user-policies` 명령은 이름이 `Bob`인 IAM 사용자에게 연결된 정책을 나열합니다.  

```
aws iam list-user-policies \
    --user-name Bob
```
출력:  

```
{
    "PolicyNames": [
        "ExamplePolicy",
        "TestPolicy"
    ]
}
```
자세한 내용은 [IAM 사용 설명서의 AWS 계정에서 IAM 사용자 생성을 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html). *AWS *   
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListUserPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-user-policies.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUserPolicies lists the inline policies for the specified user.
func (wrapper UserWrapper) ListUserPolicies(ctx context.Context, userName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListUserPolicies(ctx, &iam.ListUserPoliciesInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for user %v. Here's why: %v\n", userName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListUserPolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListUserPolicies)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `David`라는 IAM 사용자에게 포함된 인라인 정책의 이름 목록을 검색합니다.**  

```
Get-IAMUserPolicyList -UserName David
```
**출력:**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `David`라는 IAM 사용자에게 포함된 인라인 정책의 이름 목록을 검색합니다.**  

```
Get-IAMUserPolicyList -UserName David
```
**출력:**  

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

------

# CLI로 `ListUserTags` 사용
<a name="iam_example_iam_ListUserTags_section"></a>

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

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

**AWS CLI**  
**사용자에게 연결된 태그 나열**  
다음 `list-user-tags` 명령은 지정된 IAM 사용자와 연결된 태그 목록을 검색합니다.  

```
aws iam list-user-tags \
    --user-name alice
```
출력:  

```
{
    "Tags": [
        {
            "Key": "Department",
            "Value": "Accounting"
        },
        {
            "Key": "DeptID",
            "Value": "12345"
        }
    ],
    "IsTruncated": false
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 리소스 태그 지정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListUserTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-user-tags.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 사용자와 연결된 태그를 가져옵니다.**  

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

**Tools for PowerShell V5**  
**예제 1: 이 예제는 사용자와 연결된 태그를 가져옵니다.**  

```
Get-IAMUserTagList -UserName joe
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListUserTags](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 

------
#### [ .NET ]

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

```
    /// <summary>
    /// List IAM users.
    /// </summary>
    /// <returns>A list of IAM users.</returns>
    public async Task<List<User>> ListUsersAsync()
    {
        var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest());
        var users = new List<User>();

        await foreach (var response in listUsersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [ListUsers](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListUsers)를 참조하세요.

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_list_users
#
# List the IAM users in the account.
#
# Returns:
#       The list of users names
#    And:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_list_users() {
  local option OPTARG # Required to use getopts command in a function.
  local error_code
  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_list_users"
    echo "Lists the AWS Identity and Access Management (IAM) user in the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "h" option; do
    case "${option}" in
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local response

  response=$(aws iam list-users \
    --output text \
    --query "Users[].UserName")
  error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports list-users operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListUsers](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/ListUsers)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::listUsers(const Aws::Client::ClientConfiguration &clientConfig) {
    const Aws::String DATE_FORMAT = "%Y-%m-%d";
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListUsersRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListUsers(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list iam users:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(32) << "Name" <<
                      std::setw(30) << "ID" << std::setw(64) << "Arn" <<
                      std::setw(20) << "CreateDate" << std::endl;
            header = true;
        }

        const auto &users = outcome.GetResult().GetUsers();
        for (const auto &user: users) {
            std::cout << std::left << std::setw(32) << user.GetUserName() <<
                      std::setw(30) << user.GetUserId() << std::setw(64) <<
                      user.GetArn() << std::setw(20) <<
                      user.GetCreateDate().ToGmtString(DATE_FORMAT.c_str())
                      << std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [ListUsers](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListUsers)를 참조하세요.

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

**AWS CLI**  
**IAM 사용자 나열**  
다음 `list-users` 명령은 현재 계정의 IAM 사용자를 나열합니다.  

```
aws iam list-users
```
출력:  

```
{
    "Users": [
        {
            "UserName": "Adele",
            "Path": "/",
            "CreateDate": "2013-03-07T05:14:48Z",
            "UserId": "AKIAI44QH8DHBEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:user/Adele"
        },
        {
            "UserName": "Bob",
            "Path": "/",
            "CreateDate": "2012-09-21T23:03:13Z",
            "UserId": "AKIAIOSFODNN7EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:user/Bob"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 나열](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_manage_list)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-users.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUsers gets up to maxUsers number of users.
func (wrapper UserWrapper) ListUsers(ctx context.Context, maxUsers int32) ([]types.User, error) {
	var users []types.User
	result, err := wrapper.IamClient.ListUsers(ctx, &iam.ListUsersInput{
		MaxItems: aws.Int32(maxUsers),
	})
	if err != nil {
		log.Printf("Couldn't list users. Here's why: %v\n", err)
	} else {
		users = result.Users
	}
	return users, err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [ListUsers](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListUsers)를 참조하십시오.

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

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

```
import software.amazon.awssdk.services.iam.model.AttachedPermissionsBoundary;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListUsersRequest;
import software.amazon.awssdk.services.iam.model.ListUsersResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.User;

/**
 * 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 ListUsers {
    public static void main(String[] args) {
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listAllUsers(iam);
        System.out.println("Done");
        iam.close();
    }

    public static void listAllUsers(IamClient iam) {
        try {
            boolean done = false;
            String newMarker = null;
            while (!done) {
                ListUsersResponse response;
                if (newMarker == null) {
                    ListUsersRequest request = ListUsersRequest.builder().build();
                    response = iam.listUsers(request);
                } else {
                    ListUsersRequest request = ListUsersRequest.builder()
                            .marker(newMarker)
                            .build();

                    response = iam.listUsers(request);
                }

                for (User user : response.users()) {
                    System.out.format("\n Retrieved user %s", user.userName());
                    AttachedPermissionsBoundary permissionsBoundary = user.permissionsBoundary();
                    if (permissionsBoundary != null)
                        System.out.format("\n Permissions boundary details %s",
                                permissionsBoundary.permissionsBoundaryTypeAsString());
                }

                if (!response.isTruncated()) {
                    done = true;
                } else {
                    newMarker = response.marker();
                }
            }

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [ListUsers](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListUsers)를 참조하십시오.

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

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

```
import { ListUsersCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const listUsers = async () => {
  const command = new ListUsersCommand({ MaxItems: 10 });

  const response = await client.send(command);

  for (const { UserName, CreateDate } of response.Users) {
    console.log(`${UserName} created on: ${CreateDate}`);
  }
  return response;
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-listing-users)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListUsers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListUsersCommand)를 참조하십시오.

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

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  MaxItems: 10,
};

iam.listUsers(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var users = data.Users || [];
    users.forEach(function (user) {
      console.log("User " + user.UserName + " created", user.CreateDate);
    });
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-listing-users)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [ListUsers](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListUsers)를 참조하십시오.

------
#### [ Kotlin ]

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

```
suspend fun listAllUsers() {
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listUsers(ListUsersRequest { })
        response.users?.forEach { user ->
            println("Retrieved user ${user.userName}")
            val permissionsBoundary = user.permissionsBoundary
            if (permissionsBoundary != null) {
                println("Permissions boundary details ${permissionsBoundary.permissionsBoundaryType}")
            }
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [ListUsers](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하십시오.

------
#### [ PHP ]

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

```
$uuid = uniqid();
$service = new IAMService();

    public function listUsers($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listUsersArguments = [];
        if ($pathPrefix) {
            $listUsersArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listUsersArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listUsersArguments["MaxItems"] = $maxItems;
        }

        return $this->iamClient->listUsers($listUsersArguments);
    }
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [ListUsers](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListUsers)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제는 현재의 사용자 모음을 검색합니다 AWS 계정.**  

```
Get-IAMUserList
```
**출력:**  

```
      Arn              : arn:aws:iam::123456789012:user/Administrator
      CreateDate       : 10/16/2014 9:03:09 AM
      PasswordLastUsed : 3/4/2015 12:12:33 PM
      Path             : /
      UserId           : 7K3GJEANSKZF2EXAMPLE1
      UserName         : Administrator
      
      Arn              : arn:aws:iam::123456789012:user/Bob
      CreateDate       : 4/6/2015 12:54:42 PM
      PasswordLastUsed : 1/1/0001 12:00:00 AM
      Path             : /
      UserId           : L3EWNONDOM3YUEXAMPLE2
      UserName         : bab
      
      Arn              : arn:aws:iam::123456789012:user/David
      CreateDate       : 12/10/2014 3:39:27 PM
      PasswordLastUsed : 3/19/2015 8:44:04 AM
      Path             : /
      UserId           : Y4FKWQCXTA52QEXAMPLE3
      UserName         : David
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListUsers](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제는 현재의 사용자 모음을 검색합니다 AWS 계정.**  

```
Get-IAMUserList
```
**출력:**  

```
      Arn              : arn:aws:iam::123456789012:user/Administrator
      CreateDate       : 10/16/2014 9:03:09 AM
      PasswordLastUsed : 3/4/2015 12:12:33 PM
      Path             : /
      UserId           : 7K3GJEANSKZF2EXAMPLE1
      UserName         : Administrator
      
      Arn              : arn:aws:iam::123456789012:user/Bob
      CreateDate       : 4/6/2015 12:54:42 PM
      PasswordLastUsed : 1/1/0001 12:00:00 AM
      Path             : /
      UserId           : L3EWNONDOM3YUEXAMPLE2
      UserName         : bab
      
      Arn              : arn:aws:iam::123456789012:user/David
      CreateDate       : 12/10/2014 3:39:27 PM
      PasswordLastUsed : 3/19/2015 8:44:04 AM
      Path             : /
      UserId           : Y4FKWQCXTA52QEXAMPLE3
      UserName         : David
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListUsers](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def list_users():
    """
    Lists the users in the current account.

    :return: The list of users.
    """
    try:
        users = list(iam.users.all())
        logger.info("Got %s users.", len(users))
    except ClientError:
        logger.exception("Couldn't get users.")
        raise
    else:
        return users
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [ListUsers](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListUsers)를 참조하십시오.

------
#### [ Ruby ]

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

```
  # Lists all users in the AWS account
  #
  # @return [Array<Aws::IAM::Types::User>] An array of user objects
  def list_users
    users = []
    @iam_client.list_users.each_page do |page|
      page.users.each do |user|
        users << user
      end
    end
    users
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing users: #{e.message}")
    []
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [ListUsers](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListUsers)를 참조하십시오.

------
#### [ Rust ]

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

```
pub async fn list_users(
    client: &iamClient,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListUsersOutput, SdkError<ListUsersError>> {
    let response = client
        .list_users()
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;
    Ok(response)
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [ListUsers](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_users)을 참조하세요.

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

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

```
    TRY.
        oo_result = lo_iam->listusers( ).
        MESSAGE 'Retrieved user list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing users.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 *AWS SDK for SAP ABAP API*의 [ListUsers](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    public func listUsers() async throws -> [MyUserRecord] {
        var userList: [MyUserRecord] = []
        
        // Use "Paginated" to get all the users.
        // This lets the SDK handle the 'isTruncated' in "ListUsersOutput".
        let input = ListUsersInput()
        let output = client.listUsersPaginated(input: input)

        do {
            for try await page in output {
                guard let users = page.users else {
                    continue
                }
                for user in users {
                    if let id = user.userId, let name = user.userName {
                        userList.append(MyUserRecord(id: id, name: name))
                    }
                }
            }
        }
        catch {
            print("ERROR: listUsers:", dump(error))
            throw error
        }
       return userList
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [ListUsers](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listusers(input:))를 참조하세요.

------

# CLI로 `ListVirtualMfaDevices` 사용
<a name="iam_example_iam_ListVirtualMfaDevices_section"></a>

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

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

**AWS CLI**  
**가상 MFA 디바이스 나열**  
다음 `list-virtual-mfa-devices` 명령은 현재 계정에 대해 구성된 가상 MFA 디바이스를 나열합니다.  

```
aws iam list-virtual-mfa-devices
```
출력:  

```
{
    "VirtualMFADevices": [
        {
            "SerialNumber": "arn:aws:iam::123456789012:mfa/ExampleMFADevice"
        },
        {
            "SerialNumber": "arn:aws:iam::123456789012:mfa/Fred"
        }
    ]
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [가상 다중 인증(MFA) 디바이스 활성화](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ListVirtualMfaDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-virtual-mfa-devices.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1:이 예제는 AWS 계정의 사용자에게 할당된 가상 MFA 디바이스의 모음을 검색합니다. 각각의 `User` 속성은 해당 디바이스가 할당된 IAM 사용자의 세부 정보가 포함된 객체입니다.**  

```
Get-IAMVirtualMFADevice -AssignmentStatus Assigned
```
**출력:**  

```
Base32StringSeed : 
EnableDate       : 4/13/2015 12:03:42 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/David
User             : Amazon.IdentityManagement.Model.User

Base32StringSeed : 
EnableDate       : 4/13/2015 12:06:41 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/root-account-mfa-device
User             : Amazon.IdentityManagement.Model.User
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ListVirtualMfaDevices](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1:이 예제는 AWS 계정의 사용자에게 할당된 가상 MFA 디바이스의 모음을 검색합니다. 각각의 `User` 속성은 해당 디바이스가 할당된 IAM 사용자의 세부 정보가 포함된 객체입니다.**  

```
Get-IAMVirtualMFADevice -AssignmentStatus Assigned
```
**출력:**  

```
Base32StringSeed : 
EnableDate       : 4/13/2015 12:03:42 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/David
User             : Amazon.IdentityManagement.Model.User

Base32StringSeed : 
EnableDate       : 4/13/2015 12:06:41 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/root-account-mfa-device
User             : Amazon.IdentityManagement.Model.User
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ListVirtualMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `PutGroupPolicy` 사용
<a name="iam_example_iam_PutGroupPolicy_section"></a>

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

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

**AWS CLI**  
**그룹에 정책 추가**  
다음 `put-group-policy` 명령은 이름이 `Admins`인 IAM 그룹에 정책을 추가합니다.  

```
aws iam put-group-policy \
    --group-name Admins \
    --policy-document file://AdminPolicy.json \
    --policy-name AdminRoot
```
이 명령은 출력을 생성하지 않습니다.  
정책은 AdminPolicy.json** 파일에서 JSON 문서로 정의됩니다. (파일 이름과 확장자는 중요하지 않습니다.)  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 정책 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-group-policy.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `AppTesterPolicy`라는 인라인 정책을 생성하고 이를 IAM 그룹 `AppTesters`에 포함합니다. 동일한 이름의 인라인 정책이 이미 존재하는 경우 해당 정책을 덮어씁니다. JSON 정책 내용은 `apptesterpolicy.json` 파일로 제공됩니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 파라미터를 사용해야 합니다.**  

```
Write-IAMGroupPolicy -GroupName AppTesters -PolicyName AppTesterPolicy -PolicyDocument (Get-Content -Raw apptesterpolicy.json)
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [PutGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `AppTesterPolicy`라는 인라인 정책을 생성하고 이를 IAM 그룹 `AppTesters`에 포함합니다. 동일한 이름의 인라인 정책이 이미 존재하는 경우 해당 정책을 덮어씁니다. JSON 정책 내용은 `apptesterpolicy.json` 파일로 제공됩니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 파라미터를 사용해야 합니다.**  

```
Write-IAMGroupPolicy -GroupName AppTesters -PolicyName AppTesterPolicy -PolicyDocument (Get-Content -Raw apptesterpolicy.json)
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `PutRolePermissionsBoundary` 사용
<a name="iam_example_iam_PutRolePermissionsBoundary_section"></a>

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

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

**AWS CLI**  
**예제 1: IAM 역할에 사용자 지정 정책을 기반으로 권한 경계 적용**  
다음 `put-role-permissions-boundary` 예제는 `intern-boundary`라는 사용자 지정 정책을 지정된 IAM 역할에 대한 권한 경계로 적용합니다.  

```
aws iam put-role-permissions-boundary \
    --permissions-boundary arn:aws:iam::123456789012:policy/intern-boundary \
    --role-name lambda-application-role
```
이 명령은 출력을 생성하지 않습니다.  
**예제 2: AWS 관리형 정책을 기반으로 IAM 역할에 권한 경계 적용**  
다음 `put-role-permissions-boundary` 예제에서는 AWS 관리형 `PowerUserAccess` 정책을 지정된 IAM 역할에 대한 권한 경계로 적용합니다.  

```
aws iam put-role-permissions-boundary \
    --permissions-boundary arn:aws:iam::aws:policy/PowerUserAccess \
    --role-name x-account-admin
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [역할 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutRolePermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-role-permissions-boundary.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 역할의 권한 경계를 설정하는 방법을 보여줍니다. AWS 관리형 정책 또는 사용자 지정 정책을 권한 경계로 설정할 수 있습니다.**  

```
Set-IAMRolePermissionsBoundary -RoleName MyRoleName -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [PutRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 역할의 권한 경계를 설정하는 방법을 보여줍니다. AWS 관리형 정책 또는 사용자 지정 정책을 권한 경계로 설정할 수 있습니다.**  

```
Set-IAMRolePermissionsBoundary -RoleName MyRoleName -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

------
#### [ .NET ]

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

```
    /// <summary>
    /// Update the inline policy document embedded in a role.
    /// </summary>
    /// <param name="policyName">The name of the policy to embed.</param>
    /// <param name="roleName">The name of the role to update.</param>
    /// <param name="policyDocument">The policy document that defines the role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutRolePolicyAsync(string policyName, string roleName, string policyDocument)
    {
        var request = new PutRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutRolePolicyAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [PutRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/PutRolePolicy)를 참조하십시오.

------
#### [ C\$1\$1 ]

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

```
bool AwsDoc::IAM::putRolePolicy(
        const Aws::String &roleName,
        const Aws::String &policyName,
        const Aws::String &policyDocument,
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iamClient(clientConfig);
    Aws::IAM::Model::PutRolePolicyRequest request;

    request.SetRoleName(roleName);
    request.SetPolicyName(policyName);
    request.SetPolicyDocument(policyDocument);

    Aws::IAM::Model::PutRolePolicyOutcome outcome = iamClient.PutRolePolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error putting policy on role. " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully put the role policy." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [PutRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/PutRolePolicy)를 참조하세요.

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

**AWS CLI**  
**IAM 역할에 권한 정책 연결**  
다음 `put-role-policy` 명령은 이름이 `Test-Role`인 역할에 권한 정책을 추가합니다.  

```
aws iam put-role-policy \
    --role-name Test-Role \
    --policy-name ExamplePolicy \
    --policy-document file://AdminPolicy.json
```
이 명령은 출력을 생성하지 않습니다.  
정책은 AdminPolicy.json** 파일에서 JSON 문서로 정의됩니다. (파일 이름과 확장자는 중요하지 않습니다.)  
신뢰 정책을 역할에 연결하려면 `update-assume-role-policy` 명령을 사용합니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [역할 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-role-policy.html)를 참조하세요.

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

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

```
import { PutRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const examplePolicyDocument = JSON.stringify({
  Version: "2012-10-17",
  Statement: [
    {
      Sid: "VisualEditor0",
      Effect: "Allow",
      Action: [
        "s3:ListBucketMultipartUploads",
        "s3:ListBucketVersions",
        "s3:ListBucket",
        "s3:ListMultipartUploadParts",
      ],
      Resource: "arn:aws:s3:::amzn-s3-demo-bucket",
    },
    {
      Sid: "VisualEditor1",
      Effect: "Allow",
      Action: [
        "s3:ListStorageLensConfigurations",
        "s3:ListAccessPointsForObjectLambda",
        "s3:ListAllMyBuckets",
        "s3:ListAccessPoints",
        "s3:ListJobs",
        "s3:ListMultiRegionAccessPoints",
      ],
      Resource: "*",
    },
  ],
});

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 * @param {string} policyName
 * @param {string} policyDocument
 */
export const putRolePolicy = async (roleName, policyName, policyDocument) => {
  const command = new PutRolePolicyCommand({
    RoleName: roleName,
    PolicyName: policyName,
    PolicyDocument: policyDocument,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [PutRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/PutRolePolicyCommand)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `FedTesterRolePolicy`라는 인라인 정책을 생성하고 이를 IAM 역할 `FedTesterRole`에 포함합니다. 동일한 이름의 인라인 정책이 이미 존재하는 경우 해당 정책을 덮어씁니다. JSON 정책 내용은 `FedTesterPolicy.json` 파일에서 가져옵니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 파라미터를 사용해야 합니다.**  

```
Write-IAMRolePolicy -RoleName FedTesterRole -PolicyName FedTesterRolePolicy -PolicyDocument (Get-Content -Raw FedTesterPolicy.json)
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [PutRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `FedTesterRolePolicy`라는 인라인 정책을 생성하고 이를 IAM 역할 `FedTesterRole`에 포함합니다. 동일한 이름의 인라인 정책이 이미 존재하는 경우 해당 정책을 덮어씁니다. JSON 정책 내용은 `FedTesterPolicy.json` 파일에서 가져옵니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 파라미터를 사용해야 합니다.**  

```
Write-IAMRolePolicy -RoleName FedTesterRole -PolicyName FedTesterRolePolicy -PolicyDocument (Get-Content -Raw FedTesterPolicy.json)
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `PutUserPermissionsBoundary` 사용
<a name="iam_example_iam_PutUserPermissionsBoundary_section"></a>

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

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

**AWS CLI**  
**예제 1: IAM 사용자에게 사용자 지정 정책을 기반으로 권한 경계 적용**  
다음 `put-user-permissions-boundary` 예제는 `intern-boundary`라는 사용자 지정 정책을 지정된 IAM 사용자에 대한 권한 경계로 적용합니다.  

```
aws iam put-user-permissions-boundary \
    --permissions-boundary arn:aws:iam::123456789012:policy/intern-boundary \
    --user-name intern
```
이 명령은 출력을 생성하지 않습니다.  
**예제 2: AWS 관리형 정책을 기반으로 IAM 사용자에게 권한 경계 적용**  
다음 `put-user-permissions-boundary` 예제에서는 라는 AWS 관리형 폴리시를 지정된 IAM 사용자의 권한 경계`PowerUserAccess`로 적용합니다.  

```
aws iam put-user-permissions-boundary \
    --permissions-boundary arn:aws:iam::aws:policy/PowerUserAccess \
    --user-name developer
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 자격 증명 권한 추가 및 제거](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutUserPermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-user-permissions-boundary.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 사용자의 권한 경계를 설정하는 방법을 보여줍니다. AWS 관리형 정책 또는 사용자 지정 정책을 권한 경계로 설정할 수 있습니다. **   

```
Set-IAMUserPermissionsBoundary -UserName joe -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [PutUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 사용자의 권한 경계를 설정하는 방법을 보여줍니다. AWS 관리형 정책 또는 사용자 지정 정책을 권한 경계로 설정할 수 있습니다. **   

```
Set-IAMUserPermissionsBoundary -UserName joe -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

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

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

**AWS CLI**  
**IAM 사용자에게 정책 연결**  
다음 `put-user-policy` 명령은 정책을 이름이 `Bob`인 IAM 사용자에게 연결합니다.  

```
aws iam put-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy \
    --policy-document file://AdminPolicy.json
```
이 명령은 출력을 생성하지 않습니다.  
정책은 AdminPolicy.json** 파일에서 JSON 문서로 정의됩니다. (파일 이름과 확장자는 중요하지 않습니다.)  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 자격 증명 권한 추가 및 제거](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [PutUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-user-policy.html)를 참조하세요.

------
#### [ Go ]

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

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `EC2AccessPolicy`라는 인라인 정책을 생성하고 이를 IAM 사용자 `Bob`에게 포함합니다. 동일한 이름의 인라인 정책이 이미 존재하는 경우 해당 정책을 덮어씁니다. JSON 정책 내용은 `EC2AccessPolicy.json` 파일에서 가져옵니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 파라미터를 사용해야 합니다.**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [PutUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `EC2AccessPolicy`라는 인라인 정책을 생성하고 이를 IAM 사용자 `Bob`에게 포함합니다. 동일한 이름의 인라인 정책이 이미 존재하는 경우 해당 정책을 덮어씁니다. JSON 정책 내용은 `EC2AccessPolicy.json` 파일에서 가져옵니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 파라미터를 사용해야 합니다.**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [PutUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Ruby ]

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

```
  # Creates an inline policy for a specified user.
  # @param username [String] The name of the IAM user.
  # @param policy_name [String] The name of the policy to create.
  # @param policy_document [String] The JSON policy document.
  # @return [Boolean]
  def create_user_policy(username, policy_name, policy_document)
    @iam_client.put_user_policy({
                                  user_name: username,
                                  policy_name: policy_name,
                                  policy_document: policy_document
                                })
    @logger.info("Policy #{policy_name} created for user #{username}.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't create policy #{policy_name} for user #{username}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    false
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)를 참조하십시오.

------
#### [ Swift ]

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

```
import AWSIAM
import AWSS3


    func putUserPolicy(policyDocument: String, policyName: String, user: IAMClientTypes.User) async throws {
        let input = PutUserPolicyInput(
            policyDocument: policyDocument,
            policyName: policyName,
            userName: user.userName
        )
        do {
            _ = try await iamClient.putUserPolicy(input: input)
        } catch {
            print("ERROR: putUserPolicy:", dump(error))
            throw error
        }
    }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [PutUserPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/putuserpolicy(input:))를 참조하세요.

------

# CLI로 `RemoveClientIdFromOpenIdConnectProvider` 사용
<a name="iam_example_iam_RemoveClientIdFromOpenIdConnectProvider_section"></a>

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

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

**AWS CLI**  
**지정된 IAM OpenID Connect 제공업체에 등록된 클라이언트 ID 목록에서 지정된 클라이언트 ID 제거**  
이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com`인 IAM OIDC 제공업체와 연결된 클라이언트 ID 목록에서 클라이언트 ID `My-TestApp-3`을 제거합니다.  

```
aws iam remove-client-id-from-open-id-connect-provider
    --client-id My-TestApp-3 \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM에서 OIDC(OpenID Connect) ID 제공업체 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [RemoveClientIdFromOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/remove-client-id-from-open-id-connect-provider.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com`인 IAM OIDC 제공업체와 연결된 클라이언트 ID 목록에서 클라이언트 ID `My-TestApp-3`을 제거합니다.**  

```
Remove-IAMClientIDFromOpenIDConnectProvider -ClientID My-TestApp-3 -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [RemoveClientIdFromOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com`인 IAM OIDC 제공업체와 연결된 클라이언트 ID 목록에서 클라이언트 ID `My-TestApp-3`을 제거합니다.**  

```
Remove-IAMClientIDFromOpenIDConnectProvider -ClientID My-TestApp-3 -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RemoveClientIdFromOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `RemoveRoleFromInstanceProfile` 사용
<a name="iam_example_iam_RemoveRoleFromInstanceProfile_section"></a>

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

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

**AWS CLI**  
**인스턴스 프로파일에서 역할 제거**  
다음 `remove-role-from-instance-profile` 명령은 이름이 `ExampleInstanceProfile`인 인스턴스 프로파일에서 이름이 `Test-Role`인 역할을 제거합니다.  

```
aws iam remove-role-from-instance-profile \
    --instance-profile-name ExampleInstanceProfile \
    --role-name Test-Role
```
자세한 내용은 **AWS IAM 사용 설명서의 [인스턴스 프로파일 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [RemoveRoleFromInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/remove-role-from-instance-profile.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `MyNewRole`이라는 EC2 인스턴스 프로파일에서 `MyNewRole`이라는 역할을 삭제합니다. IAM 콘솔에서 생성되는 인스턴스 프로파일은 이 예제와 같이 항상 역할과 동일한 이름을 갖습니다. API 또는 CLI에서 생성하는 경우 서로 다른 이름을 가질 수 있습니다.**  

```
Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyNewRole -RoleName MyNewRole -Force
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `MyNewRole`이라는 EC2 인스턴스 프로파일에서 `MyNewRole`이라는 역할을 삭제합니다. IAM 콘솔에서 생성되는 인스턴스 프로파일은 이 예제와 같이 항상 역할과 동일한 이름을 갖습니다. API 또는 CLI에서 생성하는 경우 서로 다른 이름을 가질 수 있습니다.**  

```
Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyNewRole -RoleName MyNewRole -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `RemoveUserFromGroup` 사용
<a name="iam_example_iam_RemoveUserFromGroup_section"></a>

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

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

**AWS CLI**  
**IAM 그룹에서 사용자 제거**  
다음 `remove-user-from-group` 명령은 이름이 `Admins`인 IAM 그룹에서 이름이 `Bob`인 사용자를 제거합니다.  

```
aws iam remove-user-from-group \
    --user-name Bob \
    --group-name Admins
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 그룹에서 사용자 추가 및 제거](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_add-remove-users.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [RemoveUserFromGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/remove-user-from-group.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 그룹 `Testers`에서 IAM 사용자 `Bob`을 제거합니다.**  

```
Remove-IAMUserFromGroup -GroupName Testers -UserName Bob
```
**예제 2: 이 예제는 IAM 사용자 `Theresa`가 구성원으로 속한 그룹을 찾은 다음 해당 그룹에서 `Theresa`를 제거합니다.**  

```
$groups = Get-IAMGroupForUser -UserName Theresa 
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName Theresa -Force }
```
**예제 3: 이 예제는 `Testers` 그룹에서 IAM 사용자 `Bob`을 제거하는 다른 방법을 보여줍니다.**  

```
Get-IAMGroupForUser -UserName Bob | Remove-IAMUserFromGroup -UserName Bob -GroupName Testers -Force
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [RemoveUserFromGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 그룹 `Testers`에서 IAM 사용자 `Bob`을 제거합니다.**  

```
Remove-IAMUserFromGroup -GroupName Testers -UserName Bob
```
**예제 2: 이 예제는 IAM 사용자 `Theresa`가 구성원으로 속한 그룹을 찾은 다음 해당 그룹에서 `Theresa`를 제거합니다.**  

```
$groups = Get-IAMGroupForUser -UserName Theresa 
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName Theresa -Force }
```
**예제 3: 이 예제는 `Testers` 그룹에서 IAM 사용자 `Bob`을 제거하는 다른 방법을 보여줍니다.**  

```
Get-IAMGroupForUser -UserName Bob | Remove-IAMUserFromGroup -UserName Bob -GroupName Testers -Force
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [RemoveUserFromGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `ResyncMfaDevice` 사용
<a name="iam_example_iam_ResyncMfaDevice_section"></a>

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

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

**AWS CLI**  
**MFA 디바이스 동기화**  
다음 `resync-mfa-device` 예제는 IAM 사용자 `Bob`과 연결되어 있고 ARN이 `arn:aws:iam::123456789012:mfa/BobsMFADevice`인 MFA 디바이스를 두 개의 인증 코드를 제공한 인증 프로그램과 동기화합니다.  

```
aws iam resync-mfa-device \
    --user-name Bob \
    --serial-number arn:aws:iam::210987654321:mfa/BobsMFADevice \
    --authentication-code1 123456 \
    --authentication-code2 987654
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [AWS에서 다중 인증(MFA) 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [ResyncMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/resync-mfa-device.html)를 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 사용자 `Bob`과 연결되어 있고 ARN이 `arn:aws:iam::123456789012:mfa/bob`인 MFA 디바이스를 두 개의 인증 코드를 제공한 인증 프로그램과 동기화합니다.**  

```
Sync-IAMMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/theresa -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Bob
```
**예제 2: 이 예제는 IAM 사용자 `Theresa`와 연결된 IAM MFA 디바이스를 일련 번호가 `ABCD12345678`이고 두 개의 인증 코드를 제공한 물리적 디바이스와 동기화합니다.**  

```
Sync-IAMMFADevice -SerialNumber ABCD12345678 -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Theresa
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [ResyncMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 사용자 `Bob`과 연결되어 있고 ARN이 `arn:aws:iam::123456789012:mfa/bob`인 MFA 디바이스를 두 개의 인증 코드를 제공한 인증 프로그램과 동기화합니다.**  

```
Sync-IAMMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/theresa -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Bob
```
**예제 2: 이 예제는 IAM 사용자 `Theresa`와 연결된 IAM MFA 디바이스를 일련 번호가 `ABCD12345678`이고 두 개의 인증 코드를 제공한 물리적 디바이스와 동기화합니다.**  

```
Sync-IAMMFADevice -SerialNumber ABCD12345678 -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Theresa
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [ResyncMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

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

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [정책 관리](iam_example_iam_Scenario_PolicyManagement_section.md) 
+  [정책 버전 롤백](iam_example_iam_Scenario_RollbackPolicyVersion_section.md) 

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

**AWS CLI**  
**지정된 정책의 지정된 버전을 정책의 기본 버전으로 설정**  
이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyPolicy`인 정책의 `v2` 버전을 기본 활성 버전으로 설정합니다.  

```
aws iam set-default-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --version-id v2
```
자세한 내용은 *AWS IAM 사용 설명서*에서 [IAM의 정책 및 권한](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [SetDefaultPolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/set-default-policy-version.html)을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyPolicy`인 정책의 `v2` 버전을 기본 활성 버전으로 설정합니다.**  

```
Set-IAMDefaultPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -VersionId v2
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [SetDefaultPolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:policy/MyPolicy`인 정책의 `v2` 버전을 기본 활성 버전으로 설정합니다.**  

```
Set-IAMDefaultPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -VersionId v2
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [SetDefaultPolicyVersion](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_iam->setdefaultpolicyversion(
          iv_policyarn = iv_policy_arn
          iv_versionid = iv_version_id ).
        MESSAGE 'Default policy version set successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy or version does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iaminvalidinputex.
        MESSAGE 'Invalid input provided.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 [AWS SDK for SAP ABAP API 참조](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)의 *SetDefaultPolicyVersion*을 참조하세요.

------

# CLI로 `TagRole` 사용
<a name="iam_example_iam_TagRole_section"></a>

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

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

**AWS CLI**  
**역할에 태그 추가**  
다음 `tag-role` 명령은 지정된 역할에 Department 이름이 포함된 태그를 추가합니다.  

```
aws iam tag-role --role-name my-role \
    --tags '{"Key": "Department", "Value": "Accounting"}'
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 리소스 태그 지정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [TagRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-role.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ID 관리 서비스의 역할에 태그를 추가합니다.**  

```
Add-IAMRoleTag -RoleName AdminRoleacess -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [TagRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ID 관리 서비스의 역할에 태그를 추가합니다.**  

```
Add-IAMRoleTag -RoleName AdminRoleacess -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [TagRole](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `TagUser` 사용
<a name="iam_example_iam_TagUser_section"></a>

다음 코드 예시는 `TagUser`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**사용자에게 태그 추가**  
다음 `tag-user` 명령은 지정된 사용자에게 연관된 Department가 포함된 태그를 추가합니다.  

```
aws iam tag-user \
    --user-name alice \
    --tags '{"Key": "Department", "Value": "Accounting"}'
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 리소스 태그 지정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [TagUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-user.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ID 관리 서비스의 사용자에게 태그를 추가합니다.**  

```
Add-IAMUserTag -UserName joe -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [TagUser](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ID 관리 서비스의 사용자에게 태그를 추가합니다.**  

```
Add-IAMUserTag -UserName joe -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [TagUser](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `UntagRole` 사용
<a name="iam_example_iam_UntagRole_section"></a>

다음 코드 예시는 `UntagRole`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**역할에서 태그 제거**  
다음 `untag-role` 명령은 지정된 역할에서 키 이름이 'Department'인 모든 태그를 제거합니다.  

```
aws iam untag-role \
    --role-name my-role \
    --tag-keys Department
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 리소스 태그 지정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UntagRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-role.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 태그 키가 'abac'인 'MyRoleName' 역할에서 태그를 제거합니다. 여러 태그를 제거하려면 쉼표로 구분된 태그 키 목록을 제공합니다.**  

```
Remove-IAMRoleTag -RoleName MyRoleName -TagKey "abac","xyzw"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UntagRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 태그 키가 'abac'인 'MyRoleName' 역할에서 태그를 제거합니다. 여러 태그를 제거하려면 쉼표로 구분된 태그 키 목록을 제공합니다.**  

```
Remove-IAMRoleTag -RoleName MyRoleName -TagKey "abac","xyzw"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UntagRole](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `UntagUser` 사용
<a name="iam_example_iam_UntagUser_section"></a>

다음 코드 예시는 `UntagUser`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**사용자에게서 태그 제거**  
다음 `untag-user` 명령은 지정된 사용자에게서 키 이름이 'Department'인 모든 태그를 제거합니다.  

```
aws iam untag-user \
    --user-name alice \
    --tag-keys Department
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 리소스 태그 지정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UntagUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-user.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 태그 키가 'abac' 및 'xyzw'인 'joe'라는 사용자에게서 태그를 제거합니다. 여러 태그를 제거하려면 쉼표로 구분된 태그 키 목록을 제공합니다.**  

```
Remove-IAMUserTag -UserName joe -TagKey "abac","xyzw"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UntagUser](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 태그 키가 'abac' 및 'xyzw'인 'joe'라는 사용자에게서 태그를 제거합니다. 여러 태그를 제거하려면 쉼표로 구분된 태그 키 목록을 제공합니다.**  

```
Remove-IAMUserTag -UserName joe -TagKey "abac","xyzw"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UntagUser](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `UpdateAccessKey` 함께 사용
<a name="iam_example_iam_UpdateAccessKey_section"></a>

다음 코드 예시는 `UpdateAccessKey`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [ 액세스 키 관리](iam_example_iam_Scenario_ManageAccessKeys_section.md) 

------
#### [ Bash ]

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function iam_update_access_key
#
# This function can activate or deactivate an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to update.
#       -a            -- Activate the selected access key.
#       -d            -- Deactivate the selected access key.
#
# Example:
#       # To deactivate the selected access key for IAM user Bob
#       iam_update_access_key -u Bob -k AKIAIOSFODNN7EXAMPLE -d 
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_update_access_key() {
  local user_name access_key status response
  local option OPTARG # Required to use getopts command in a function.
  local activate_flag=false deactivate_flag=false

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_update_access_key"
    echo "Updates the status of an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to update."
    echo "  -a              Activate the access key."
    echo "  -d              Deactivate the access key."
    echo ""
  }

  # Retrieve the calling parameters.
    while getopts "u:k:adh" option; do
      case "${option}" in
        u) user_name="${OPTARG}" ;;
        k) access_key="${OPTARG}" ;;
        a) activate_flag=true ;;
        d) deactivate_flag=true ;;
        h)
          usage
          return 0
          ;;
        \?)
          echo "Invalid parameter"
          usage
          return 1
          ;;
      esac
    done
    export OPTIND=1
  
   # Validate input parameters
    if [[ -z "$user_name" ]]; then
      errecho "ERROR: You must provide a username with the -u parameter."
      usage
      return 1
    fi
  
    if [[ -z "$access_key" ]]; then
      errecho "ERROR: You must provide an access key with the -k parameter."
      usage
      return 1
    fi

    # Ensure that only -a or -d is specified
    if [[ "$activate_flag" == true && "$deactivate_flag" == true ]]; then
      errecho "ERROR: You cannot specify both -a (activate) and -d (deactivate) at the same time."
      usage
      return 1
    fi
  
    # If neither -a nor -d is provided, return an error
    if [[ "$activate_flag" == false && "$deactivate_flag" == false ]]; then
      errecho "ERROR: You must specify either -a (activate) or -d (deactivate)."
      usage
      return 1
    fi

    # Determine the status based on the flag
    if [[ "$activate_flag" == true ]]; then
      status="Active"
    elif [[ "$deactivate_flag" == true ]]; then
      status="Inactive"
    fi
  
    iecho "Parameters:\n"
    iecho "    Username:   $user_name"
    iecho "    Access key: $access_key"
    iecho "    New status: $status"
    iecho ""
  
    # Update the access key status
    response=$(aws iam update-access-key \
      --user-name "$user_name" \
      --access-key-id "$access_key" \
      --status "$status" 2>&1)
  
    local error_code=${?}
  
    if [[ $error_code -ne 0 ]]; then
      aws_cli_error_log $error_code
      errecho "ERROR: AWS reports update-access-key operation failed.\n$response"
      return 1
    fi
  
    iecho "update-access-key response: $response"
    iecho
  
    return 0
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/UpdateAccessKey)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
bool AwsDoc::IAM::updateAccessKey(const Aws::String &userName,
                                  const Aws::String &accessKeyID,
                                  Aws::IAM::Model::StatusType status,
                                  const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::UpdateAccessKeyRequest request;
    request.SetUserName(userName);
    request.SetAccessKeyId(accessKeyID);
    request.SetStatus(status);

    auto outcome = iam.UpdateAccessKey(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated status of access key "
                  << accessKeyID << " for user " << userName << std::endl;
    }
    else {
        std::cerr << "Error updated status of access key " << accessKeyID <<
                  " for user " << userName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [UpdateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/UpdateAccessKey)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**IAM 사용자의 액세스 키를 활성화 또는 비활성화**  
다음 `update-access-key` 명령은 이름이 `Bob`인 IAM 사용자의 지정된 액세스 키(액세스 키 ID 및 시크릿 액세스 키)를 비활성화합니다.  

```
aws iam update-access-key \
    --access-key-id AKIAIOSFODNN7EXAMPLE \
    --status Inactive \
    --user-name Bob
```
이 명령은 출력을 생성하지 않습니다.  
키를 비활성화하면 프로그래밍 방식 액세스에 사용할 수 없습니다 AWS. 하지만 키는 계속 사용할 수 있고 다시 활성화할 수 있습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자의 액세스 키 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateAccessKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-access-key.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.StatusType;
import software.amazon.awssdk.services.iam.model.UpdateAccessKeyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;

/**
 * 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 UpdateAccessKey {

    private static StatusType statusType;

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <username> <accessId> <status>\s

                Where:
                    username - The name of the user whose key you want to update.\s
                    accessId - The access key ID of the secret access key you want to update.\s
                    status - The status you want to assign to the secret access key.\s
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String username = args[0];
        String accessId = args[1];
        String status = args[2];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        updateKey(iam, username, accessId, status);
        System.out.println("Done");
        iam.close();
    }

    public static void updateKey(IamClient iam, String username, String accessId, String status) {
        try {
            if (status.toLowerCase().equalsIgnoreCase("active")) {
                statusType = StatusType.ACTIVE;
            } else if (status.toLowerCase().equalsIgnoreCase("inactive")) {
                statusType = StatusType.INACTIVE;
            } else {
                statusType = StatusType.UNKNOWN_TO_SDK_VERSION;
            }

            UpdateAccessKeyRequest request = UpdateAccessKeyRequest.builder()
                    .accessKeyId(accessId)
                    .userName(username)
                    .status(statusType)
                    .build();

            iam.updateAccessKey(request);
            System.out.printf("Successfully updated the status of access key %s to" +
                    "status %s for user %s", accessId, status, username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [UpdateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/UpdateAccessKey)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
액세스 키를 업데이트합니다.  

```
import {
  UpdateAccessKeyCommand,
  IAMClient,
  StatusType,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} userName
 * @param {string} accessKeyId
 */
export const updateAccessKey = (userName, accessKeyId) => {
  const command = new UpdateAccessKeyCommand({
    AccessKeyId: accessKeyId,
    Status: StatusType.Inactive,
    UserName: userName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-updating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UpdateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UpdateAccessKeyCommand)를 참조하십시오.

**SDK for JavaScript (v2)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  AccessKeyId: "ACCESS_KEY_ID",
  Status: "Active",
  UserName: "USER_NAME",
};

iam.updateAccessKey(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-updating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UpdateAccessKey](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/UpdateAccessKey)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자에 대한 액세스 키 `AKIAIOSFODNN7EXAMPLE`의 상태를 `Inactive`로 변경합니다.**  

```
Update-IAMAccessKey -UserName Bob -AccessKeyId AKIAIOSFODNN7EXAMPLE -Status Inactive
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateAccessKey](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자에 대한 액세스 키 `AKIAIOSFODNN7EXAMPLE`의 상태를 `Inactive`로 변경합니다.**  

```
Update-IAMAccessKey -UserName Bob -AccessKeyId AKIAIOSFODNN7EXAMPLE -Status Inactive
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateAccessKey](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def update_key(user_name, key_id, activate):
    """
    Updates the status of a key.

    :param user_name: The user that owns the key.
    :param key_id: The ID of the key to update.
    :param activate: When True, the key is activated. Otherwise, the key is deactivated.
    """

    try:
        key = iam.User(user_name).AccessKey(key_id)
        if activate:
            key.activate()
        else:
            key.deactivate()
        logger.info("%s key %s.", "Activated" if activate else "Deactivated", key_id)
    except ClientError:
        logger.exception(
            "Couldn't %s key %s.", "Activate" if activate else "Deactivate", key_id
        )
        raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [UpdateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/UpdateAccessKey)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_iam->updateaccesskey(
          iv_accesskeyid = iv_access_key_id
          iv_status = iv_status
          iv_username = iv_user_name ).
        MESSAGE 'Access key updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Access key or user does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 [AWS SDK for SAP ABAP API 참조](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)의 *UpdateAccessKey*를 참조하세요.

------

# CLI로 `UpdateAccountPasswordPolicy` 사용
<a name="iam_example_iam_UpdateAccountPasswordPolicy_section"></a>

다음 코드 예시는 `UpdateAccountPasswordPolicy`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**현재 계정 암호 정책 설정 또는 변경**  
다음 `update-account-password-policy` 명령은 최소 8자 길이를 요구하고 암호에 하나 이상의 숫자를 요구하도록 암호 정책을 설정합니다.  

```
aws iam update-account-password-policy \
    --minimum-password-length 8 \
    --require-numbers
```
이 명령은 출력을 생성하지 않습니다.  
계정의 암호 정책 변경은 해당 계정의 IAM 사용자에 대해 새로 생성되는 모든 암호에 영향을 줍니다. 암호 정책 변경은 기존 암호에 영향을 주지 않습니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 사용자의 계정 암호 정책 설정](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateAccountPasswordPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-account-password-policy.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 계정의 암호 정책을 지정된 설정으로 업데이트합니다. 단, 명령에 포함되지 않은 파라미터는 수정되지 않은 채로 남아 있지 않습니다. 대신 기본값으로 재설정됩니다.**  

```
Update-IAMAccountPasswordPolicy -AllowUsersToChangePasswords $true -HardExpiry $false -MaxPasswordAge 90 -MinimumPasswordLength 8 -PasswordReusePrevention 20 -RequireLowercaseCharacters $true -RequireNumbers $true -RequireSymbols $true -RequireUppercaseCharacters $true
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 계정의 암호 정책을 지정된 설정으로 업데이트합니다. 단, 명령에 포함되지 않은 파라미터는 수정되지 않은 채로 남아 있지 않습니다. 대신 기본값으로 재설정됩니다.**  

```
Update-IAMAccountPasswordPolicy -AllowUsersToChangePasswords $true -HardExpiry $false -MaxPasswordAge 90 -MinimumPasswordLength 8 -PasswordReusePrevention 20 -RequireLowercaseCharacters $true -RequireNumbers $true -RequireSymbols $true -RequireUppercaseCharacters $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `UpdateAssumeRolePolicy` 사용
<a name="iam_example_iam_UpdateAssumeRolePolicy_section"></a>

다음 코드 예시는 `UpdateAssumeRolePolicy`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 역할의 신뢰 정책 업데이트**  
다음 `update-assume-role-policy` 명령은 `Test-Role`이라는 역할에 대한 신뢰 정책을 업데이트합니다.  

```
aws iam update-assume-role-policy \
    --role-name Test-Role \
    --policy-document file://Test-Role-Trust-Policy.json
```
이 명령은 출력을 생성하지 않습니다.  
신뢰 정책은 Test-Role-Trust-Policy.json** 파일에 JSON 문서로 정의됩니다. (파일 이름과 확장자는 중요하지 않습니다.) 신뢰 정책에서 위탁자를 지정해야 합니다.  
역할에 대한 권한 정책을 업데이트하려면 `put-role-policy` 명령을 사용합니다.  
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateAssumeRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-assume-role-policy.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 이름이 `ClientRole`인 IAM 역할을 새 신뢰 정책으로 업데이트하고, 그 내용은 `ClientRolePolicy.json` 파일에서 가져옵니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
Update-IAMAssumeRolePolicy -RoleName ClientRole -PolicyDocument (Get-Content -raw ClientRolePolicy.json)
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateAssumeRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 이름이 `ClientRole`인 IAM 역할을 새 신뢰 정책으로 업데이트하고, 그 내용은 `ClientRolePolicy.json` 파일에서 가져옵니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
Update-IAMAssumeRolePolicy -RoleName ClientRole -PolicyDocument (Get-Content -raw ClientRolePolicy.json)
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateAssumeRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `UpdateGroup` 사용
<a name="iam_example_iam_UpdateGroup_section"></a>

다음 코드 예시는 `UpdateGroup`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 그룹 이름 바꾸기**  
다음 `update-group` 명령은 IAM 그룹의 이름을 `Test`에서 `Test-1`로 변경합니다.  

```
aws iam update-group \
    --group-name Test \
    --new-group-name Test-1
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 그룹 이름 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_rename.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-group.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 그룹 이름을 `Testers`에서 `AppTesters`로 변경합니다.**  

```
Update-IAMGroup -GroupName Testers -NewGroupName AppTesters
```
**예제 2: 이 예제는 IAM 그룹 `AppTesters`의 경로를 `/Org1/Org2/`로 변경합니다. 그러면 그룹의 ARN이 `arn:aws:iam::123456789012:group/Org1/Org2/AppTesters`로 변경됩니다.**  

```
Update-IAMGroup -GroupName AppTesters -NewPath /Org1/Org2/
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateGroup](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 그룹 이름을 `Testers`에서 `AppTesters`로 변경합니다.**  

```
Update-IAMGroup -GroupName Testers -NewGroupName AppTesters
```
**예제 2: 이 예제는 IAM 그룹 `AppTesters`의 경로를 `/Org1/Org2/`로 변경합니다. 그러면 그룹의 ARN이 `arn:aws:iam::123456789012:group/Org1/Org2/AppTesters`로 변경됩니다.**  

```
Update-IAMGroup -GroupName AppTesters -NewPath /Org1/Org2/
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateGroup](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `UpdateLoginProfile` 사용
<a name="iam_example_iam_UpdateLoginProfile_section"></a>

다음 코드 예시는 `UpdateLoginProfile`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 사용자의 암호 업데이트**  
다음 `update-login-profile` 명령은 `Bob`이라는 IAM 사용자에 대한 새 암호를 생성합니다.  

```
aws iam update-login-profile \
    --user-name Bob \
    --password <password>
```
이 명령은 출력을 생성하지 않습니다.  
계정의 암호 정책을 설정하려면 `update-account-password-policy` 명령을 사용합니다. 새 암호가 계정 암호 정책을 위반하는 경우 명령은 `PasswordPolicyViolation` 오류를 반환합니다.  
계정 암호 정책에서 허용하는 경우 IAM 사용자는 `change-password` 명령을 사용하여 자신의 암호를 변경할 수 있습니다.  
암호를 안전한 위치에 저장합니다. 암호를 분실한 경우 복구가 불가능하며, `create-login-profile` 명령을 사용하여 암호를 새로 생성해야 합니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 암호 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-login-profile.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 사용자 `Bob`에 대한 새 임시 암호를 설정하고 사용자가 다음에 로그인할 때 암호를 변경하도록 요구합니다.**  

```
Update-IAMLoginProfile -UserName Bob -Password "P@ssw0rd1234" -PasswordResetRequired $true
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateLoginProfile](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 사용자 `Bob`에 대한 새 임시 암호를 설정하고 사용자가 다음에 로그인할 때 암호를 변경하도록 요구합니다.**  

```
Update-IAMLoginProfile -UserName Bob -Password "P@ssw0rd1234" -PasswordResetRequired $true
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `UpdateOpenIdConnectProviderThumbprint` 사용
<a name="iam_example_iam_UpdateOpenIdConnectProviderThumbprint_section"></a>

다음 코드 예시는 `UpdateOpenIdConnectProviderThumbprint`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**기존 서버 인증서 지문 목록을 새 목록으로 바꾸기**  
이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com`인 OIDC 제공업체에 대한 인증서 지문 목록을 업데이트하여 새 지문을 사용합니다.  

```
aws iam update-open-id-connect-provider-thumbprint \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com \
    --thumbprint-list 7359755EXAMPLEabc3060bce3EXAMPLEec4542a3
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM에서 OIDC(OpenID Connect) ID 제공업체 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateOpenIdConnectProviderThumbprint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-open-id-connect-provider-thumbprint.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com`인 OIDC 제공업체에 대한 인증서 지문 목록을 업데이트하여 새 지문을 사용합니다. OIDC 제공업체는 제공업체와 연결된 인증서가 변경될 때 새 값을 공유합니다.**  

```
Update-IAMOpenIDConnectProviderThumbprint -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com -ThumbprintList 7359755EXAMPLEabc3060bce3EXAMPLEec4542a3
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateOpenIdConnectProviderThumbprint](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com`인 OIDC 제공업체에 대한 인증서 지문 목록을 업데이트하여 새 지문을 사용합니다. OIDC 제공업체는 제공업체와 연결된 인증서가 변경될 때 새 값을 공유합니다.**  

```
Update-IAMOpenIDConnectProviderThumbprint -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com -ThumbprintList 7359755EXAMPLEabc3060bce3EXAMPLEec4542a3
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateOpenIdConnectProviderThumbprint](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `UpdateRole` 사용
<a name="iam_example_iam_UpdateRole_section"></a>

다음 코드 예시는 `UpdateRole`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 역할의 설명 또는 세션 기간 변경**  
다음 `update-role` 명령은 IAM 역할 `production-role`의 설명을 `Main production role`로 변경하고 최대 세션 기간을 12시간으로 설정합니다.  

```
aws iam update-role \
    --role-name production-role \
    --description 'Main production role' \
    --max-session-duration 43200
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [역할 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-role.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 역할 설명과 역할 세션을 요청할 수 있는 최대 세션 기간 값 (초)을 업데이트합니다.**  

```
Update-IAMRole -RoleName MyRoleName -Description "My testing role" -MaxSessionDuration 43200
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateRole](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 역할 설명과 역할 세션을 요청할 수 있는 최대 세션 기간 값 (초)을 업데이트합니다.**  

```
Update-IAMRole -RoleName MyRoleName -Description "My testing role" -MaxSessionDuration 43200
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateRole](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `UpdateRoleDescription` 사용
<a name="iam_example_iam_UpdateRoleDescription_section"></a>

다음 코드 예시는 `UpdateRoleDescription`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 역할의 설명 변경**  
다음 `update-role` 명령은 IAM 역할에 대한 설명을 `production-role`에서 `Main production role`로 변경합니다.  

```
aws iam update-role-description \
    --role-name production-role \
    --description 'Main production role'
```
출력:  

```
{
    "Role": {
        "Path": "/",
        "RoleName": "production-role",
        "RoleId": "AROA1234567890EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:role/production-role",
        "CreateDate": "2017-12-06T17:16:37+00:00",
        "AssumeRolePolicyDocument": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "AWS": "arn:aws:iam::123456789012:root"
                    },
                    "Action": "sts:AssumeRole",
                    "Condition": {}
                }
            ]
        },
        "Description": "Main production role"
    }
}
```
자세한 내용은 **AWS IAM 사용 설명서의 [역할 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateRoleDescription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-role-description.html)을 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 계정의 IAM 역할 설명을 업데이트합니다.**  

```
Update-IAMRoleDescription -RoleName MyRoleName -Description "My testing role"
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateRoleDescription](https://docs.aws.amazon.com/powershell/v4/reference)을 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 계정의 IAM 역할 설명을 업데이트합니다.**  

```
Update-IAMRoleDescription -RoleName MyRoleName -Description "My testing role"
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateRoleDescription](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------

# CLI로 `UpdateSamlProvider` 사용
<a name="iam_example_iam_UpdateSamlProvider_section"></a>

다음 코드 예시는 `UpdateSamlProvider`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**기존 SAML 제공업체에 대한 메타데이터 문서 업데이트**  
이 예제는 ARN이 `arn:aws:iam::123456789012:saml-provider/SAMLADFS`인 IAM의 SAML 제공업체를 `SAMLMetaData.xml` 파일의 새 SAML 메타데이터 문서로 업데이트합니다.  

```
aws iam update-saml-provider \
    --saml-metadata-document file://SAMLMetaData.xml \
    --saml-provider-arn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
출력:  

```
{
    "SAMLProviderArn": "arn:aws:iam::123456789012:saml-provider/SAMLADFS"
}
```
자세한 내용은 *AWS IAM 사용 설명서*의 [IAM SAML 자격 증명 공급자 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateSamlProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-saml-provider.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:saml-provider/SAMLADFS`인 IAM의 SAML 제공업체를 `SAMLMetaData.xml` 파일의 새 SAML 메타데이터 문서로 업데이트합니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
Update-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateSamlProvider](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 ARN이 `arn:aws:iam::123456789012:saml-provider/SAMLADFS`인 IAM의 SAML 제공업체를 `SAMLMetaData.xml` 파일의 새 SAML 메타데이터 문서로 업데이트합니다. JSON 파일의 내용을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
Update-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `UpdateServerCertificate` 함께 사용
<a name="iam_example_iam_UpdateServerCertificate_section"></a>

다음 코드 예시는 `UpdateServerCertificate`의 사용 방법을 보여 줍니다.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
bool AwsDoc::IAM::updateServerCertificate(const Aws::String &currentCertificateName,
                                          const Aws::String &newCertificateName,
                                          const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::UpdateServerCertificateRequest request;
    request.SetServerCertificateName(currentCertificateName);
    request.SetNewServerCertificateName(newCertificateName);

    auto outcome = iam.UpdateServerCertificate(request);
    bool result = true;
    if (outcome.IsSuccess()) {
        std::cout << "Server certificate " << currentCertificateName
                  << " successfully renamed as " << newCertificateName
                  << std::endl;
    }
    else {
        if (outcome.GetError().GetErrorType() != Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
            std::cerr << "Error changing name of server certificate " <<
                      currentCertificateName << " to " << newCertificateName << ":" <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Certificate '" << currentCertificateName
                      << "' not found." << std::endl;
        }
    }

    return result;
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [UpdateServerCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/UpdateServerCertificate)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
** AWS 계정에서 서버 인증서의 경로 또는 이름을 변경하려면**  
다음 `update-server-certificate` 명령은 인증서의 이름을 `myServerCertificate`에서 `myUpdatedServerCertificate`로 변경합니다. 또한 Amazon CloudFront 서비스에서 액세스할 수 있도록 경로를 `/cloudfront/`로 변경합니다. 이 명령은 출력을 생성하지 않습니다. `list-server-certificates` 명령을 실행하여 업데이트 결과를 볼 수 있습니다.  

```
aws-iam update-server-certificate \
    --server-certificate-name myServerCertificate \
    --new-server-certificate-name myUpdatedServerCertificate \
    --new-path /cloudfront/
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM에서 서버 인증서 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-server-certificate.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
서버 인증서를 업데이트합니다.  

```
import { UpdateServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} currentName
 * @param {string} newName
 */
export const updateServerCertificate = (currentName, newName) => {
  const command = new UpdateServerCertificateCommand({
    ServerCertificateName: currentName,
    NewServerCertificateName: newName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-updating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UpdateServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UpdateServerCertificateCommand)를 참조하십시오.

**SDK for JavaScript (v2)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  ServerCertificateName: "CERTIFICATE_NAME",
  NewServerCertificateName: "NEW_CERTIFICATE_NAME",
};

iam.updateServerCertificate(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-updating)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UpdateServerCertificate](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/UpdateServerCertificate)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 인증서 이름을 `MyServerCertificate`에서 `MyRenamedServerCertificate`로 변경합니다.**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewServerCertificateName MyRenamedServerCertificate
```
**예제 2: 이 예제는 `MyServerCertificate`라는 인증서를 /Org1/Org2/ 경로로 이동합니다. 그러면 리소스의 ARN이 `arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate`로 변경됩니다.**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewPath /Org1/Org2/
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 인증서 이름을 `MyServerCertificate`에서 `MyRenamedServerCertificate`로 변경합니다.**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewServerCertificateName MyRenamedServerCertificate
```
**예제 2: 이 예제는 `MyServerCertificate`라는 인증서를 /Org1/Org2/ 경로로 이동합니다. 그러면 리소스의 ARN이 `arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate`로 변경됩니다.**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewPath /Org1/Org2/
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
서버 인증서를 나열하고, 업데이트하고, 삭제합니다.  

```
class ServerCertificateManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'ServerCertificateManager'
  end

  # Creates a new server certificate.
  # @param name [String] the name of the server certificate
  # @param certificate_body [String] the contents of the certificate
  # @param private_key [String] the private key contents
  # @return [Boolean] returns true if the certificate was successfully created
  def create_server_certificate(name, certificate_body, private_key)
    @iam_client.upload_server_certificate({
                                            server_certificate_name: name,
                                            certificate_body: certificate_body,
                                            private_key: private_key
                                          })
    true
  rescue Aws::IAM::Errors::ServiceError => e
    puts "Failed to create server certificate: #{e.message}"
    false
  end

  # Lists available server certificate names.
  def list_server_certificate_names
    response = @iam_client.list_server_certificates

    if response.server_certificate_metadata_list.empty?
      @logger.info('No server certificates found.')
      return
    end

    response.server_certificate_metadata_list.each do |certificate_metadata|
      @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}")
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing server certificates: #{e.message}")
  end

  # Updates the name of a server certificate.
  def update_server_certificate_name(current_name, new_name)
    @iam_client.update_server_certificate(
      server_certificate_name: current_name,
      new_server_certificate_name: new_name
    )
    @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error updating server certificate name: #{e.message}")
    false
  end

  # Deletes a server certificate.
  def delete_server_certificate(name)
    @iam_client.delete_server_certificate(server_certificate_name: name)
    @logger.info("Server certificate '#{name}' deleted.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting server certificate: #{e.message}")
    false
  end
end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [UpdateServerCertificate](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/UpdateServerCertificate)를 참조하세요.

------

# CLI로 `UpdateSigningCertificate` 사용
<a name="iam_example_iam_UpdateSigningCertificate_section"></a>

다음 코드 예시는 `UpdateSigningCertificate`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 사용자의 서명 인증서 활성화 또는 비활성**  
다음 `update-signing-certificate` 명령은 `Bob`이라는 IAM 사용자에 대해 지정된 서명 인증서를 비활성화합니다.  

```
aws iam update-signing-certificate \
    --certificate-id TA7SMP42TDN5Z26OBPJE7EXAMPLE \
    --status Inactive \
    --user-name Bob
```
서명 인증서의 ID를 가져오려면 `list-signing-certificates` 명령을 사용합니다.  
자세한 내용은 **Amazon EC2 사용 설명서의 [서명 인증서 관리](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-up-ami-tools.html#ami-tools-managing-certs)를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateSigningCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-signing-certificate.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자와 연결되어 있고 인증서 ID가 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU`인 인증서를 업데이트하여 비활성으로 표시합니다.**  

```
Update-IAMSigningCertificate -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU -UserName Bob -Status Inactive
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateSigningCertificate](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 `Bob`이라는 IAM 사용자와 연결되어 있고 인증서 ID가 `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU`인 인증서를 업데이트하여 비활성으로 표시합니다.**  

```
Update-IAMSigningCertificate -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU -UserName Bob -Status Inactive
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# AWS SDK 또는 CLI와 `UpdateUser` 함께 사용
<a name="iam_example_iam_UpdateUser_section"></a>

다음 코드 예시는 `UpdateUser`의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [읽기 전용 및 읽기-쓰기 사용자 생성](iam_example_iam_Scenario_UserPolicies_section.md) 

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
bool AwsDoc::IAM::updateUser(const Aws::String &currentUserName,
                             const Aws::String &newUserName,
                             const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::UpdateUserRequest request;
    request.SetUserName(currentUserName);
    request.SetNewUserName(newUserName);

    auto outcome = iam.UpdateUser(request);
    if (outcome.IsSuccess()) {
        std::cout << "IAM user " << currentUserName <<
                  " successfully updated with new user name " << newUserName <<
                  std::endl;
    }
    else {
        std::cerr << "Error updating user name for IAM user " << currentUserName <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [UpdateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/UpdateUser)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**IAM 사용자의 이름 변경**  
다음 `update-user` 명령은 IAM 사용자의 이름을 `Bob`에서 `Robert`로 변경합니다.  

```
aws iam update-user \
    --user-name Bob \
    --new-user-name Robert
```
이 명령은 출력을 생성하지 않습니다.  
자세한 내용은 **AWS IAM 사용 설명서의 [IAM 사용자 그룹 이름 변경](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_rename.html)을 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UpdateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-user.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.UpdateUserRequest;

/**
 * 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 UpdateUser {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <curName> <newName>\s

                Where:
                    curName - The current user name.\s
                    newName - An updated user name.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String curName = args[0];
        String newName = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        updateIAMUser(iam, curName, newName);
        System.out.println("Done");
        iam.close();
    }

    public static void updateIAMUser(IamClient iam, String curName, String newName) {
        try {
            UpdateUserRequest request = UpdateUserRequest.builder()
                    .userName(curName)
                    .newUserName(newName)
                    .build();

            iam.updateUser(request);
            System.out.printf("Successfully updated user to username %s", newName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [UpdateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/UpdateUser)를 참조하십시오.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
사용자를 업데이트합니다.  

```
import { UpdateUserCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} currentUserName
 * @param {string} newUserName
 */
export const updateUser = (currentUserName, newUserName) => {
  const command = new UpdateUserCommand({
    UserName: currentUserName,
    NewUserName: newUserName,
  });

  return client.send(command);
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-updating-users)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UpdateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UpdateUserCommand)를 참조하십시오.

**SDK for JavaScript (v2)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
  NewUserName: process.argv[3],
};

iam.updateUser(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-updating-users)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UpdateUser](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/UpdateUser)를 참조하십시오.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun updateIAMUser(
    curName: String?,
    newName: String?,
) {
    val request =
        UpdateUserRequest {
            userName = curName
            newUserName = newName
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.updateUser(request)
        println("Successfully updated user to $newName")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [UpdateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 IAM 사용자 이름을 `Bob`에서 `Robert`로 변경합니다.**  

```
Update-IAMUser -UserName Bob -NewUserName Robert
```
**예제 2: 이 예제는 IAM 사용자 `Bob`의 경로를 `/Org1/Org2/`로 변경합니다. 그러면 해당 사용자의 ARN이 `arn:aws:iam::123456789012:user/Org1/Org2/bob`으로 효과적으로 변경됩니다.**  

```
Update-IAMUser -UserName Bob -NewPath /Org1/Org2/
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UpdateUser](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 IAM 사용자 이름을 `Bob`에서 `Robert`로 변경합니다.**  

```
Update-IAMUser -UserName Bob -NewUserName Robert
```
**예제 2: 이 예제는 IAM 사용자 `Bob`의 경로를 `/Org1/Org2/`로 변경합니다. 그러면 해당 사용자의 ARN이 `arn:aws:iam::123456789012:user/Org1/Org2/bob`으로 효과적으로 변경됩니다.**  

```
Update-IAMUser -UserName Bob -NewPath /Org1/Org2/
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UpdateUser](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/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
def update_user(user_name, new_user_name):
    """
    Updates a user's name.

    :param user_name: The current name of the user to update.
    :param new_user_name: The new name to assign to the user.
    :return: The updated user.
    """
    try:
        user = iam.User(user_name)
        user.update(NewUserName=new_user_name)
        logger.info("Renamed %s to %s.", user_name, new_user_name)
    except ClientError:
        logger.exception("Couldn't update name for user %s.", user_name)
        raise
    return user
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [UpdateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/UpdateUser)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
  # Updates an IAM user's name
  #
  # @param current_name [String] The current name of the user
  # @param new_name [String] The new name of the user
  def update_user_name(current_name, new_name)
    @iam_client.update_user(user_name: current_name, new_user_name: new_name)
    true
  rescue StandardError => e
    @logger.error("Error updating user name from '#{current_name}' to '#{new_name}': #{e.message}")
    false
  end
```
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [UpdateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/UpdateUser)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_iam->updateuser(
          iv_username = iv_user_name
          iv_newusername = iv_new_user_name ).
        MESSAGE 'User updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'New user name already exists.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는AWS *SDK for SAP ABAP API*의 [UpdateUser](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------

# AWS SDK 또는 CLI와 `UploadServerCertificate` 함께 사용
<a name="iam_example_iam_UploadServerCertificate_section"></a>

다음 코드 예시는 `UploadServerCertificate`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
** AWS 계정에 서버 인증서를 업로드하려면**  
다음 **upload-server-certificate** 명령은 서버 인증서를 AWS 계정에 업로드합니다. 이 예제에서 인증서는 `public_key_cert_file.pem` 파일에 있고, 연결된 프라이빗 키가 `my_private_key.pem` 파일에 있으며, CA(인증 기관)에서 제공하는 인증서 체인은 `my_certificate_chain_file.pem` 파일에 있습니다. 파일 업로드가 완료되면 myServerCertificate** 이름 아래에서 사용할 수 있습니다. `file://`로 시작하는 파라미터는 명령에 파일 내용을 읽고 해당 내용을 파일 이름 대신 파라미터 값으로 사용하도록 지시합니다.  

```
aws iam upload-server-certificate \
    --server-certificate-name myServerCertificate \
    --certificate-body file://public_key_cert_file.pem \
    --private-key file://my_private_key.pem \
    --certificate-chain file://my_certificate_chain_file.pem
```
출력:  

```
{
    "ServerCertificateMetadata": {
        "Path": "/",
        "ServerCertificateName": "myServerCertificate",
        "ServerCertificateId": "ASCAEXAMPLE123EXAMPLE",
        "Arn": "arn:aws:iam::1234567989012:server-certificate/myServerCertificate",
        "UploadDate": "2019-04-22T21:13:44+00:00",
        "Expiration": "2019-10-15T22:23:16+00:00"
    }
}
```
자세한 내용은 **IAM 사용 설명서의 서버 인증서 생성, 업로드 및 삭제를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UploadServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/upload-server-certificate.html)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import { UploadServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";
import { readFileSync } from "node:fs";
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import * as path from "node:path";

const client = new IAMClient({});

const certMessage = `Generate a certificate and key with the following command, or the equivalent for your system.

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
-keyout example.key -out example.crt -subj "/CN=example.com" \
-addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1"
`;

const getCertAndKey = () => {
  try {
    const cert = readFileSync(
      path.join(dirnameFromMetaUrl(import.meta.url), "./example.crt"),
    );
    const key = readFileSync(
      path.join(dirnameFromMetaUrl(import.meta.url), "./example.key"),
    );
    return { cert, key };
  } catch (err) {
    if (err.code === "ENOENT") {
      throw new Error(
        `Certificate and/or private key not found. ${certMessage}`,
      );
    }

    throw err;
  }
};

/**
 *
 * @param {string} certificateName
 */
export const uploadServerCertificate = (certificateName) => {
  const { cert, key } = getCertAndKey();
  const command = new UploadServerCertificateCommand({
    ServerCertificateName: certificateName,
    CertificateBody: cert.toString(),
    PrivateKey: key.toString(),
  });

  return client.send(command);
};
```
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [UploadServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UploadServerCertificateCommand)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 새 서버 인증서를 IAM 계정에 업로드합니다. 인증서 본문, 프라이빗 키 및 인증서 체인(선택 사항)이 포함된 파일은 모두 PEM 인코딩되어야 합니다. 파라미터에는 파일 이름 대신 파일의 실제 내용이 필요합니다. 파일 내용을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다. **   

```
Publish-IAMServerCertificate -ServerCertificateName MyTestCert -CertificateBody (Get-Content -Raw server.crt) -PrivateKey (Get-Content -Raw server.key)
```
**출력:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/MyTestCert
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /
ServerCertificateId   : ASCAJIEXAMPLE7J7HQZYW
ServerCertificateName : MyTestCert
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UploadServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 새 서버 인증서를 IAM 계정에 업로드합니다. 인증서 본문, 프라이빗 키 및 인증서 체인(선택 사항)이 포함된 파일은 모두 PEM 인코딩되어야 합니다. 파라미터에는 파일 이름 대신 파일의 실제 내용이 필요합니다. 파일 내용을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다. **   

```
Publish-IAMServerCertificate -ServerCertificateName MyTestCert -CertificateBody (Get-Content -Raw server.crt) -PrivateKey (Get-Content -Raw server.key)
```
**출력:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/MyTestCert
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /
ServerCertificateId   : ASCAJIEXAMPLE7J7HQZYW
ServerCertificateName : MyTestCert
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UploadServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------

# CLI로 `UploadSigningCertificate` 사용
<a name="iam_example_iam_UploadSigningCertificate_section"></a>

다음 코드 예시는 `UploadSigningCertificate`의 사용 방법을 보여 줍니다.

------
#### [ CLI ]

**AWS CLI**  
**IAM 사용자의 서명 인증서 업로드**  
다음 `upload-signing-certificate` 명령은 `Bob`이라는 IAM 사용자의 서명 인증서를 업로드합니다.  

```
aws iam upload-signing-certificate \
    --user-name Bob \
    --certificate-body file://certificate.pem
```
출력:  

```
{
    "Certificate": {
        "UserName": "Bob",
        "Status": "Active",
        "CertificateBody": "-----BEGIN CERTIFICATE-----<certificate-body>-----END CERTIFICATE-----",
        "CertificateId": "TA7SMP42TDN5Z26OBPJE7EXAMPLE",
        "UploadDate": "2013-06-06T21:40:08.121Z"
    }
}
```
인증서는 PEM 형식의 *certificate.pem*이라는 파일에 있습니다.  
자세한 내용은 **IAM 사용 설명서의 사용자 서명 인증서 생성 및 업로드를 참조하세요.  
+  API 세부 정보는 **AWS CLI 명령 참조의 [UploadSigningCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/upload-signing-certificate.html)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제는 새로운 X.509 서명 인증서를 업로드하고 이를 `Bob`이라는 IAM 사용자와 연결합니다. 인증서 본문이 포함된 파일은 PEM으로 인코딩됩니다. `CertificateBody` 파라미터에는 파일 이름이 아닌 인증서 파일의 실제 내용이 필요합니다. 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
Publish-IAMSigningCertificate -UserName Bob -CertificateBody (Get-Content -Raw SampleSigningCert.pem)
```
**출력:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCEXAMPLEHMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API 세부 정보는 **AWS Tools for PowerShell Cmdlet 참조(V4)의 [UploadSigningCertificate](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제는 새로운 X.509 서명 인증서를 업로드하고 이를 `Bob`이라는 IAM 사용자와 연결합니다. 인증서 본문이 포함된 파일은 PEM으로 인코딩됩니다. `CertificateBody` 파라미터에는 파일 이름이 아닌 인증서 파일의 실제 내용이 필요합니다. 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다.**  

```
Publish-IAMSigningCertificate -UserName Bob -CertificateBody (Get-Content -Raw SampleSigningCert.pem)
```
**출력:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCEXAMPLEHMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [UploadSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------