

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

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

# AWS SDKs基本的な例
<a name="iam_code_examples_basics"></a>

次のコード例は、 SDKs AWS Identity and Access Management で AWS の基本を使用する方法を示しています。

**Contents**
+ [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)

# 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)での設定と実行の方法を確認してください。
From 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(())
}
```
From 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 アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの 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)での設定と実行の方法を確認してください。
IAM ユーザーと、Amazon S3 バケットを一覧表示するアクセス権限を付与するロールを作成します。ユーザーには、ロールの引き受けのみ権限があります。ロールを引き受けた後、一時的な認証情報を使用してアカウントのバケットを一覧表示します。  

```
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)での設定と実行の方法を確認してください。
IAM ユーザーと、Amazon S3 バケットを一覧表示するアクセス権限を付与するロールを作成します。ユーザーには、ロールの引き受けのみ権限があります。ロールを引き受けた後、一時的な認証情報を使用してアカウントのバケットを一覧表示します。  

```
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)での設定と実行の方法を確認してください。
IAM ユーザーと、Amazon S3 バケットを一覧表示するアクセス権限を付与するロールを作成します。ユーザーには、ロールの引き受けのみ権限があります。ロールを引き受けた後、一時的な認証情報を使用してアカウントのバケットを一覧表示します。  

```
# 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アクション
<a name="iam_code_examples_actions"></a>

次のコード例は、 AWS SDKs で個々の IAM アクションを実行する方法を示しています。それぞれの例には、GitHub へのリンクがあり、そこにはコードの設定と実行に関する説明が記載されています。

これらは IAM API を呼び出すもので、コンテキスト内で実行する必要がある大規模なプログラムからのコード抜粋です。アクションは [AWS SDKsシナリオ](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**  
**Open-ID Connect (OIDC) プロバイダーにクライアント ID (対象者) を追加するには**  
次の `add-client-id-to-open-id-connect-provider` コマンドは、クライアント ID `my-application-ID` を `server.example.com` という名前の OIDC プロバイダーに追加します。  

```
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 で OpenID Connect (OIDC) 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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` コマンドは、`S3Access` という名前のロールを `Webserver` という名前のインスタンスプロファイルに追加します。  

```
aws iam add-role-to-instance-profile \
    --role-name S3Access \
    --instance-profile-name Webserver
```
このコマンドでは何も出力されません。  
インスタンスプロファイルを作成するには、`create-instance-profile` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[Amazon EC2 インスタンスで実行されるアプリケーションに IAM ロールを使用してアクセス許可を付与する](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: このコマンドは、`S3Access` という名前のロールを `webserver` という名前の既存のインスタンスプロファイルに追加します。インスタンスプロファイルを作成するには、`New-IAMInstanceProfile` コマンドを使用します。このコマンドを使用してインスタンスプロファイルを作成し、ロールに関連付けると、EC2 インスタンスにアタッチできます。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile-Name` パラメータと共に使用して、新しいインスタンスを起動します。**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddRoleToInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: このコマンドは、`S3Access` という名前のロールを `webserver` という名前の既存のインスタンスプロファイルに追加します。インスタンスプロファイルを作成するには、`New-IAMInstanceProfile` コマンドを使用します。このコマンドを使用してインスタンスプロファイルを作成し、ロールに関連付けると、EC2 インスタンスにアタッチできます。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile-Name` パラメータと共に使用して、新しいインスタンスを起動します。**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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` コマンドは、`Bob` という名前の IAM ユーザーを `Admins` という名前の 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 ポリシーを という名前の IAM ロール`ReadOnlyAccess`にアタッチします`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 コマンドレットリファレンス (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 Policy オブジェクトを使用して、ロールにポリシーをアタッチします。  

```
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 Role オブジェクトを使用して、ロールにポリシーをアタッチします。  

```
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**  
 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 リファレンス*」の「[AttachRolePolicy](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 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 コマンドレットリファレンス (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**  
 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 リファレンス*」の「[AttachUserPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

# CLI で `ChangePassword` を使用する
<a name="iam_example_iam_ChangePassword_section"></a>

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

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

**AWS CLI**  
**IAM ユーザーのパスワードを変更するには**  
IAM ユーザーのパスワードを変更するには、`--cli-input-json` パラメータを使用して、古いパスワードと新しいパスワードを含む JSON ファイルを渡すことをお勧めします。この方法を使用すると、英数字以外の文字を含む強力なパスワードを使用できます。英数字以外の文字を含むパスワードをコマンドラインパラメータとして渡す場合、そのパスワードの使用が難しい場合があります。`--cli-input-json` パラメータを使用するには、まず次の例のように、`change-password` コマンドと `--generate-cli-skeleton` パラメータを組み合わせて使用します。  

```
aws iam change-password \
    --generate-cli-skeleton > change-password.json
```
前のコマンドは change-password.json という名前の JSON ファイルを作成し、これを使用して古いパスワードと新しいパスワードを入力できます。例えば、ファイルは次のようになります。  

```
{
    "OldPassword": "3s0K_;xh4~8XXI",
    "NewPassword": "]35d/{pB9Fo9wJ"
}
```
次に、パスワードを変更するには、`change-password` コマンドをもう一度使用します。今度は、JSON ファイルを指定する `--cli-input-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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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`コマンドは、`examplecorp` AWS アカウントのエイリアスを作成します。  

```
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 コマンドレットリファレンス (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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 ユーザーガイド*」の「[Amazon EC2 インスタンスで実行されるアプリケーションに IAM ロールを使用してアクセス許可を付与する](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 インスタンスにアタッチします。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile_Name` パラメータと共に使用します。**  

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

**Tools for PowerShell V5**  
**例 1: この例では、`ProfileForDevEC2Instance` という名前の新しい IAM インスタンスプロファイルを作成します。`Add-IAMRoleToInstanceProfile` コマンドを個別に実行して、インスタンスにアクセス許可を与える既存の IAM ロールにインスタンスプロファイルを関連付ける必要があります。最後に、EC2 インスタンスを起動する際に、インスタンスプロファイルを EC2 インスタンスにアタッチします。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile_Name` パラメータと共に使用します。**  

```
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` パラメータを使用するには、まず次の例のように、`create-login-profile` コマンドと `--generate-cli-skeleton` パラメータを組み合わせて使用します。  

```
aws iam create-login-profile \
    --generate-cli-skeleton > create-login-profile.json
```
前のコマンドでは、create-login-profile.json という名前の JSON ファイルが作成されます。このファイルを使用して、後続の `create-login-profile` コマンドの情報を入力できます。例えば、次のようになります。  

```
{
    "UserName": "Bob",
    "Password": "&1-3a6u:RA0djs",
    "PasswordResetRequired": true
}
```
次に、IAM ユーザーのパスワードを作成するには、`create-login-profile` コマンドをもう一度使用します。今度は、JSON ファイルを指定する `--cli-input-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 コマンドレットリファレンス (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 コマンドレットリファレンス (V5) の「[CreateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

# CLI で `CreateOpenIdConnectProvider` を使用する
<a name="iam_example_iam_CreateOpenIdConnectProvider_section"></a>

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

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

**AWS CLI**  
**OpenID Connect (OIDC) プロバイダーを作成するには**  
OpenID Connect (OIDC) プロバイダーを作成するには、`--cli-input-json` パラメータを使用して、必要なパラメータを含む JSON ファイルを渡すことをお勧めします。OIDC プロバイダーを作成するときは、プロバイダーの URL を渡す必要があり、URL は `https://` で始まる必要があります。コマンドライン環境によっては、コロン (:) とフォワードスラッシュ (/) の文字が特別な意味を持つため、URL をコマンドラインパラメータとして渡すのは難しい場合があります。この `--cli-input-json` パラメータを使用すると、この制限を回避できます。  
`--cli-input-json` パラメータを使用するには、まず次の例のように、`create-open-id-connect-provider` コマンドと `--generate-cli-skeleton` パラメータを組み合わせて使用します。  

```
aws iam create-open-id-connect-provider \
    --generate-cli-skeleton > create-open-id-connect-provider.json
```
前のコマンドでは、create-open-id-connect-provider.json という名前の JSON ファイルが作成されます。このファイルを使用して、後続の `create-open-id-connect-provider` コマンドの情報を入力できます。例えば、次のようになります。  

```
{
    "Url": "https://server.example.com",
    "ClientIDList": [
        "example-application-ID"
    ],
    "ThumbprintList": [
        "c3768084dfb3d2b68b7897bf5f565da8eEXAMPLE"
    ]
}
```
次に、OpenID Connect (OIDC) プロバイダーを作成するには、`create-open-id-connect-provider` コマンドをもう一度使用します。今度は、JSON ファイルを指定する `--cli-input-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 で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
OIDC プロバイダーのサムプリントの取得に関する詳細については、「*AWS IAM ユーザーガイド*」の「[OpenID Connect ID プロバイダーのサムプリントを取得する](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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 Policy Builder 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` は、現在のフォルダにある JSON ドキュメントで、`amzn-s3-demo-bucket` という名前の Amazon S3 バケット内の `shared` フォルダに対する読み取り専用アクセスを付与します。  

```
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"
    }
}
```
文字列パラメータの入力としてファイルを使用する方法の詳細については、「 [CLI ユーザーガイド」の「CLI AWS のパラメータ値を指定する](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 形式のタグを持つ `--tags` パラメーターを使用します: `'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`。あるいは、`--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` switch パラメータを使用する必要があることに注意してください。**  

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

**Tools for PowerShell V5**  
**例 1: この例では、 という名前の現在の AWS アカウントに新しい IAM `MySamplePolicy` ポリシーを作成します。 ファイルはポリシーコンテンツ`MySamplePolicy.json`を提供します。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。**  

```
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**  
 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` switch パラメータを使用する必要があることに注意してください。**  

```
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 コマンドレットリファレンス (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` switch パラメータを使用する必要があることに注意してください。**  

```
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**  
 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 リファレンス*」の「[CreateRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/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 リファレンス*」の「[CreateRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/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 形式のタグを持つ `--tags` パラメータフラグを使用します: `'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`。あるいは、`--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 リファレンス*」の「[CreateRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.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 リファレンス*」の「[CreateRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/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 リファレンス*」の「[CreateRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)」を参照してください。

------
#### [ 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 リファレンス*」の「[CreateRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、`MyNewRole` という名前の新しいロールを作成し、`NewRoleTrustPolicy.json` ファイルにあるポリシーをそのロールにアタッチします。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。出力に表示されるポリシードキュメントは、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 コマンドレットリファレンス (V4)* の「[CreateRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、`MyNewRole` という名前の新しいロールを作成し、`NewRoleTrustPolicy.json` ファイルにあるポリシーをそのロールにアタッチします。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。出力に表示されるポリシードキュメントは、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 Reference*」の「[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 リファレンス*」の「[CreateRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/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**  
 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 ID プロバイダーの作成](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 コマンドレットリファレンス (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 コマンドレットリファレンス (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: この例では、自動スケーリングサービスのサービスにリンクされたロールを作成します。**  

```
New-IAMServiceLinkedRole -AWSServiceName autoscaling.amazonaws.com -CustomSuffix RoleNameEndsWithThis -Description "My service-linked role to support autoscaling"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、自動スケーリングサービスのサービスにリンクされたロールを作成します。**  

```
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**  
 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 リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/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 リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/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 ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html)」を参照してください。  
**例 3: タグを使用して IAM ユーザーを作成するには**  
次の `create-user` コマンドは、タグを使用して `Bob` という名前の IAM ユーザーを作成します。この例では、次の JSON 形式のタグを持つ `--tags` パラメータフラグを使用します: `'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`。あるいは、`--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 リファレンス*の「[CreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.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 リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/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 デベロッパーガイド」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateUserCommand)」を参照してください。

**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 リファレンス」の「[CreateUser](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/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 リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/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 コマンドレットリファレンス (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 リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/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**  
 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 ソフトウェアプログラムが (QR コードの代わりに) アカウントを作成するのに必要な `Base32StringSeed` 値を抽出します。この値でプログラムを設定したら、プログラムから 2 つの連続した認証コードを取得します。最後に、最後のコマンドを使用して仮想 MFA デバイスを IAM ユーザー `Bob` にリンクし、アカウントを 2 つの認証コードと同期します。**  

```
$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 プログラムでアカウントを作成したら、2 つの連続した認証コードを取得して最後のコマンドに入力し、仮想 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 コマンドレットリファレンス (V4)* の「[CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、新しい仮想 MFA デバイスを作成します。2 行目と 3 行目は、仮想 MFA ソフトウェアプログラムが (QR コードの代わりに) アカウントを作成するのに必要な `Base32StringSeed` 値を抽出します。この値でプログラムを設定したら、プログラムから 2 つの連続した認証コードを取得します。最後に、最後のコマンドを使用して仮想 MFA デバイスを IAM ユーザー `Bob` にリンクし、アカウントを 2 つの認証コードと同期します。**  

```
$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 プログラムでアカウントを作成したら、2 つの連続した認証コードを取得して最後のコマンドに入力し、仮想 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 コマンドレットリファレンス (V5) の「[CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

# CLI で `DeactivateMfaDevice` を使用する
<a name="iam_example_iam_DeactivateMfaDevice_section"></a>

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

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

**AWS CLI**  
**デバイスを無効にするには**  
このコマンドは、ユーザー `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` コマンドを使用して、古い仮想 MFA デバイスを削除する必要があります。**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (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` コマンドを使用して、古い仮想 MFA デバイスを削除する必要があります。**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 リファレンス](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」の「*DeleteAccessKey*」を参照してください。

------
#### [ 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 コマンドレットリファレンス (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**  
 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 アカウント し、すべての値を元のデフォルトにリセットします。パスワードポリシーが現在存在しない場合、次のエラーメッセージが表示されます。The account policy with name PasswordPolicy cannot be found.**  

```
Remove-IAMAccountPasswordPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、 のパスワードポリシーを削除 AWS アカウント し、すべての値を元のデフォルトにリセットします。パスワードポリシーが現在存在しない場合、次のエラーメッセージが表示されます。The account policy with name PasswordPolicy cannot be found.**  

```
Remove-IAMAccountPasswordPolicy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 ユーザーを削除し、2 番目のコマンドは IAM グループを削除します。どちらのコマンドも、確認を求めるプロンプトが表示されなくても機能します。**  

```
(Get-IAMGroup -GroupName MyTestGroup).Users | Remove-IAMUserFromGroup -GroupName MyTestGroup -Force
Remove-IAMGroup -GroupName MyTestGroup -Force
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DeleteGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、`MyTestGroup` という名前の IAM グループを削除します。最初のコマンドはグループのメンバーであるすべての IAM ユーザーを削除し、2 番目のコマンドは IAM グループを削除します。どちらのコマンドも、確認を求めるプロンプトが表示されなくても機能します。**  

```
(Get-IAMGroup -GroupName MyTestGroup).Users | Remove-IAMUserFromGroup -GroupName MyTestGroup -Force
Remove-IAMGroup -GroupName MyTestGroup -Force
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (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` コマンドを使用します。  
IAM ポリシーの詳細については、「*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: この例では、`TesterPolicy` という名前のインラインポリシーを IAM グループ `Testers` から削除します。そのグループのユーザーは、そのポリシーで定義されているアクセス権限をすぐに失います。**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、`TesterPolicy` という名前のインラインポリシーを IAM グループ `Testers` から削除します。そのグループのユーザーは、そのポリシーで定義されているアクセス権限をすぐに失います。**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 インスタンスプロファイルを削除します。最初のコマンドはインスタンスプロファイルからすべてのロールをデタッチし、2 番目のコマンドはインスタンスプロファイルを削除します。**  

```
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、`MyAppInstanceProfile` という名前の EC2 インスタンスプロファイルを削除します。最初のコマンドはインスタンスプロファイルからすべてのロールをデタッチし、2 番目のコマンドはインスタンスプロファイルを削除します。**  

```
(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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 で OpenID Connect (OIDC) 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 行目から 6 行目では、アタッチされている各エンティティからポリシーをデタッチします。最後の行では、このコマンドを使用して管理ポリシーと残りのデフォルトバージョンを削除します。この例には、確認を求めるプロンプトを非表示にするための `-Force` switch パラメータが、このパラメータを必要とする行に含まれています。**  

```
$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 コマンドレットリファレンス (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 行目から 6 行目では、アタッチされている各エンティティからポリシーをデタッチします。最後の行では、このコマンドを使用して管理ポリシーと残りのデフォルトバージョンを削除します。この例には、確認を求めるプロンプトを非表示にするための `-Force` switch パラメータが、このパラメータを必要とする行に含まれています。**  

```
$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**  
 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 リファレンス*」の「[DeletePolicy](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 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**  
**管理ポリシーのバージョンを削除するには**  
この例では、`v2` と識別されたバージョンを ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーから削除します。  

```
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: この例では、`v2` と識別されたバージョンを ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーから削除します。**  

```
Remove-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy -VersionID v2
```
**例 2: この例では、最初にデフォルト以外のポリシーバージョンをすべて削除し、次にポリシー自体を削除することでポリシーを削除します。1 行目では、ポリシーオブジェクトを取得します。2 行目では、デフォルトとしてフラグが立てられていないすべてのポリシーバージョンをコレクションに取得し、このコマンドを使用してコレクション内の各ポリシーを削除します。最後の行では、ポリシー自体と残りのデフォルトバージョンを削除します。管理ポリシーを正常に削除するには、`Unregister-IAMUserPolicy`、`Unregister-IAMGroupPolicy`、`Unregister-IAMRolePolicy` コマンドを使用して、ユーザー、グループ、またはロールからポリシーをデタッチする必要があることに注意してください。`Remove-IAMPolicy` コマンドレットの例を参照してください。**  

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

**Tools for PowerShell V5**  
**例 1: この例では、`v2` と識別されたバージョンを ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーから削除します。**  

```
Remove-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy -VersionID v2
```
**例 2: この例では、最初にデフォルト以外のポリシーバージョンをすべて削除し、次にポリシー自体を削除することでポリシーを削除します。1 行目では、ポリシーオブジェクトを取得します。2 行目では、デフォルトとしてフラグが立てられていないすべてのポリシーバージョンをコレクションに取得し、このコマンドを使用してコレクション内の各ポリシーを削除します。最後の行では、ポリシー自体と残りのデフォルトバージョンを削除します。管理ポリシーを正常に削除するには、`Unregister-IAMUserPolicy`、`Unregister-IAMGroupPolicy`、`Unregister-IAMRolePolicy` コマンドを使用して、ユーザー、グループ、またはロールからポリシーをデタッチする必要があることに注意してください。`Remove-IAMPolicy` コマンドレットの例を参照してください。**  

```
$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 コマンドレットリファレンス (V5) の「[DeletePolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

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

**SDK for SAP ABAP**  
 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` という名前のロールから管理ポリシーをすべてデタッチして、ロールを削除します。最初の行では、ロールにアタッチされているすべての管理ポリシーをコレクションとして取得し、コレクション内の各ポリシーをロールからデタッチします。2 行目では、ロール自体を削除します。インラインポリシーは、ロールと共に削除されます。**  

```
Get-IAMAttachedRolePolicyList -RoleName MyNewRole | Unregister-IAMRolePolicy -RoleName MyNewRole
Remove-IAMRole -RoleName MyNewRole
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (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` という名前のロールから管理ポリシーをすべてデタッチして、ロールを削除します。最初の行では、ロールにアタッチされているすべての管理ポリシーをコレクションとして取得し、コレクション内の各ポリシーをロールからデタッチします。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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 ID プロバイダーの作成](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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (V5) の「[DeleteVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

# CLI で `DetachGroupPolicy` を使用する
<a name="iam_example_iam_DetachGroupPolicy_section"></a>

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

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

**AWS CLI**  
**グループからポリシーをデタッチするには**  
この例では、ARN `arn:aws:iam::123456789012:policy/TesterAccessPolicy` を持つ管理ポリシーを `Testers` というグループから削除します。  

```
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 コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
**ロールからポリシーをデタッチするには**  
この例では、ARN `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy` を持つ管理ポリシーを `FedTesterRole` というロールから削除します。  

```
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 コマンドレットリファレンス (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 Policy オブジェクトを使用して、ロールからポリシーをデタッチします。  

```
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 Role オブジェクトを使用して、ロールからポリシーをデタッチします。  

```
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**  
 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**  
**ユーザーからポリシーをデタッチするには**  
この例では、ARN `arn:aws:iam::123456789012:policy/TesterPolicy` を持つ管理ポリシーをユーザー `Bob` から削除します。  

```
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 コマンドレットリファレンス (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**  
 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 デバイスからの最初の 2 つのコードを順番に含める 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` に関連付けます。また、このコマンドは、デバイスからの最初の 2 つのコードを順番に含めます。**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**例 2: この例では、仮想 MFA デバイスを作成して有効にします。最初のコマンドは仮想デバイスを作成し、そのデバイスのオブジェクト表現を変数 `$MFADevice` に返します。`.Base32StringSeed` または `QRCodePng` プロパティを使用して、ユーザーのソフトウェアアプリケーションを設定できます。最後のコマンドはデバイスをユーザー `David` に割り当て、デバイスをシリアル番号で識別します。コマンドは、仮想 MFA デバイスからの最初の 2 つのコードを順番に含める 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 コマンドレットリファレンス (V4)* の「[EnableMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: このコマンドは、シリアル番号 `987654321098` を持つハードウェア MFA デバイスを有効にし、このデバイスをユーザー `Bob` に関連付けます。また、このコマンドは、デバイスからの最初の 2 つのコードを順番に含めます。**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**例 2: この例では、仮想 MFA デバイスを作成して有効にします。最初のコマンドは仮想デバイスを作成し、そのデバイスのオブジェクト表現を変数 `$MFADevice` に返します。`.Base32StringSeed` または `QRCodePng` プロパティを使用して、ユーザーのソフトウェアアプリケーションを設定できます。最後のコマンドはデバイスをユーザー `David` に割り当て、デバイスをシリアル番号で識別します。コマンドは、仮想 MFA デバイスからの最初の 2 つのコードを順番に含める 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 コマンドレットリファレンス (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 時間ごとに実行できる新しいレポートの生成を要求しています。最新のレポートがまだ新しい場合、[状態] フィールドには `COMPLETE` と表示されます。`Get-IAMCredentialReport` を使用して、完成したレポートを表示します。**  

```
Request-IAMCredentialReport
```
**出力:**  

```
Description                                                    State
-----------                                                    -----
No report exists. Starting a new report generation task        STARTED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GenerateCredentialReport](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、4 時間ごとに実行できる新しいレポートの生成を要求しています。最新のレポートがまだ新しい場合、[状態] フィールドには `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**  
 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`例では、バックグラウンドジョブを開始して、IAM ユーザーおよびその他のエンティティが AWS マネージド`AdministratorAccess`ポリシーでアクセスしたサービスを一覧表示するレポートを生成します。`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 と同等のコマンドレットです。これにより、Get-IAMServiceLastAccessedDetail と Get-IAMServiceLastAccessedDetailWithEntity で使用できるジョブ ID が提供されます。**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GenerateServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例は GenerateServiceLastAccessedDetails API と同等のコマンドレットです。これにより、Get-IAMServiceLastAccessedDetail と Get-IAMServiceLastAccessedDetailWithEntity で使用できるジョブ ID が提供されます。**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 アカウント内の ID に関する認可の詳細を取得し、返されたオブジェクトの要素リスト (ユーザー、グループ、ロールを含む) を表示します。例えば、`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 コマンドレットリファレンス (V4)* の「[GetAccountAuthorizationDetails](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウント内の ID に関する認可の詳細を取得し、返されたオブジェクトの要素リスト (ユーザー、グループ、ロールを含む) を表示します。例えば、`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**  
 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 リファレンス*」の「[GetAccountAuthorizationDetails](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 コマンドレットリファレンス (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**  
 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 コマンドレットリファレンス (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**  
 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: コマンドラインでパラメータとして指定された 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: ファイル入力として提供される 1 つ以上のカスタム JSON ポリシーによって参照されるコンテキストキーを一覧表示するには**  
次の `get-context-keys-for-custom-policy` コマンドは前の例と同じですが、ポリシーがパラメータとしてではなくファイルで提供される点が異なります。このコマンドは JSON 構造のリストではなく JSON 文字列のリストを想定しているため、ファイルは次のような構造にする必要があります。ただし、1 つにまとめることはできます。  

```
[
    "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 Policy Simulator (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 Policy Simulator (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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` コマンドレットを使用してレポートを生成する必要があります。レポートを 1 つの文字列として取得するには、`-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 コマンドレットリファレンス (V4)* の「[GetCredentialReport](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、返されたレポートを開き、それをテキスト行の配列としてパイプラインに出力します。最初の行は、カンマで区切られた列名のヘッダーです。連続する各行は 1 人のユーザーの詳細行で、各フィールドはカンマで区切られています。レポートを表示するには、`Request-IAMCredentialReport` コマンドレットを使用してレポートを生成する必要があります。レポートを 1 つの文字列として取得するには、`-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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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"
}
```
IAM ポリシーの詳細については、「*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 コマンドレットリファレンス (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 コマンドレットリファレンス (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: この例では、現在の AWS アカウントで定義されている `ec2instancerole` という名前のインスタンスプロファイルの詳細を返します。**  

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

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントで定義されている `ec2instancerole` という名前のインスタンスプロファイルの詳細を返します。**  

```
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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 で OpenID Connect (OIDC) 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 コマンドレットリファレンス (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 コマンドレットリファレンス (V5) の「[GetOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

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

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

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [IAM Policy Builder 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 Policy Builder 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 プロバイダーに関する詳細を取得します。レスポンスには、SAML プロバイダーエンティティを作成するために ID AWS プロバイダーから取得したメタデータドキュメントと、作成日と有効期限が含まれます。  

```
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 ID プロバイダーの作成](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 プロバイダーに関する詳細を取得します。レスポンスには、SAML プロバイダーエンティティを作成するために ID AWS プロバイダーから取得したメタデータドキュメントと、作成日と有効期限が含まれます。**  

```
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 コマンドレットリファレンス (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 プロバイダーに関する詳細を取得します。レスポンスには、SAML プロバイダーエンティティを作成するために ID AWS プロバイダーから取得したメタデータドキュメントと、作成日と有効期限が含まれます。**  

```
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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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"
    }
}
```
IAM ポリシーの詳細については、「*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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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` コマンドレットを使用して新しいアクセスキーを作成する必要があります。**  

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

**Tools for PowerShell V5**  
**例 1: このコマンドは、`Bob` という名前の IAM ユーザーのアクセスキーを一覧表示します。IAM ユーザーのシークレットアクセスキーを一覧表示できないことに注意してください。シークレットアクセスキーを紛失した場合は、`New-IAMAccessKey` コマンドレットを使用して新しいアクセスキーを作成する必要があります。**  

```
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**  
 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 コマンドレットリファレンス (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**  
 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 の詳細については、「*AWS SDK for SAP ABAP 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 アカウント`Admins`内の という名前の IAM グループにアタッチされている管理ポリシーの名前と ARNs を返します。  

```
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 アカウント`Admins`内の という名前の IAM グループにアタッチされている管理ポリシーの名前と ARNs を返します。グループに埋め込まれているインラインポリシーのリストを表示するには、`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 コマンドレットリファレンス (V4)* の「[ListAttachedGroupPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: このコマンドは、 AWS アカウント`Admins`内の という名前の IAM グループにアタッチされている管理ポリシーの名前と ARNs を返します。グループに埋め込まれているインラインポリシーのリストを表示するには、`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 コマンドレットリファレンス (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 アカウント`SecurityAuditRole`で という名前の IAM ロールにアタッチされた管理ポリシーの名前と ARNs を返します。  

```
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 API リファレンス」の「[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 コマンドレットリファレンス (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**  
 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 アカウント`Bob`で という名前の IAM ユーザー用の管理ポリシーの名前と ARNs を返します。  

```
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 アカウント`Bob`で という名前の IAM ユーザー用の管理ポリシーの名前と ARNs を返します。IAM ユーザーに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMUserPolicyList` コマンドを使用します。**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAttachedUserPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: このコマンドは、 AWS アカウント`Bob`で という名前の IAM ユーザー用の管理ポリシーの名前と ARNs を返します。IAM ユーザーに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMUserPolicyList` コマンドを使用します。**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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"
    ]
}
```
IAM ポリシーの詳細については、「*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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 リファレンス*」の「[ListGroup](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 リファレンス*」の「[ListGroup](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 リファレンス」の「[ListGroup](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 リファレンス*」の「[ListGroup](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 コマンドレットリファレンス (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 リファレンス*」の「[ListGroup](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**  
 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 ユーザーが属する 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 で OpenID Connect (OIDC) 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 プロバイダーの ARN のリストを返します。**  

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

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントで定義されているすべての OpenID Connect プロバイダーの ARN のリストを返します。**  

```
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 コマンドレットリファレンス (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 アカウントで利用可能な最初の 2 つの管理ポリシーのコレクションを返します。  

```
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 アカウントで使用できる最初の 2 つのカスタマー管理ポリシーのコレクションを返します。`-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 コマンドレットリファレンス (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 アカウントで使用できる最初の 2 つのカスタマー管理ポリシーのコレクションを返します。`-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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (V5) の「[ListPolicyVersions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

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

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

**Tools for PowerShell V5**  
**例 1: この例では、ロールに関連付けられているタグを取得します。**  

```
Get-IAMRoleTagList -RoleName MyRoleName
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 ID プロバイダーの作成](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 コマンドレットリファレンス (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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 API リファレンス」の「[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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (V4)* の「[ListUserTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、ユーザーに関連付けられているタグを取得します。**  

```
Get-IAMUserTagList -UserName joe
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 ドキュメントとして定義されます。(ファイル名と拡張子には意味はありません。)  
IAM ポリシーの詳細については、「*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 コマンドレットリファレンス (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 コマンドレットリファレンス (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` の例では、指定した IAM ロールのアクセス許可の境界として、`intern-boundary` という名前のカスタムポリシーを適用します。  

```
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`例では、指定された IAM ロールのアクセス許可の境界として AWS 管理`PowerUserAccess`ポリシーを適用します。  

```
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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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` の例では、指定した IAM ユーザーのアクセス許可の境界として、`intern-boundary` という名前のカスタムポリシーを適用します。  

```
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`例では、指定された IAM ユーザーのアクセス許可の境界`PowerUserAccess`として という名前の AWS マネージドポーリーを適用します。  

```
aws iam put-user-permissions-boundary \
    --permissions-boundary arn:aws:iam::aws:policy/PowerUserAccess \
    --user-name developer
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM ユーザーガイド*の「[IAM ID アクセス許可の追加および削除](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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 ID アクセス許可の追加および削除](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 コマンドレットリファレンス (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 で OpenID Connect (OIDC) 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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: この例では、IAM ユーザー `Bob` をグループ `Testers` から削除します。**  

```
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: この例は、IAM ユーザー `Bob` を `Testers` グループから削除する別の方法を示しています。**  

```
Get-IAMGroupForUser -UserName Bob | Remove-IAMUserFromGroup -UserName Bob -GroupName Testers -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveUserFromGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ユーザー `Bob` をグループ `Testers` から削除します。**  

```
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: この例は、IAM ユーザー `Bob` を `Testers` グループから削除する別の方法を示しています。**  

```
Get-IAMGroupForUser -UserName Bob | Remove-IAMUserFromGroup -UserName Bob -GroupName Testers -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 デバイスを、2 つの認証コードを提供した認証プログラムと同期します。  

```
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 デバイスを、2 つの認証コードを提供した認証プログラムと同期します。**  

```
Sync-IAMMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/theresa -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Bob
```
**例 2: この例では、IAM ユーザー `Theresa` に関連付けられている IAM MFA デバイスを、シリアル番号が `ABCD12345678` であり、2 つの認証コードを提供した物理デバイスと同期します。**  

```
Sync-IAMMFADevice -SerialNumber ABCD12345678 -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Theresa
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (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 デバイスを、2 つの認証コードを提供した認証プログラムと同期します。**  

```
Sync-IAMMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/theresa -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Bob
```
**例 2: この例では、IAM ユーザー `Theresa` に関連付けられている IAM MFA デバイスを、シリアル番号が `ABCD12345678` であり、2 つの認証コードを提供した物理デバイスと同期します。**  

```
Sync-IAMMFADevice -SerialNumber ABCD12345678 -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Theresa
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (V5) の「[SetDefaultPolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

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

**SDK for SAP ABAP**  
 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 リファレンス*」の「[SetDefaultPolicyVersion](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

# CLI で `TagRole` を使用する
<a name="iam_example_iam_TagRole_section"></a>

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

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

**AWS CLI**  
**ロールにタグを追加するには**  
次の `tag-role` コマンドは、部門名を持つタグを指定したロールに追加します。  

```
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 コマンドレットリファレンス (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 コマンドレットリファレンス (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` コマンドは、関連付けらた部門を持つタグを指定したユーザーに追加します。  

```
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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 リファレンス*」の「[UpdateAccessKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

# CLI で `UpdateAccountPasswordPolicy` を使用する
<a name="iam_example_iam_UpdateAccountPasswordPolicy_section"></a>

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

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

**AWS CLI**  
**現在のアカウントのパスワードポリシーを設定または変更するには**  
次の `update-account-password-policy` コマンドは、8 文字以上の長さを要求し、パスワードに 1 つ以上の数字を要求するようにパスワードポリシーを設定します。  

```
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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 で OpenID Connect (OIDC) 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 ID プロバイダーの作成](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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 コマンドレットリファレンス (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**  
 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 コマンドレットリファレンス (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 コマンドレットリファレンス (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 の使用*に関するガイドの「Creating and Uploading a User Signing Certificate」を参照してください。  
+  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 コマンドレットリファレンス (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 コマンドレットリファレンス (V5) の「[UploadSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------