如何使用 Amazon PHP SDK 2 获取 EC2 实例列表?

2021-12-21 00:00:00 amazon-ec2 php

如何使用 AWS SDK for PHP 2 获取与某些过滤器匹配的 Amazon EC2 实例列表?

How to get list of Amazon EC2 instances matching some filters using AWS SDK for PHP 2?

推荐答案

使用 DescribeInstances 方法.让我们详细介绍一下.

Use DescribeInstances method for this. Let's cover this with some more details.

您需要先获取 Ec2Client 实例.最简单的客户端初始化方式:

You need to get Ec2Client instance first. The easiest way to initialize the client:

$config = array();
$config['key'] = 'key';
$config['secret'] = 'secret';
$config['region'] = 'us-east-1';
$config['version'] = 'latest'; // Or Specified
$ec2Client = AwsEc2Ec2Client::factory($config);

然后只需调用 DescribeInstances 方法.

And then just call DescribeInstances method.

$result = $ec2Client->DescribeInstances(array(
        'Filters' => array(
                array('Name' => 'instance-type', 'Values' => array('m1.small')),
        )
));

您可以在亚马逊上获取可用过滤器列表DescribeInstances API 方法页面.

You can get list of available filters on the Amazon DescribeInstances API method page.

但是等等,这里有什么困难?

But wait, what might be difficult here?

  • 注意参数名称Filters.在 API 中它被称为 Filter
  • 参数Values的调用方式与API不同,是一个数组
  • Note the parameter name Filters. In the API it is called Filter
  • Parameter Values is called different from API and it is an array

是的,这在文档中都有描述.但是,如果您查看一些旧 API 使用示例您可以看到语法发生了变化,这可能真的很难注意到在这些示例中必须更新哪些内容才能使其正常工作.

Yes, this is all described in the documentation. But if you look at some Old API usage samples you can see that the syntax has changed and this might be really hard to notice what have to be updated in that examples to make things working.

为了完成这个例子,让我展示一些简单的结果输出.

And to complete the example let me show some simple output of the results.

$reservations = $result['Reservations'];
foreach ($reservations as $reservation) {
    $instances = $reservation['Instances'];
    foreach ($instances as $instance) {

        $instanceName = '';
        foreach ($instance['Tags'] as $tag) {
            if ($tag['Key'] == 'Name') {
                $instanceName = $tag['Value'];
            }
        }


        echo 'Instance Name: ' . $instanceName . PHP_EOL;
        echo '---> State: ' . $instance['State']['Name'] . PHP_EOL;
        echo '---> Instance ID: ' . $instance['InstanceId'] . PHP_EOL;
        echo '---> Image ID: ' . $instance['ImageId'] . PHP_EOL;
        echo '---> Private Dns Name: ' . $instance['PrivateDnsName'] . PHP_EOL;
        echo '---> Instance Type: ' . $instance['InstanceType'] . PHP_EOL;
        echo '---> Security Group: ' . $instance['SecurityGroups'][0]['GroupName'] . PHP_EOL;
    }

}

相关文章