如何使用 if 语句检查 ec2 实例是否为 运行?

How to check if an ec2 instance is running or not with an if statement?

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

使用 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')

我认为重要的是默认情况下,仅描述 运行 个实例。因此,如果你想检查实例的状态,不需要 运行,那么你需要指定“IncludeAllInstances”选项。所以它应该是这样的:

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