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

