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

如何获取AWS联合用户名以配置Terraform的aws_iam_user_policy_attachment

获取AWS联合用户名称的方法(无需CloudTrail)

你需要获取AWS联合用户名称,用于Terraform的aws_iam_user_policy_attachment资源配置:

resource "aws_iam_user_policy_attachment" "test-attach" {
  user       = aws_iam_user.user.name
  policy_arn = aws_iam_policy.policy.arn
}

目前你能通过拼接得到格式为"arn:aws:sts::<account_id>:federated-user/<role_name>/<user_id>"的ARN,也可通过aws sts get-caller-identity得到类似"arn:aws:sts::<account_id>:assumed-role/<role_name>/<user_id>"的ARN,以下是无需创建CloudTrail的获取方法:

方法1:通过AWS CLI解析调用者身份输出

直接解析aws sts get-caller-identity的返回结果,提取联合用户名称:

  • 使用jq工具提取:
    aws sts get-caller-identity | jq -r '.Arn' | awk -F '/' '{print $NF}'
    
  • 若没有jq,用AWS CLI内置的--query参数:
    aws sts get-caller-identity --query 'Arn' --output text | cut -d '/' -f 3
    
    注:如果ARN格式为arn:aws:sts::<account_id>:federated-user/<role_name>/<user_id>,cut -d '/' -f 3会提取最后的<user_id>部分,即联合用户名称。

方法2:通过AWS SDK编程获取

以Python的boto3为例,直接调用STS API并解析ARN:

import boto3

sts_client = boto3.client('sts')
caller_info = sts_client.get_caller_identity()
arn_segments = caller_info['Arn'].split('/')
federated_user_name = arn_segments[-1]
print(federated_user_name)

注意事项

aws_iam_user_policy_attachment资源仅适用于永久IAM用户,而联合用户(federated-user)或角色会话(assumed-role)属于临时身份,无法直接用该资源绑定策略。如果要为临时会话附加权限,建议通过角色的信任策略配置,或在调用assume-role时指定会话策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:02:08