使用 管理IAM角色 AWS SDK - AWS Identity and Access Management

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 管理IAM角色 AWS SDK

以下程式碼範例顯示做法:

  • 建立 IAM 角色。

  • 連接和分離角色的政策。

  • 刪除角色。

Python
SDK for Python (Boto3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立可包裝IAM角色動作的函數。

import json import logging import pprint import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) iam = boto3.resource("iam") def create_role(role_name, allowed_services): """ Creates a role that lets a list of specified services assume the role. :param role_name: The name of the role. :param allowed_services: The services that can assume the role. :return: The newly created role. """ trust_policy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": service}, "Action": "sts:AssumeRole", } for service in allowed_services ], } try: role = iam.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy) ) logger.info("Created role %s.", role.name) except ClientError: logger.exception("Couldn't create role %s.", role_name) raise else: return role def attach_policy(role_name, policy_arn): """ Attaches a policy to a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Role(role_name).attach_policy(PolicyArn=policy_arn) logger.info("Attached policy %s to role %s.", policy_arn, role_name) except ClientError: logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name) raise def detach_policy(role_name, policy_arn): """ Detaches a policy from a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Role(role_name).detach_policy(PolicyArn=policy_arn) logger.info("Detached policy %s from role %s.", policy_arn, role_name) except ClientError: logger.exception( "Couldn't detach policy %s from role %s.", policy_arn, role_name ) raise def delete_role(role_name): """ Deletes a role. :param role_name: The name of the role to delete. """ try: iam.Role(role_name).delete() logger.info("Deleted role %s.", role_name) except ClientError: logger.exception("Couldn't delete role %s.", role_name) raise

使用包裝函數建立角色,然後連接和分離政策。

def usage_demo(): """Shows how to use the role functions.""" logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") print("-" * 88) print("Welcome to the AWS Identity and Account Management role demo.") print("-" * 88) print( "Roles let you define sets of permissions and can be assumed by " "other entities, like users and services." ) print("The first 10 roles currently in your account are:") roles = list_roles(10) print(f"The inline policies for role {roles[0].name} are:") list_policies(roles[0].name) role = create_role( "demo-iam-role", ["lambda.amazonaws.com", "batchoperations.s3.amazonaws.com"] ) print(f"Created role {role.name}, with trust policy:") pprint.pprint(role.assume_role_policy_document) policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" attach_policy(role.name, policy_arn) print(f"Attached policy {policy_arn} to {role.name}.") print(f"Policies attached to role {role.name} are:") list_attached_policies(role.name) detach_policy(role.name, policy_arn) print(f"Detached policy {policy_arn} from {role.name}.") delete_role(role.name) print(f"Deleted {role.name}.") print("Thanks for watching!")

如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 將此服務與 搭配使用 AWS SDK。本主題也包含有關入門的資訊,以及先前SDK版本的詳細資訊。