쿠키 기본 설정 선택

당사는 사이트와 서비스를 제공하는 데 필요한 필수 쿠키 및 유사한 도구를 사용합니다. 고객이 사이트를 어떻게 사용하는지 파악하고 개선할 수 있도록 성능 쿠키를 사용해 익명의 통계를 수집합니다. 필수 쿠키는 비활성화할 수 없지만 '사용자 지정' 또는 ‘거부’를 클릭하여 성능 쿠키를 거부할 수 있습니다.

사용자가 동의하는 경우 AWS와 승인된 제3자도 쿠키를 사용하여 유용한 사이트 기능을 제공하고, 사용자의 기본 설정을 기억하고, 관련 광고를 비롯한 관련 콘텐츠를 표시합니다. 필수가 아닌 모든 쿠키를 수락하거나 거부하려면 ‘수락’ 또는 ‘거부’를 클릭하세요. 더 자세한 내용을 선택하려면 ‘사용자 정의’를 클릭하세요.

AWS SDK를 사용하여 IAM 계정 관리 - AWS SDK 코드 예제

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWS SDK를 사용하여 IAM 계정 관리

다음 코드 예제는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 계정 별칭을 가져오고 업데이트합니다.

  • 사용자 및 보안 인증에 대한 보고서를 생성합니다.

  • 계정 사용량 요약을 가져옵니다.

  • 서로의 관계를 포함하여 계정의 모든 사용자, 그룹, 역할 및 정책에 대한 세부 정보를 가져옵니다.

Python
SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

IAM 계정 작업을 래핑하는 함수를 생성합니다.

import logging import pprint import sys import time import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) iam = boto3.resource("iam") def list_aliases(): """ Gets the list of aliases for the current account. An account has at most one alias. :return: The list of aliases for the account. """ try: response = iam.meta.client.list_account_aliases() aliases = response["AccountAliases"] if len(aliases) > 0: logger.info("Got aliases for your account: %s.", ",".join(aliases)) else: logger.info("Got no aliases for your account.") except ClientError: logger.exception("Couldn't list aliases for your account.") raise else: return response["AccountAliases"] def create_alias(alias): """ Creates an alias for the current account. The alias can be used in place of the account ID in the sign-in URL. An account can have only one alias. When a new alias is created, it replaces any existing alias. :param alias: The alias to assign to the account. """ try: iam.create_account_alias(AccountAlias=alias) logger.info("Created an alias '%s' for your account.", alias) except ClientError: logger.exception("Couldn't create alias '%s' for your account.", alias) raise def delete_alias(alias): """ Removes the alias from the current account. :param alias: The alias to remove. """ try: iam.meta.client.delete_account_alias(AccountAlias=alias) logger.info("Removed alias '%s' from your account.", alias) except ClientError: logger.exception("Couldn't remove alias '%s' from your account.", alias) raise def generate_credential_report(): """ Starts generation of a credentials report about the current account. After calling this function to generate the report, call get_credential_report to get the latest report. A new report can be generated a minimum of four hours after the last one was generated. """ try: response = iam.meta.client.generate_credential_report() logger.info( "Generating credentials report for your account. " "Current state is %s.", response["State"], ) except ClientError: logger.exception("Couldn't generate a credentials report for your account.") raise else: return response def get_credential_report(): """ Gets the most recently generated credentials report about the current account. :return: The credentials report. """ try: response = iam.meta.client.get_credential_report() logger.debug(response["Content"]) except ClientError: logger.exception("Couldn't get credentials report.") raise else: return response["Content"] def get_summary(): """ Gets a summary of account usage. :return: The summary of account usage. """ try: summary = iam.AccountSummary() logger.debug(summary.summary_map) except ClientError: logger.exception("Couldn't get a summary for your account.") raise else: return summary.summary_map def get_authorization_details(response_filter): """ Gets an authorization detail report for the current account. :param response_filter: A list of resource types to include in the report, such as users or roles. When not specified, all resources are included. :return: The authorization detail report. """ try: account_details = iam.meta.client.get_account_authorization_details( Filter=response_filter ) logger.debug(account_details) except ClientError: logger.exception("Couldn't get details for your account.") raise else: return account_details

래퍼 함수를 호출하여 계정 별칭을 변경하고 계정에 대한 보고서를 가져옵니다.

def usage_demo(): """Shows how to use the account functions.""" logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Welcome to the AWS Identity and Account Management account demo.") print("-" * 88) print( "Setting an account alias lets you use the alias in your sign-in URL " "instead of your account number." ) old_aliases = list_aliases() if len(old_aliases) > 0: print(f"Your account currently uses '{old_aliases[0]}' as its alias.") else: print("Your account currently has no alias.") for index in range(1, 3): new_alias = f"alias-{index}-{time.time_ns()}" print(f"Setting your account alias to {new_alias}") create_alias(new_alias) current_aliases = list_aliases() print(f"Your account alias is now {current_aliases}.") delete_alias(current_aliases[0]) print(f"Your account now has no alias.") if len(old_aliases) > 0: print(f"Restoring your original alias back to {old_aliases[0]}...") create_alias(old_aliases[0]) print("-" * 88) print("You can get various reports about your account.") print("Let's generate a credentials report...") report_state = None while report_state != "COMPLETE": cred_report_response = generate_credential_report() old_report_state = report_state report_state = cred_report_response["State"] if report_state != old_report_state: print(report_state, sep="") else: print(".", sep="") sys.stdout.flush() time.sleep(1) print() cred_report = get_credential_report() col_count = 3 print(f"Got credentials report. Showing only the first {col_count} columns.") cred_lines = [ line.split(",")[:col_count] for line in cred_report.decode("utf-8").split("\n") ] col_width = max([len(item) for line in cred_lines for item in line]) + 2 for line in cred_report.decode("utf-8").split("\n"): print( "".join(element.ljust(col_width) for element in line.split(",")[:col_count]) ) print("-" * 88) print("Let's get an account summary.") summary = get_summary() print("Here's your summary:") pprint.pprint(summary) print("-" * 88) print("Let's get authorization details!") details = get_authorization_details([]) see_details = input("These are pretty long, do you want to see them (y/n)? ") if see_details.lower() == "y": pprint.pprint(details) print("-" * 88) pw_policy_created = None see_pw_policy = input("Want to see the password policy for the account (y/n)? ") if see_pw_policy.lower() == "y": while True: if print_password_policy(): break else: answer = input( "Do you want to create a default password policy (y/n)? " ) if answer.lower() == "y": pw_policy_created = iam.create_account_password_policy() else: break if pw_policy_created is not None: answer = input("Do you want to delete the password policy (y/n)? ") if answer.lower() == "y": pw_policy_created.delete() print("Password policy deleted.") print("The SAML providers for your account are:") list_saml_providers(10) print("-" * 88) print("Thanks for watching.")
SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

IAM 계정 작업을 래핑하는 함수를 생성합니다.

import logging import pprint import sys import time import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) iam = boto3.resource("iam") def list_aliases(): """ Gets the list of aliases for the current account. An account has at most one alias. :return: The list of aliases for the account. """ try: response = iam.meta.client.list_account_aliases() aliases = response["AccountAliases"] if len(aliases) > 0: logger.info("Got aliases for your account: %s.", ",".join(aliases)) else: logger.info("Got no aliases for your account.") except ClientError: logger.exception("Couldn't list aliases for your account.") raise else: return response["AccountAliases"] def create_alias(alias): """ Creates an alias for the current account. The alias can be used in place of the account ID in the sign-in URL. An account can have only one alias. When a new alias is created, it replaces any existing alias. :param alias: The alias to assign to the account. """ try: iam.create_account_alias(AccountAlias=alias) logger.info("Created an alias '%s' for your account.", alias) except ClientError: logger.exception("Couldn't create alias '%s' for your account.", alias) raise def delete_alias(alias): """ Removes the alias from the current account. :param alias: The alias to remove. """ try: iam.meta.client.delete_account_alias(AccountAlias=alias) logger.info("Removed alias '%s' from your account.", alias) except ClientError: logger.exception("Couldn't remove alias '%s' from your account.", alias) raise def generate_credential_report(): """ Starts generation of a credentials report about the current account. After calling this function to generate the report, call get_credential_report to get the latest report. A new report can be generated a minimum of four hours after the last one was generated. """ try: response = iam.meta.client.generate_credential_report() logger.info( "Generating credentials report for your account. " "Current state is %s.", response["State"], ) except ClientError: logger.exception("Couldn't generate a credentials report for your account.") raise else: return response def get_credential_report(): """ Gets the most recently generated credentials report about the current account. :return: The credentials report. """ try: response = iam.meta.client.get_credential_report() logger.debug(response["Content"]) except ClientError: logger.exception("Couldn't get credentials report.") raise else: return response["Content"] def get_summary(): """ Gets a summary of account usage. :return: The summary of account usage. """ try: summary = iam.AccountSummary() logger.debug(summary.summary_map) except ClientError: logger.exception("Couldn't get a summary for your account.") raise else: return summary.summary_map def get_authorization_details(response_filter): """ Gets an authorization detail report for the current account. :param response_filter: A list of resource types to include in the report, such as users or roles. When not specified, all resources are included. :return: The authorization detail report. """ try: account_details = iam.meta.client.get_account_authorization_details( Filter=response_filter ) logger.debug(account_details) except ClientError: logger.exception("Couldn't get details for your account.") raise else: return account_details

래퍼 함수를 호출하여 계정 별칭을 변경하고 계정에 대한 보고서를 가져옵니다.

def usage_demo(): """Shows how to use the account functions.""" logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Welcome to the AWS Identity and Account Management account demo.") print("-" * 88) print( "Setting an account alias lets you use the alias in your sign-in URL " "instead of your account number." ) old_aliases = list_aliases() if len(old_aliases) > 0: print(f"Your account currently uses '{old_aliases[0]}' as its alias.") else: print("Your account currently has no alias.") for index in range(1, 3): new_alias = f"alias-{index}-{time.time_ns()}" print(f"Setting your account alias to {new_alias}") create_alias(new_alias) current_aliases = list_aliases() print(f"Your account alias is now {current_aliases}.") delete_alias(current_aliases[0]) print(f"Your account now has no alias.") if len(old_aliases) > 0: print(f"Restoring your original alias back to {old_aliases[0]}...") create_alias(old_aliases[0]) print("-" * 88) print("You can get various reports about your account.") print("Let's generate a credentials report...") report_state = None while report_state != "COMPLETE": cred_report_response = generate_credential_report() old_report_state = report_state report_state = cred_report_response["State"] if report_state != old_report_state: print(report_state, sep="") else: print(".", sep="") sys.stdout.flush() time.sleep(1) print() cred_report = get_credential_report() col_count = 3 print(f"Got credentials report. Showing only the first {col_count} columns.") cred_lines = [ line.split(",")[:col_count] for line in cred_report.decode("utf-8").split("\n") ] col_width = max([len(item) for line in cred_lines for item in line]) + 2 for line in cred_report.decode("utf-8").split("\n"): print( "".join(element.ljust(col_width) for element in line.split(",")[:col_count]) ) print("-" * 88) print("Let's get an account summary.") summary = get_summary() print("Here's your summary:") pprint.pprint(summary) print("-" * 88) print("Let's get authorization details!") details = get_authorization_details([]) see_details = input("These are pretty long, do you want to see them (y/n)? ") if see_details.lower() == "y": pprint.pprint(details) print("-" * 88) pw_policy_created = None see_pw_policy = input("Want to see the password policy for the account (y/n)? ") if see_pw_policy.lower() == "y": while True: if print_password_policy(): break else: answer = input( "Do you want to create a default password policy (y/n)? " ) if answer.lower() == "y": pw_policy_created = iam.create_account_password_policy() else: break if pw_policy_created is not None: answer = input("Do you want to delete the password policy (y/n)? ") if answer.lower() == "y": pw_policy_created.delete() print("Password policy deleted.") print("The SAML providers for your account are:") list_saml_providers(10) print("-" * 88) print("Thanks for watching.")
프라이버시사이트 이용 약관쿠키 기본 설정
© 2025, Amazon Web Services, Inc. 또는 계열사. All rights reserved.