AWS SDK 또는 CLI로 ListRoles 사용하기

AWS SDK 또는 CLI로 ListRoles 사용하기

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

출처: 문서

본문

SDK for .NET

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

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

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

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

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
}



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

SDK for JavaScript (v3)

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

역할을 나열해요.

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

SDK for PHP

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

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

Tools for PowerShell V4

예시 1: 이 예시는 AWS 계정의 모든 IAM 역할 목록을 조회해요.

Get-IAMRoleList

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

Tools for PowerShell V5

예시 1: 이 예시는 AWS 계정의 모든 IAM 역할 목록을 조회해요.

Get-IAMRoleList

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

SDK for Python (Boto3)

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

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

SDK for Ruby

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

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

SDK for Rust

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

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

SDK for SAP ABAP

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

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

SDK for Swift

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

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

더 알아보기 (Learn more)