首页 > 解决方案 > AWS 通过 api 网关添加实例

问题描述

所以我在 Lambda 中有函数。函数连接到 api 网关,它应该添加 EC2 实例。当我通过 api gateway 方法测试到达端点时,它返回状态 200 但没有添加任何实例。也许实例参数是错误的?基本上该功能是文档示例的修改版本。

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2'});

exports.handler = function index(event, context, callback) {
    // Load the AWS SDK for Node.js

// Load credentials and set region from JSON file

// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});

// AMI is amzn-ami-2011.09.1.x86_64-ebs
var instanceParams = {
   InstanceType: 't2.micro',
   KeyName: 'firstkeypair',
   ImageId: 'ami-0bbe28eb2173f6167'
};

// Create a promise on an EC2 service object
var instancePromise = new AWS.EC2({apiVersion: '2016-11-15'}).runInstances(instanceParams).promise();

// Handle promise's fulfilled/rejected states
instancePromise.then(
  function(data) {
    console.log(data);
    var instanceId = data.Instances[0].InstanceId;
    console.log("Created instance", instanceId);
    // Add tags to the instance
    tagParams = {Resources: [instanceId], Tags: [
       {
          Key: 'Name',
          Value: 'SDK Sample'
       }
    ]};
    // Create a promise on an EC2 service object
    var tagPromise = new AWS.EC2({apiVersion: '2016-11-15'}).createTags(tagParams).promise();
    // Handle promise's fulfilled/rejected states
    tagPromise.then(
      function(data) {
        console.log("Instance tagged");
      }).catch(
        function(err) {
        console.error(err, err.stack);
      });
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
}

AWS 测试日志:

Execution log for request a83bae6e-2fbf-4d88-ad70-a683a83bdc41
Sun Aug 16 16:56:00 UTC 2020 : Starting execution for request: a83bae6e-2fbf-4d88-ad70-a683a83bdc41
Sun Aug 16 16:56:00 UTC 2020 : HTTP Method: GET, Resource Path: /
Sun Aug 16 16:56:00 UTC 2020 : Method request path: {}
Sun Aug 16 16:56:00 UTC 2020 : Method request query string: {}
Sun Aug 16 16:56:00 UTC 2020 : Method request headers: {}
Sun Aug 16 16:56:00 UTC 2020 : Method request body before transformations: 
Sun Aug 16 16:56:00 UTC 2020 : Endpoint request URI: https://lambda.us-east-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-2:081348884123:function:hello/invocations
Sun Aug 16 16:56:00 UTC 2020 : Endpoint request headers: {x-amzn-lambda-integration-tag=a83bae6e-2fbf-4d88-ad70-a683a83bdc41, Authorization=**************************************************************************************************************************************************************************************************************************************************************************************59de14, X-Amz-Date=20200816T165600Z, x-amzn-apigateway-api-id=o2hkrbm1o4, X-Amz-Source-Arn=arn:aws:execute-api:us-east-2:081348884123:o2hkrbm1o4/test-invoke-stage/GET/, Accept=application/json, User-Agent=AmazonAPIGateway_o2hkrbm1o4, X-Amz-Security-Token=IQoJb3JpZ2luX2VjEAAaCXVzLWVhc3QtMiJIMEYCIQCPi2S8PtDGsVK3w101D8B05/BCFGyUCzHeX8CT6tC7pAIhAJZCgpbZN94qCVdAgrQGlIIE+ABsO9MDkzh6Lf3WGq3IKr0DCNn//////////wEQARoMNzE4NzcwNDUzMTk1IgxILUqxpu50pB1cJmcqkQP/g+OuOqP7/zXYq8IAzTMolDThuprxjuzwDbmtAmS3adcmmHO25YxBQrId1XiR7ZEU7mq52k4A0nIFhBPkz2dZZIfr8MiLVCDx5tLok8j3lPZJOW+I3n7BVglTMtfQDpPYRSUcIQhOfsSnEEc+FKPzHyrzGsLeazIUHItf5L3xY4QO9tyDWnTXfcM2pp [TRUNCATED]
Sun Aug 16 16:56:00 UTC 2020 : Endpoint request body after transformations: 
Sun Aug 16 16:56:00 UTC 2020 : Sending request to https://lambda.us-east-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-2:081348884123:function:hello/invocations
Sun Aug 16 16:56:02 UTC 2020 : Received response. Status: 200, Integration latency: 1952 ms
Sun Aug 16 16:56:02 UTC 2020 : Endpoint response headers: {Date=Sun, 16 Aug 2020 16:56:02 GMT, Content-Type=application/json, Content-Length=4, Connection=keep-alive, x-amzn-RequestId=f84212ea-38f8-40cc-b5c6-c12885e78392, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=root=1-5f396520-4d9dfcb6b965192c5fea0df6;sampled=0}
Sun Aug 16 16:56:02 UTC 2020 : Endpoint response body before transformations: null
Sun Aug 16 16:56:02 UTC 2020 : Method response body after transformations: null
Sun Aug 16 16:56:02 UTC 2020 : Method response headers: {X-Amzn-Trace-Id=Root=1-5f396520-4d9dfcb6b965192c5fea0df6;Sampled=0, Content-Type=application/json}
Sun Aug 16 16:56:02 UTC 2020 : Successfully completed execution
Sun Aug 16 16:56:02 UTC 2020 : Method completed with status: 200

政策:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iam:*",
                "organizations:DescribeAccount",
                "organizations:DescribeOrganization",
                "organizations:DescribeOrganizationalUnit",
                "organizations:DescribePolicy",
                "organizations:ListChildren",
                "organizations:ListParents",
                "organizations:ListPoliciesForTarget",
                "organizations:ListRoots",
                "organizations:ListPolicies",
                "organizations:ListTargetsForPolicy"
            ],
            "Resource": "*"
        }
    ]
}

编辑: 通过向 Lambda 函数添​​加 EC2 完全访问权限来解决。

标签: node.jsamazon-web-servicesaws-lambda

解决方案


通过评论发现了 2 个问题。

首先是该RunInstances任务不包括导致没有启动实例的 MinCount 和 MaxCount 属性。

解决此问题后,下一个问题是权限问题,因为缺少运行ec2:RunInstancee2:CreateTags.

值得说明的是,权限的最佳实践是将范围缩小到成功运行所需的最低权限。


推荐阅读