确认IAM角色是否存在。可使用AWS管理控制台或IAM API进行确认。
确认IAM角色是否可被附加到资源上。可通过添加适当的策略或权限来使角色可附加到资源上。
以下是一些常见的代码示例:
检查IAM角色是否存在:
import boto3
client = boto3.client('iam')
try: response = client.get_role(RoleName='my-iam-role') except client.exceptions.NoSuchEntityException: print("IAM角色不存在") else: print("IAM角色存在")
使IAM角色可被附加到资源上:
import boto3
client = boto3.client('iam')
role_name = 'my-iam-role' resource_arn = 'arn:aws:s3:::my-bucket/*'
response = client.attach_role_policy( RoleName=role_name, PolicyArn='arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess', )
response = client.attach_role_policy( RoleName=role_name, PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole', )
response = client.attach_role_policy( RoleName=role_name, PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole', )
response = client.update_assume_role_policy( RoleName=role_name, PolicyDocument='{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }', )
response = client.add_role_to_instance_profile( InstanceProfileName='my-instance-profile', RoleName=role_name, )
print("IAM角色现在可被附加到资源上")