AWS SDK 또는 CLI로 ListRolePolicies 사용하기

AWS SDK 또는 CLI로 ListRolePolicies 사용하기

다음 코드 예시는 ListRolePolicies을(를) 사용하는 방법을 보여줘요.

액션 예시는 더 큰 프로그램에서 발췌한 코드 조각이라, 실제 프로그램 컨텍스트 안에서 실행돼야 해요.

출처: 문서

본문

SDK for .NET

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

    /// <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 Reference의 ListRolePolicies 문서를 참고하세요.

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 역할 생성' 문서를 참고하세요.

API 상세 내용은 AWS CLI Command Reference의 ListRolePolicies 문서를 참고하세요.

SDK for Go V2

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

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 Reference의 ListRolePolicies 문서를 참고하세요.

SDK for JavaScript (v3)

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

정책을 나열해요.

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 Reference의 ListRolePolicies 문서를 참고하세요.

SDK for PHP

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

$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 Reference의 ListRolePolicies 문서를 참고하세요.

Tools for PowerShell V4

예시 1: 이 예시는 lamda_exec_role 역할에 포함된 인라인 정책 이름 목록을 반환해요. 인라인 정책의 세부 내용을 보려면 Get-IAMRolePolicy 명령을 사용하면 돼요.

Get-IAMRolePolicyList -RoleName lambda_exec_role

출력:

oneClick_lambda_exec_role_policy

API 상세 내용은 AWS Tools for PowerShell Cmdlet Reference (V4)의 ListRolePolicies 문서를 참고하세요.

Tools for PowerShell V5

예시 1: 이 예시는 lamda_exec_role 역할에 포함된 인라인 정책 이름 목록을 반환해요. 인라인 정책의 세부 내용을 보려면 Get-IAMRolePolicy 명령을 사용하면 돼요.

Get-IAMRolePolicyList -RoleName lambda_exec_role

출력:

oneClick_lambda_exec_role_policy

API 상세 내용은 AWS Tools for PowerShell Cmdlet Reference (V5)의 ListRolePolicies 문서를 참고하세요.

SDK for Python (Boto3)

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

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 Reference의 ListRolePolicies 문서를 참고하세요.

SDK for Ruby

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

  # 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 Reference의 ListRolePolicies 문서를 참고하세요.

SDK for Rust

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

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 reference의 ListRolePolicies 문서를 참고하세요.

SDK for SAP ABAP

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

    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 reference의 ListRolePolicies 문서를 참고하세요.

SDK for Swift

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

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 reference의 ListRolePolicies 문서를 참고하세요.

더 알아보기 (Learn more)