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

如何在AWS EKS on Fargate环境下以编程方式获取AWS账号ID(不使用aws sts get-caller-identity)

获取AWS EKS Fargate上的账号ID(无需aws sts get-caller-identity)

Great question! Since the EC2 instance metadata service isn't accessible on Fargate, here are two reliable workarounds to grab your AWS account ID without relying on aws sts get-caller-identity:

方法1:从IAM角色ARN文件提取

When your Fargate pod uses an IAM role via IRSA (the standard way to grant permissions to EKS pods), Kubernetes mounts the role's ARN into the container at this path: /var/run/secrets/eks.amazonaws.com/serviceaccount/role-arn. The ARN follows the format arn:aws:iam::123456789012:role/your-role-name — the 5th segment (split by colons) is your account ID.

You can extract it with a simple bash command:

ACCOUNT_ID=$(cat /var/run/secrets/eks.amazonaws.com/serviceaccount/role-arn | cut -d':' -f5)
echo $ACCOUNT_ID

方法2:用Kubernetes Downward API注入环境变量

If you want to make the account ID available as an environment variable from the start, you can use Kubernetes' Downward API to inject the role ARN annotation into your pod, then extract the account ID from that.

First, update your pod definition to include the environment variable:

apiVersion: v1
kind: Pod
metadata:
  name: my-fargate-app
  annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/my-fargate-service-role
spec:
  containers:
  - name: app-container
    image: your-app-image:latest
    env:
    - name: SERVICE_ROLE_ARN
      valueFrom:
        fieldRef:
          fieldPath: metadata.annotations['eks.amazonaws.com/role-arn']

Then inside the container, extract the account ID like this:

ACCOUNT_ID=$(echo $SERVICE_ROLE_ARN | cut -d':' -f5)
echo $ACCOUNT_ID

Both methods work without needing the AWS CLI installed, and they leverage the native IRSA setup that's required for Fargate pods to interact with AWS services anyway.

内容的提问来源于stack exchange,提问作者d.a.d.a

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:42:47