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

无需凭证在EC2实例用多配置文件访问不同SecretsManager密钥

需求可行性及配置方案

你的需求完全可行,核心思路是通过IAM角色细分+CLI配置STS AssumeRole实现权限隔离,同时限制默认凭证的访问权限。具体步骤如下:

1. 调整EC2关联的主IAM角色权限

首先修改当前EC2绑定的主IAM角色,移除所有直接访问SecretsManager密钥的权限,仅保留允许它扮演两个细分权限角色的权限。示例权限策略如下:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": [
                "arn:aws:iam::你的AWS账号ID:role/SecretAccess-Role-Key1",
                "arn:aws:iam::你的AWS账号ID:role/SecretAccess-Role-Key2"
            ]
        }
    ]
}

此配置确保默认情况下(EC2实例元数据提供的主角色凭证)无法访问任何密钥,满足你“默认配置文件无权限”的要求。

2. 创建两个细分权限的IAM角色

分别创建两个仅能访问单个密钥的IAM角色:

角色1(仅访问密钥Key1)

  • 信任策略:允许EC2主角色作为可信实体,示例:
    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "AWS": "arn:aws:iam::你的AWS账号ID:role/EC2绑定的主角色名称"
                },
                "Action": "sts:AssumeRole"
            }
        ]
    }
    
  • 权限策略:仅允许访问指定密钥Key1,示例:
    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "secretsmanager:GetSecretValue",
                    "secretsmanager:DescribeSecret"
                ],
                "Resource": "arn:aws:secretsmanager:你的区域:你的AWS账号ID:secret:Key1的完整ARN"
            }
        ]
    }
    

角色2(仅访问密钥Key2)

重复上述步骤,将权限策略中的Resource替换为Key2的ARN即可。

3. 配置EC2实例上的AWS CLI配置文件

编辑EC2实例中的~/.aws/config文件,添加两个自定义profile,指定要扮演的细分角色:

[default]
# 无需额外配置,实例会自动从元数据获取主角色凭证(已无密钥访问权限)
[profile key1-access]
role_arn = arn:aws:iam::你的AWS账号ID:role/SecretAccess-Role-Key1
source_profile = default
region = 你的AWS区域
[profile key2-access]
role_arn = arn:aws:iam::你的AWS账号ID:role/SecretAccess-Role-Key2
source_profile = default
region = 你的AWS区域

4. 验证配置

  • 默认profile访问密钥:aws secretsmanager get-secret-value --secret-id Key1 → 提示权限不足
  • 用key1-access profile访问Key1:aws --profile key1-access secretsmanager get-secret-value --secret-id Key1 → 成功返回密钥内容
  • 用key1-access profile访问Key2:aws --profile key1-access secretsmanager get-secret-value --secret-id Key2 → 提示权限不足
  • Key2的profile验证逻辑同上

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:25:16