如何从 ec2 实例中获取实例 ID?

如何从 ec2 实例中获取实例 ID?

<p>如何从 ec2 实例中找出 ec2 实例的实例 ID?</p>
如何从 ec2 实例中获取实例 ID? 2022-09-01 14:38:17
如何从 ec2 实例中获取实例 ID? 0
如何从 ec2 实例中获取实例 ID?
<p>请参阅<a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html" target="_blank">有关该主题的 EC2 文档</a>。<br /> 运行:</p> <pre><code class="lang-">wget -q -O - http://169.254.169.254/latest/meta-data/instance-id </code></pre> <p>如果您需要从脚本中以编程方式访问实例 ID,</p> <pre><code class="lang-">die() { status=$1; shift; echo &quot;FATAL: $*&quot;; exit $status; } EC2_INSTANCE_ID=&quot;`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \&quot;wget instance-id has failed: $?\&quot;`&quot; </code></pre> <p>下面是一个更高级的使用示例(检索实例ID以及可用性区域和区域等):</p> <pre><code class="lang-">EC2_INSTANCE_ID=&quot;`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \&quot;wget instance-id has failed: $?\&quot;`&quot; test -n &quot;$EC2_INSTANCE_ID&quot; || die 'cannot obtain instance-id' EC2_AVAIL_ZONE=&quot;`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone || die \&quot;wget availability-zone has failed: $?\&quot;`&quot; test -n &quot;$EC2_AVAIL_ZONE&quot; || die 'cannot obtain availability-zone' EC2_REGION=&quot;`echo \&quot;$EC2_AVAIL_ZONE\&quot; | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`&quot; </code></pre> <p>您也可以使用 curl 而不是 wget,具体取决于您的平台上安装的内容。</p>