如何基于托管在amazon的EC2实例ip获取aws账号/id我有一个实例名称CTI服务器,它托管在一个AWS帐户中。我有CTI服务器的详细信息,比如私人ip和主机,可以通过putty进行ssh。我想要AWS帐号/AWS帐号ID创建此实例的位置。他们的任何命令都可以在不登录aws控制台的情况下找到账号吗
您可以通过查询实例元数据从EC2实例中获取帐号。元数据位于http://169.254.169.254/latest/dynamic/instance-identity/document.
如果IAM角色附加到实例,则可以使用以下方法检索它:
aws sts get-caller-identity
此信息在动态实例元数据中可用。它可以通过多种不同的方式提取。
jq
jq
JSON解析器是目前可用的最佳方法,它预装在AWS Linux AMI上。
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .accountId
我在网上发现的大多数其他方法都倾向于进行长链的进程调用,如grep | sed | awk
等,这并不理想。因此,我探索了一些替代方案,试图将解析限制在一个额外的过程中。
sed
我能想到的最好的替代方案是使用sed
和扩展正则表达式,只使用一个管道。另外,与其他解决方案不同的是,这甚至可以处理(人为的(场景,即在accountId:中间使用(转义的(双引号
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | sed -nE 's/.*"accountId"s*:s*"(.*)".*/1/p'
或者,使用普通BRE:时可读性稍差
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | sed -n 's/.*"accountId"s*:s*"(.*)".*/1/p'
grep
grep
是一个选项,但需要具有PCRE支持的GNU grep:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep -oP '"accountId"s*:s*"K[^"]+'
grep|cut
这种更便携的替代方案需要额外的步骤(如果避免使用awk
等较重的工具(,但也更简单易懂:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep '"region"' | cut -d" -f4
grep
输出如下:
"region" : "us-east-1"
然后cut
将在双引号上拆分并选择第四个字段。
awk
我尽量避免将awk用于类似这样的简单用途,但它显然可以一步完成上述操作。有时它可能是唯一可用的选项(例如busybox(:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | awk -F'"' '/"accountId"/ { print $4 }'
如果没有jq,您可以使用这个。
curl http://169.254.169.254/latest/dynamic/instance-identity/document|grep accountId| awk '{print $3}'|sed 's/"//g'|sed 's/,//g'
以下将为您提供AWS帐户ID:
curl http://169.254.169.254/latest/meta-data/network/interfaces/macs/02:a2:1f:d5:fe:0f/owner-id
这里有一个使用元数据而不使用jq 的解决方案
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | sed '2q;d' |cut -d : -f2 | awk -F" '{print $2}'