AWS SDK 또는 CLI로 GetRole 사용하기

AWS SDK 또는 CLI로 GetRole 사용하기

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

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

출처: 문서

본문

SDK for .NET

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

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

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

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

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
}



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

SDK for JavaScript (v3)

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

역할을 가져와요.

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

SDK for PHP

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

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

Tools for PowerShell V4

예시 1: 이 예시는 lamda_exec_role에 대한 상세 정보를 반환해요. 누가 이 역할을 수임(assume)할 수 있는지 지정하는 트러스트 정책 문서가 포함돼요. 정책 문서는 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 Reference (V4)의 GetRole 문서를 참고하세요.

Tools for PowerShell V5

예시 1: 이 예시는 lamda_exec_role에 대한 상세 정보를 반환해요. 누가 이 역할을 수임(assume)할 수 있는지 지정하는 트러스트 정책 문서가 포함돼요. 정책 문서는 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 Reference (V5)의 GetRole 문서를 참고하세요.

SDK for Python (Boto3)

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

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

SDK for Ruby

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

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

SDK for Rust

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

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

SDK for SAP ABAP

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

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

SDK for Swift

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

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

더 알아보기 (Learn more)