如何将区域作为 aws java lambda 函数的查询参数传递
How to pass region as query param for aws java lambda function
我是 AWS lambda 的新手。我正在使用 AWS java Lambda 函数创建 ec2 实例,我在其中尝试使用 API 网关动态传递区域。
我将区域作为查询参数字符串传递。我不确定如何在 lambda 函数中获取查询参数。我已经完成了与此类似的问题,但无法理解如何实现它。
请找到以下 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 配置:
关于如何实现这一目标的任何建议都将非常有帮助。提前致谢。
你好吗?
如果您想获取这些查询参数,您可能需要使用 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.
}
让我知道这是否适合您!
我是 AWS lambda 的新手。我正在使用 AWS java Lambda 函数创建 ec2 实例,我在其中尝试使用 API 网关动态传递区域。
我将区域作为查询参数字符串传递。我不确定如何在 lambda 函数中获取查询参数。我已经完成了与此类似的问题,但无法理解如何实现它。
请找到以下 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 配置:
关于如何实现这一目标的任何建议都将非常有帮助。提前致谢。
你好吗?
如果您想获取这些查询参数,您可能需要使用 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.
}
让我知道这是否适合您!