You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署在AWS账户A1的EC2脚本如何无密钥访问多AWS账户?

Key-Free Cross-Account AWS Access from Your EC2 Instance

Absolutely, you’ve got solid, secure options to access those 10 AWS accounts without hardcoding or relying on long-term AWS_ACCESS_KEY/SECRET_KEY values. Here are the most practical approaches tailored to your setup:

1. Cross-Account IAM Roles (The Industry Standard)

This is the go-to method for secure cross-account access, relying on temporary, short-lived credentials instead of static keys. Here’s how to set it up:

Step 1: Configure Roles in Target Accounts

For each of the 10 target AWS accounts:

  • Create an IAM role (e.g., AllowAccessFromAccountA1).
  • Set the trust policy to allow your account A1’s EC2 instance role (or the entire account A1) to assume this role. Example trust policy snippet:
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "AWS": "arn:aws:iam::ACCOUNT_A1_ID:role/YourEC2InstanceRole"
          },
          "Action": "sts:AssumeRole"
        }
      ]
    }
    
  • Attach a permissions policy to this role that grants only the specific actions you need (e.g., s3:ListBucket, ec2:DescribeInstances—stick to the principle of least privilege).

Step 2: Update Your EC2 Instance’s Role in Account A1

In account A1, edit the IAM role attached to your EC2 instance to add a policy allowing it to assume all the target account roles. Example policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sts:AssumeRole",
      "Resource": [
        "arn:aws:iam::TARGET_ACCOUNT_1:role/AllowAccessFromAccountA1",
        "arn:aws:iam::TARGET_ACCOUNT_2:role/AllowAccessFromAccountA1",
        // Add all 10 target role ARNs here
      ]
    }
  ]
}

Step 3: Use the Role in Your Python Script

With roles configured, your script can leverage the EC2 instance’s default IAM role to assume each target account’s role and fetch temporary credentials. Here’s a boto3 example:

import boto3

def get_target_account_client(target_role_arn, service_name):
    # Initialize STS client using the EC2 instance's default role (no keys needed!)
    sts_client = boto3.client('sts')
    
    # Assume the target account's role
    assume_role_response = sts_client.assume_role(
        RoleArn=target_role_arn,
        RoleSessionName=f"CrossAccountSession-{service_name}"
    )
    
    # Extract temporary credentials
    temp_creds = assume_role_response['Credentials']
    
    # Return a client for the desired service using temp credentials
    return boto3.client(
        service_name,
        aws_access_key_id=temp_creds['AccessKeyId'],
        aws_secret_access_key=temp_creds['SecretAccessKey'],
        aws_session_token=temp_creds['SessionToken']
    )

# Example usage: Access S3 in target account 1
s3_client = get_target_account_client(
    "arn:aws:iam::TARGET_ACCOUNT_1:role/AllowAccessFromAccountA1",
    "s3"
)
print(s3_client.list_buckets())

2. AWS Resource Access Manager (RAM) (For Organization Members)

If all 11 accounts (A1 + 10 targets) are part of the same AWS Organization, AWS RAM simplifies cross-account access:

  • Create shared permission sets in your organization’s management account.
  • Grant access to your account A1’s EC2 role to use these permission sets across target accounts.
  • This eliminates the need to create individual roles in each target account, making management easier at scale.

Critical Best Practices

  • Least Privilege: Never grant broader permissions than needed. Tailor each target role’s policy to only the actions your script performs.
  • Audit: Use AWS CloudTrail to log all sts:AssumeRole calls and actions taken with temporary credentials for full accountability.
  • Session Duration: Temporary credentials expire after 1 hour by default; you can extend this up to 12 hours by configuring the target role’s maximum session duration.

内容的提问来源于stack exchange,提问作者Shubho Shaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 07:33:11