または ListAttachedRolePoliciesAWS SDKで を使用する CLI - AWS SDK コード例

AWS Doc SDK Examples GitHub リポジトリには他にも AWS SDK例があります。

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

または ListAttachedRolePoliciesAWS SDKで を使用する CLI

以下のコード例は、ListAttachedRolePolicies の使用方法を示しています。

.NET
AWS SDK for .NET
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

/// <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 詳細については、「 リファレンスListAttachedRolePolicies」の「」を参照してください。 AWS SDK for .NET API

CLI
AWS CLI

指定された IAM ロールにアタッチされている管理ポリシーを一覧表示するには

このコマンドは、 AWS アカウントSecurityAuditRole内の という名前ARNsのIAMロールにアタッチされた管理ポリシーの名前と を返します。

aws iam list-attached-role-policies \ --role-name SecurityAuditRole

出力:

{ "AttachedPolicies": [ { "PolicyName": "SecurityAudit", "PolicyArn": "arn:aws:iam::aws:policy/SecurityAudit" } ], "IsTruncated": false }

詳細については、「 ユーザーガイド」の「 のポリシーとアクセス許可IAMAWS IAM」を参照してください。

  • API 詳細については、「 コマンドリファレンスListAttachedRolePolicies」の「」を参照してください。 AWS CLI

Go
SDK Go V2 用
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

// 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(roleName string) ([]types.AttachedPolicy, error) { var policies []types.AttachedPolicy result, err := wrapper.IamClient.ListAttachedRolePolicies(context.TODO(), &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 詳細については、「 リファレンスListAttachedRolePolicies」の「」を参照してください。 AWS SDK for Go API

JavaScript
SDK JavaScript (v3) 用の
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

ロールにアタッチされたポリシーを一覧表示します。

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 詳細については、「 リファレンスListAttachedRolePolicies」の「」を参照してください。 AWS SDK for JavaScript API

PHP
PHP に関する SDK
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

$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 詳細については、「 リファレンスListAttachedRolePolicies」の「」を参照してください。 AWS SDK for PHP API

PowerShell
のツール PowerShell

例 1: このコマンドは、アカウントSecurityAuditRole内の という名前ARNsのIAMロールにアタッチされた管理ポリシーの名前と AWS を返します。ロールに埋め込まれているインラインポリシーのリストを表示するには、Get-IAMRolePolicyList コマンドを使用します。

Get-IAMAttachedRolePolicyList -RoleName "SecurityAuditRole"

出力:

PolicyArn PolicyName --------- ---------- arn:aws:iam::aws:policy/SecurityAudit SecurityAudit
  • API 詳細については、「 コマンドレットリファレンスListAttachedRolePolicies」の「」を参照してください。 AWS Tools for PowerShell

Python
SDK for Python (Boto3)
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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 詳細については、ListAttachedRolePolicies「 for AWS SDK Python (Boto3) APIリファレンス」の「」を参照してください。

Ruby
SDK Ruby 用
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

このサンプルモジュールは、ロールポリシーを一覧表示、作成、アタッチ、およびデタッチします。

# 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 詳細については、「 リファレンスListAttachedRolePolicies」の「」を参照してください。 AWS SDK for Ruby API

Rust
SDK Rust 用
注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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 SDKRust APIリファレンスのListAttachedRolePolicies「」の「」を参照してください。

Swift
SDK Swift 用
注記

これはプレビューリリースSDKの のプレリリースドキュメントです。このドキュメントは変更される可能性があります。

注記

については、「」を参照してください GitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

/// 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] = [] var marker: String? = nil var isTruncated: Bool repeat { let input = ListAttachedRolePoliciesInput( marker: marker, roleName: role ) let output = try await client.listAttachedRolePolicies(input: input) guard let attachedPolicies = output.attachedPolicies else { return policyList } for attachedPolicy in attachedPolicies { policyList.append(attachedPolicy) } marker = output.marker isTruncated = output.isTruncated } while isTruncated == true return policyList }
  • API 詳細については、ListAttachedRolePolicies「」の「Swift リファレンス」を参照してください。 AWS SDK API