AWS SDK 또는 CLI로 ListGroups 사용하기

AWS SDK 또는 CLI로 ListGroups 사용하기

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

출처: 문서

본문

SDK for .NET

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

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

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 사용자 그룹 관리' 문서를 참고하세요.

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

SDK for Go V2

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

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

SDK for JavaScript (v3)

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

그룹을 나열해요.

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

SDK for PHP

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

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

Tools for PowerShell V4

예시 1: 이 예시는 현재 AWS 계정에 정의된 모든 IAM 그룹 모음을 반환해요.

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 Reference (V4)의 ListGroups 문서를 참고하세요.

Tools for PowerShell V5

예시 1: 이 예시는 현재 AWS 계정에 정의된 모든 IAM 그룹 모음을 반환해요.

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 Reference (V5)의 ListGroups 문서를 참고하세요.

SDK for Python (Boto3)

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

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

SDK for Ruby

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

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

SDK for Rust

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

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

SDK for SAP ABAP

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

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

SDK for Swift

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

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

더 알아보기 (Learn more)