1
1

More than 3 years have passed since last update.

AWSのLambdaでタグのついているインスタンスの情報を辞書形式で取得する方法

Posted at

EC2インスタンスを自動起動したり自動停止したりするLambdaをつくるときに使います。Lambdaをつくってもすぐに忘れるので残します。

Lambda関数

  • ランタイム : Python3.8
# -*- coding: utf-8 -*-

from __future__ import print_function

import boto3

# インスタンスがあるリージョンを指定する
REGION_NAME = 'us-east-2'
# インスタンスの状態をリストで指定する
STATE_LIST = ['running','stopped']
# インスタンスにつけているタグの名前をリストで指定する
TAG_LIST = ['Name','AutoStop']

def get_instance_list(ec2):
    """
    タグとステータスを指定してインスタンスを取得する.
    """
    instances = ec2.describe_instances(
        Filters=[
            {'Name': 'instance-state-name', 'Values': STATE_LIST},
            {'Name': 'tag-key', 'Values': TAG_LIST}
        ]
    )['Reservations']

    if len(instances) != 0:
        instances = instances[0]['Instances']

    return instances

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', REGION_NAME)

    instances = get_instance_list(ec2)
    print(instances)

    return 0

定数に設定する内容

キャプチャ.PNG

関数を実行するための権限

上記の関数では describe_instances を使用するため、ec2:DescribeInstancesをIAMのポリシーに設定する必要がある。

IAMポリシー例
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstances"
            ],
            "Resource": "*"
        }
    ]
}

取得できるインスタンス情報

取得できる辞書形式のインスタンス情報は、EC2 — Boto 3 Docs 1.12.31 documentation - describe_instancesの「Returns」に記載されているInstancesキーの内容となる。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1