AWS跨账户访问是指在一个AWS账户中的资源(例如S3存储桶、EC2实例等)可以被另一个AWS账户中的用户访问。以下是一个解决AWS跨账户访问问题的示例代码:
import boto3
def create_role(role_name, trusted_account_id, trusted_account_name):
iam_client = boto3.client('iam')
assume_role_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": f"arn:aws:iam::{trusted_account_id}:root"
},
"Action": "sts:AssumeRole"
}
]
}
response = iam_client.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps(assume_role_policy_document),
Description=f"Role for cross-account access from {trusted_account_name}"
)
return response['Role']['Arn']
import boto3
def create_s3_access_policy(policy_name, bucket_name):
iam_client = boto3.client('iam')
policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket"
],
"Resource": [
f"arn:aws:s3:::{bucket_name}",
f"arn:aws:s3:::{bucket_name}/*"
]
}
]
}
response = iam_client.create_policy(
PolicyName=policy_name,
PolicyDocument=json.dumps(policy_document)
)
return response['Policy']['Arn']
def attach_policy_to_role(policy_arn, role_name):
iam_client = boto3.client('iam')
response = iam_client.attach_role_policy(
PolicyArn=policy_arn,
RoleName=role_name
)
import boto3
def create_iam_user(user_name, role_arn):
iam_client = boto3.client('iam')
response = iam_client.create_user(UserName=user_name)
user_arn = response['User']['Arn']
iam_client.tag_user(
UserName=user_name,
Tags=[
{
'Key': 'CrossAccountAccessRole',
'Value': role_arn
}
]
)
return user_arn
import boto3
def assume_role(role_arn):
sts_client = boto3.client('sts')
response = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName='CrossAccountAccess'
)
return response['Credentials']
这些代码示例提供了一种解决AWS跨账户访问问题的方法。您可以根据自己的需求进行调整和修改。