Describe ec2 with boto3 and retrieve the value

I'm Wakamatsu, a beginner of Lambda (Python).

Suddenly, do you use Lambda?

The code works without a server. It's attractive, isn't it?

After all, the times are Serverless. I wish I could use about one language in the infrastructure.

In the middle of a generous generation that doesn't go against such a trend, I finally stepped into Lambda.

The introduction has become longer, but I hope that the infrastructure shop will look warmly with the feeling that they are struggling to make a joke.

Thing you want to do

I want to get the instance ID of an instance that has a specific IP.

environment

AWS Lambda Python 3.6

First form

code

For the time being, I decided to retrieve all the instance information, so I wrote the following code.

import boto3

def lambda_handler(event, context):

    ec2 = boto3.client('ec2')
    
    responce = ec2.describe_instances()

    return responce

result

Return fails with the following error

{
  "errorMessage": "An error occurred during JSON serialization of response",
  "errorType": "datetime.datetime(2017, 5, 11, 5, 15, 59, tzinfo=tzlocal()) is not JSON serializable"
}

It seems that the result itself cannot be treated as JSON.

Investigation

When I call the boto3 reference, it seems that the return value of describe_instances is of type dict (dictionary). For the time being, it is better to output with print, so I decided to change the code.

Second form

code

Change the output to a print statement for the time being

import boto3

def lambda_handler(event, context):

    ec2 = boto3.client('ec2')
    
    responce = ec2.describe_instances()

    print(responce)

    return

result

The following was output to the log. That's what you often see in the AWS CLI results.

{
    "Reservations": [
        {
            "OwnerId": "xxxxxxxxxxxx", 
            "ReservationId": "r-xxxxxxxxxxxxxxxxx", 
            "Groups": [], 
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    }, 
                    "PublicDnsName": "ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com", 
                    "Platform": "xxxxxxx", 
                    "State": {
                        "Code": 80, 
                        "Name": "stopped"
                    }, 
                    "EbsOptimized": false, 
                    "LaunchTime": "xxxx-xx-xxxxx:xx:xx.xxxx", 
                    "PublicIpAddress": "xxx.xxx.xxx.xxx", 
                    "PrivateIpAddress": "xxx.xxx.xxx.xxx", 
                    "ProductCodes": [], 
                    "VpcId": "vpc-xxxxxxx", 
                    "StateTransitionReason": "", 
                    "InstanceId": "i-xxxxxxxxxxxxxxxxx", 
                    "EnaSupport": true, 
                    "ImageId": "ami-xxxxxxxx", 
The following is omitted

Investigation

Next, I would like to narrow down by IP. It seems that --filter in AWS CLI is also in boto3, so I decided to use it.

Third form

code

Added Filters to narrow down to instances that have a specific IP

import boto3

def lambda_handler(event, context):

    ec2 = boto3.client('ec2')
    
    responce = ec2.describe_instances(
        Filters=[{'Name':'network-interface.addresses.private-ip-address','Values':["xxx.xxx.xxx.xxx"]}]
    )

    print(responce)

    return

result

Narrowed down to instances with the specified IP address.

Investigation

Next, narrow down the return value to the instance ID. The image is --query in AWS CLI, but it doesn't seem to be in boto3. I had a hard time because I was danced by the information on the internet because I was converting to JSON here. As a result, I found that the dict type seems to be able to retrieve the value by writing ["hoge"] ["fuga"] after the object.

Final form

code

import boto3

def lambda_handler(event, context):

    ec2 = boto3.client('ec2')
    
    responce = ec2.describe_instances(
        Filters=[{'Name':'network-interface.addresses.private-ip-address','Values':["xxx.xxx.xxx.xxx"]}]
    )["Reservations"][0]["Instances"][0]["InstanceId"]

    print(responce)

    return

result

Congratulations on getting the instance ID. I want to be aware that you need to explicitly write 0 as [0] when you have a list.

Summary

What did you think. The content I am doing is very rudimentary, but I was addicted to it, so I summarized it as a memorandum.

It's surprisingly easy to move, so please give it a try. Lambda I'm not scared.

Recommended Posts

Describe ec2 with boto3 and retrieve the value
Extract the maximum value with pandas and change that value
read the tag assigned to you on ec2 with boto3
Extract the maximum value with pandas.
Save and retrieve files with Pepper
Phenomenon that the numerical value changes slightly with Pandas and its response
Use Jupyter Lab and Jupyter Notebook with EC2
Find the SHA256 value with R (with bonus)
Use numpy's .flatten () [0] to retrieve the value
Fill the missing value (null) of DataFrame with the values before and after with pyspark
[Python Tips] How to retrieve multiple keys with the maximum value from the dictionary
Scraping the holojour and displaying it with CLI
Find the mood value with python (Rike Koi)
Manage AWS nicely with the Python library Boto
Solving the Lorenz 96 model with Julia and Python
Archive and compress the entire directory with python
Describe the multi-stage ssh destination in the config, log in easily, and copy the file with scp
Let's transpose the matrix with numpy and multiply the matrices.
How to retrieve the nth largest value in Python
code-server online environment (3) Launch an EC2 instance with Boto3
Create Amazon Linux with AWS EC2 and log in
Manipulate S3 objects with Boto3 (high-level API and low-level API)
[Boto3] Search for Cognito users with the List Users API
Take the value of SwitchBot thermo-hygrometer with Raspberry Pi
Log the value of SwitchBot thermo-hygrometer with Raspberry Pi
Extract files from EC2 storage with the scp command
Get comments and subscribers with the YouTube Data API
Install the latest stable Python with pyenv (both 2 and 3)
Install Ubuntu 20.04 with GUI and prepare the development environment
POST the image with json and receive it with flask
[Django 2.2] Sort and get the value of the relation destination
Build AWS EC2 and RDS with Terraform Terraform 3 minutes cooking
use something other than the default profile with boto3
Call the C function with dart: ffi and call the Dart function callback