如何将区域作为AWS Java Lambda函数的查询参数传递

时间:2019-06-17 12:17:05

标签: aws-lambda aws-java-sdk

我是AWS lambda的新手。我正在使用AWS Java Lambda函数创建ec2实例,其中我尝试使用API​​网关动态传递该区域。

我将区域传递为queryparamstring。我不确定如何在lambda函数中获取queryparam。我经历了类似的问题,但无法理解如何实现。

请找到以下java lambda函数:

package com.amazonaws.lambda.demo;

    import java.util.List;

    import org.json.simple.JSONObject;

    import com.amazonaws.auth.AWSCredentials;
    import com.amazonaws.auth.AWSStaticCredentialsProvider;
    import com.amazonaws.auth.BasicAWSCredentials;
    import com.amazonaws.regions.Regions;
    import com.amazonaws.services.ec2.AmazonEC2;
    import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
    import com.amazonaws.services.ec2.model.CreateTagsRequest;
    import com.amazonaws.services.ec2.model.DescribeInstanceStatusRequest;
    import com.amazonaws.services.ec2.model.DescribeInstanceStatusResult;
    import com.amazonaws.services.ec2.model.Instance;
    import com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification;
    import com.amazonaws.services.ec2.model.InstanceStatus;
    import com.amazonaws.services.ec2.model.RunInstancesRequest;
    import com.amazonaws.services.ec2.model.RunInstancesResult;
    import com.amazonaws.services.ec2.model.StartInstancesRequest;
    import com.amazonaws.services.ec2.model.Tag;
    import com.amazonaws.services.lambda.runtime.Context;
    import com.amazonaws.services.lambda.runtime.RequestHandler;
    import com.amazonaws.services.lambda.runtime.events.S3Event;
    import com.amazonaws.services.s3.AmazonS3;
    import com.amazonaws.services.s3.AmazonS3ClientBuilder;


    public class LambdaFunctionHandler implements RequestHandler<S3Event, String> {
         private static final AWSCredentials AWS_CREDENTIALS;
            static String ACCESS_KEY="XXXXXXXXXX";
            static String SECRET_KEY="XXXXXXXXXXXXXXXX";

            static {
                // Your accesskey and secretkey
                AWS_CREDENTIALS = new BasicAWSCredentials(
                        ACCESS_KEY,
                        SECRET_KEY
                );
            }
        private AmazonS3 s3 = AmazonS3ClientBuilder.standard().build();

        public LambdaFunctionHandler() {}

        // Test purpose only.
        LambdaFunctionHandler(AmazonS3 s3) {
            this.s3 = s3;
        }


        @Override
        public String handleRequest(S3Event event, Context context) {
            context.getLogger().log("Received event: " + event);


            // Set up the amazon ec2 client
            AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(AWS_CREDENTIALS))
                    .withRegion(Regions.EU_CENTRAL_1)
                    .build();

            // Launch an Amazon EC2 Instance
            RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-XXXX")
                    .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
                    .withMinCount(1)
                    .withMaxCount(1)
                    .withKeyName("KEY")
                    .withNetworkInterfaces(new InstanceNetworkInterfaceSpecification()
                            .withAssociatePublicIpAddress(true)
                            .withDeviceIndex(0)
                            .withSubnetId("subnet-XXX")
                            .withGroups("sg-XXXX"));

            RunInstancesResult runInstancesResult = ec2Client.runInstances(runInstancesRequest);

            Instance instance = runInstancesResult.getReservation().getInstances().get(0);
            String instanceId = instance.getInstanceId();
            String instanceip=instance.getPublicIpAddress();

            System.out.println("EC2 Instance Id: " + instanceId);

            // Setting up the tags for the instance
            CreateTagsRequest createTagsRequest = new CreateTagsRequest()
                    .withResources(instance.getInstanceId())
                    .withTags(new Tag("Name", "SampleLambdaEc2"));
            ec2Client.createTags(createTagsRequest);

            // Starting the Instance
            StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId);

            ec2Client.startInstances(startInstancesRequest);




        /*// Stopping the Instance

            StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
                      .withInstanceIds(instanceId);

                    ec2Client.stopInstances(stopInstancesRequest);*/

            //describing the instance
            DescribeInstanceStatusRequest describeInstanceRequest = new DescribeInstanceStatusRequest().withInstanceIds(instanceId);
            DescribeInstanceStatusResult describeInstanceResult = ec2Client.describeInstanceStatus(describeInstanceRequest);




           List<InstanceStatus> state = describeInstanceResult.getInstanceStatuses();
           while (state.size() < 1) { 
               // Do nothing, just wait, have thread sleep if needed
               describeInstanceResult = ec2Client.describeInstanceStatus(describeInstanceRequest);
               state = describeInstanceResult.getInstanceStatuses();
           }
           String status = state.get(0).getInstanceState().getName();

           System.out.println("status"+status);
           JSONObject response=new JSONObject();

           response.put("instanceip", instanceip);
           response.put("instancestatus", status);

           System.out.println("response=>"+response);


        return response.toString();
        }
    }

我想传递查询参数,而不是 Regions.EU_CENTRAL_1

// Set up the amazon ec2 client
            AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(AWS_CREDENTIALS))
                    .withRegion(Regions.EU_CENTRAL_1)
                    .build();

请在下面找到API配置:

enter image description here

任何有关如何实现这一目标的建议都会很有帮助。预先感谢。

1 个答案:

答案 0 :(得分:1)

你好吗?

如果要获取那些查询参数,则可能要使用Lambda代理集成。

这样,您将可以使用APIGatewayProxyRequestEvent功能,可以执行Map<String, String> getQueryStringParameters()操作。

您需要像下面这样声明处理程序:

public class APIGatewayHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
 /// You cool awesome code here! 
}

这样,您的方法将如下所示:

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {

     Map<String, String> params = event.getQueryStringParameters();
     Optional<String> region = Optional.ofNullable(params.get("region"));
     // Create EC2 instance. You may need to parse that region string to AWS Region object. 
}

让我知道这是否对您有用!