AWS: Lambda function cannot call rest api using pr

2019-07-11 23:10发布

I am creating a lambda function (having full access to ec2 instances and following actions (DescribeStream, GetRecords, GetShardIterator, ListStreams)on dynamo db stream).

My requirement is to using elb name get the private IPs of the instances and call rest API on lambda event triggered by DynamoDB stream.

My Python3.6 script for the Lambda Function is working properly to get all the private IPs.

But I don't know how to call rest API using the private IP.

I would like to inform that we have a bastion instance(having public IP), using which we can ssh by tunneling through it.

I don't know how to go about it.

My python script is below:

import boto3
import sys
import string
import subprocess

def instanaceList():
    elb_name = 'xxxx-xxx-xxx-xxx-2-BlueELB'
    print(elb_name)
    print('\n')
    print('THE LIST OF INSTANCES ATTACHED TO THIS ELB IS \n')
    elbList = boto3.client('elb')
    ec2 = boto3.resource('ec2')

    bals = elbList.describe_load_balancers()
    for elb in bals['LoadBalancerDescriptions']:

        set2 = elb['LoadBalancerName']
        if elb_name == set2 :
            inst =  elb['Instances']
            print(inst)
            for xIns in inst:
                print(xIns)
                EC2InstanceId = xIns['InstanceId']
                ec2 = boto3.resource('ec2')
                ec2instance = ec2.Instance(EC2InstanceId)
                print(ec2instance.private_ip_address)
                url = "curl -X GET https://"+ec2instance.private_ip_address+"/voice/diag -H 'cache-control: no-cache'"
                result = subprocess.call(url, shell=True)

def lambda_handler(event, context):
    print('test')
    print(event)
    instanaceList()
    return 'Hello from Lambda'

1条回答
乱世女痞
2楼-- · 2019-07-11 23:55

Assuming your issue is getting Lambda to connect ec2 instances without public IP in a VPC, then you need to give additional config to your lambda to enable it to access resources in the VPC.

Example using CLI (from https://docs.aws.amazon.com/lambda/latest/dg/vpc.html):

$  aws lambda create-function \
--function-name ExampleFunction \
--runtime python3.6 \
--role execution-role-arn \
--zip-file fileb://path/app.zip \
--handler app.handler \
--vpc-config SubnetIds=comma-separated-vpc-subnet-ids,SecurityGroupIds=comma-separated-security-group-ids \
--memory-size 1024 

Or to update config of an existing Lambda:

$ aws lambda update-function-configuration \
--function-name ExampleFunction \
--vpc-config SubnetIds=comma-separated-vpc-subnet-ids,SecurityGroupIds=security-group-ids

If your issue is actually making an API call from Python, then check out how to make post request in python

查看更多
登录 后发表回答