【问题标题】:How to check if an ec2 instance is running or not with an if statement?如何使用 if 语句检查 ec2 实例是否正在运行?
【发布时间】:2019-11-03 21:38:34
【问题描述】:

我有一个 ec2 实例的实例 ID。如何使用 if 语句检查该 ec2 实例是否正在运行?我正在使用 Python 和 Boto3。

【问题讨论】:

  • 这应该有助于https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instance_status
  • 你有什么代码可以分享吗?

标签: python amazon-web-services amazon-ec2 aws-sdk boto3


【解决方案1】:

使用boto3资源方法:

import boto3

ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')

instance = ec2_resource.Instance('i-12345')
if instance.state['Name'] == 'running':
    print('It is running')

使用boto3客户端方法:

import boto3

ec2_client = boto3.client('ec2', region_name='ap-southeast-2')

response = ec2_client.describe_instance_status(InstanceIds=['i-12345'])
if response['InstanceStatuses'][0]['InstanceState']['Name'] == 'running':
    print('It is running')

【讨论】:

    【解决方案2】:

    我认为重要的是默认情况下,只描述正在运行的实例。因此,如果您想检查没有必要运行的实例的状态,则需要指定“IncludeAllInstances”选项。所以它应该是这样的:

    response = ec2_client.describe_instance_status(InstanceIds=['i-12345'], IncludeAllInstances=True)
    if response['InstanceStatuses'][0]['InstanceState']['Name'] == 'running':
        print('It is running')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      相关资源
      最近更新 更多