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.
I want to get the instance ID of an instance that has a specific IP.
AWS Lambda Python 3.6
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
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.
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.
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
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
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.
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
Narrowed down to instances with the specified IP address.
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.
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
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.
[] in --query of AWS CLI.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