135

寻找一种快速提取我的帐号的方法,我原本想使用aws iam get-account-authorization-details --max-items 1,但这样做有几个问题。有没有办法做到这一点,可能不会跨帐户来源?

4

4 回答 4

279

您可以使用以下命令从Secure Token Service子命令中获取帐号:get-caller-identity

aws sts get-caller-identity --query Account --output text
于 2016-10-19T02:28:00.417 回答
35

从我对 AWS PowerShell CLI 的相关回答中,您的账户 ID 是您创建的资源 Arn 的一部分......以及为您自动创建的资源。一些资源还会将您列为 OwnerId。

默认安全组是在每个区域的默认 VPC 中自动为您创建的,作为预留安全组。从文档中:

您不能删除默认安全组。如果您尝试删除 EC2-Classic 默认安全组,您将收到以下错误:Client.InvalidGroup.Reserved: The security group 'default' is reserved。如果您尝试删除 VPC 默认安全组,您将收到以下错误:Client.CannotDelete: the specified group: "sg-51530134" name: "default" cannot be deleted by a user。

这使它成为检索我们账户 ID 的可靠候选者,只要您使用 EC2 经典版或拥有默认 VPC(*如果您没有,请参阅边缘案例)。

例子:

aws ec2 describe-security-groups \
    --group-names 'Default' \
    --query 'SecurityGroups[0].OwnerId' \
    --output text

这用于--query将此请求的第一个结果的输出过滤到“所有者 ID”,然后用于--output将您的帐户 ID 输出为纯文本:

123456781234

边缘情况:

(感谢@kenchew)请注意,如果您已删除给定区域中的默认 VPC,则此安全组不再存在,您应该使用以下替代解决方案之一:

进一步阅读:

于 2015-11-18T22:03:49.410 回答
10

如果您在以假定角色运行的服务器上运行,则无法调用aws sts get-caller-identity. 此外,describe-security-groups您不能总是使用--group-names过滤器(如果您没有默认 VPC,则它不起作用),因此只需选择第一个安全组。我发现无论您使用哪种身份验证或拥有哪种 VPC,这都是最可靠的。

aws ec2 describe-security-groups --query 'SecurityGroups[0].OwnerId' --output text
于 2016-12-01T06:11:57.657 回答
5

我最喜欢的方法是使用aws iam get-user [--profile <profile>],因为您只需要 IAM 自助服务角色即可。

于 2018-07-31T17:57:27.930 回答