如何在同一个 Lambda 函数中使用四种不同的 HTTP 方法?

huangapple go评论98阅读模式
英文:

How I can use 4 different http_methods in the same lambda function?

问题

这是您的代码的翻译部分:

import json
import boto3

def ec2_crud(event, context):
    http_method = event['httpMethod']
    try:
        # Create a connection to EC2 using the region where the Lambda function is located
        region = context.invoked_function_arn.split(":")[3]
        ec2 = boto3.resource('ec2', region_name=region)

        if http_method == 'GET':
            # Get all EC2 instances in the region
            instances = ec2.instances.all()

            instance_list = []
            for instance in instances:
                instance_info = {
                    'InstanceId': instance.id,
                    'InstanceType': instance.instance_type,
                    'State': instance.state['Name']
                }
                instance_list.append(instance_info)

            return {
                'statusCode': 200,
                'body': json.dumps(instance_list)
            }
        elif http_method == 'POST':
            try:
                request_data = json.loads(event['body'])
                instance_name = request_data['name']
                instance_size = request_data['size']
                instance_keys = request_data['keys']

                ec2_client = boto3.client('ec2')
                new_instance = ec2_client.run_instances(
                    ImageId='ami-03f65b8614a860c29',  # Replace with the desired AMI
                    InstanceType=instance_size,
                    KeyName=instance_keys,
                    MinCount=1,
                    MaxCount=1
                )['Instances'][0]

                ec2_client.create_tags(Resources=[new_instance['InstanceId']], Tags=[{'Key': 'Name', 'Value': instance_name}])

                return {
                    'statusCode': 200,
                    'body': json.dumps({'message': 'New instance created successfully.', 'InstanceId': new_instance['InstanceId']})
                }
            except Exception as e:
                return {
                    'statusCode': 500,
                    'body': json.dumps({'error': str(e)})
                }
        elif http_method == 'PUT':
            instance_id = event['pathParameters']['instance_id']
            instance_size = json.loads(event['body'])['size']
            instance_name = json.loads(event['body'])['name']

            ec2_client = boto3.client('ec2')

            try:
                ec2_client.modify_instance_attribute(InstanceId=instance_id, Attribute='instanceType', Value=instance_size)
                ec2_client.create_tags(Resources=[instance_id], Tags=[{'Key': 'Name', 'Value': instance_name}])

                return {
                    'statusCode': 200,
                    'body': json.dumps({'message': f'Instance {instance_id} updated successfully.'})
                }
            except Exception as e:
                return {
                    'statusCode': 500,
                    'body': json.dumps({'error': str(e)})
                }
        elif http_method == 'DELETE':
            instance_id = event['pathParameters']['instance_id']

            ec2_client = boto3.client('ec2')

            try:
                ec2_client.terminate_instances(InstanceIds=[instance_id])

                return {
                    'statusCode': 200,
                    'body': json.dumps({'message': f'Instance {instance_id} deleted successfully.'})
                }
            except Exception as e:
                return {
                    'statusCode': 500,
                    'body': json.dumps({'error': str(e)})
                }
        else:
            return {
                'statusCode': 400,
                'body': json.dumps({'error': 'Invalid HTTP method.'})
            }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }

请注意,我已经将单引号(')替换为双引号(")以适应 JSON 字符串,并尽量保持原始格式。至于您的问题,关于 PUT 和 DELETE 请求出现 "Missing Authentication Token" 错误,这通常是由于缺少身份验证令牌引起的。您需要确保您的 PUT 和 DELETE 请求在发送到 AWS Lambda 函数时进行身份验证,以便执行相应的 EC2 操作。如果您需要更多关于身份验证和访问控制的帮助,请查看 AWS 文档或者提供更多关于您的问题的上下文,以便我可以提供更具体的建议。

英文:

I have this function with which I intend to handle instances of ec2, with get I list all the instances in the region, post to create a new instance, put to modify one and delete to delete one instance, I'm using Python 3.9 lambda and serverless

import json
import boto3
def ec2_crud(event, context):
http_method = event['httpMethod']
try:
# Crear una conexión con EC2 usando la región en la que se encuentra la función Lambda
region = context.invoked_function_arn.split(":")[3]
ec2 = boto3.resource('ec2', region_name=region)
if http_method == 'GET':
# Obtener todas las instancias de EC2 en la región
instances = ec2.instances.all()
instance_list = []
for instance in instances:
instance_info = {
'InstanceId': instance.id,
'InstanceType': instance.instance_type,
'State': instance.state['Name']
}
instance_list.append(instance_info)
return {
'statusCode': 200,
'body': json.dumps(instance_list)
}
elif http_method == 'POST':
try:
request_data = json.loads(event['body'])
instance_name = request_data['name']
instance_size = request_data['size']
instance_keys = request_data['keys']
ec2_client = boto3.client('ec2')
new_instance = ec2_client.run_instances(
ImageId='ami-03f65b8614a860c29',  # Reemplaza con la AMI que desees usar
InstanceType=instance_size,
KeyName=instance_keys,
MinCount=1,
MaxCount=1
)['Instances'][0]
ec2_client.create_tags(Resources=[new_instance['InstanceId']], Tags=[{'Key': 'Name', 'Value': instance_name}])
return {
'statusCode': 200,
'body': json.dumps({'message': 'Nueva instancia creada con éxito.', 'InstanceId': new_instance['InstanceId']})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}
elif http_method == 'PUT':
# Implementar la lógica para actualizar una instancia de EC2
instance_id = event['pathParameters']['instance_id']
instance_size = json.loads(event['body'])['size']
instance_name = json.loads(event['body'])['name']
# Crear una conexión con el servicio EC2
ec2_client = boto3.client('ec2')
try:
# Actualizar el tamaño y el nombre de la instancia
ec2_client.modify_instance_attribute(InstanceId=instance_id, Attribute='instanceType', Value=instance_size)
ec2_client.create_tags(Resources=[instance_id], Tags=[{'Key': 'Name', 'Value': instance_name}])
return {
'statusCode': 200,
'body': json.dumps({'message': f'Instancia {instance_id} actualizada con éxito.'})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}
elif http_method == 'DELETE':
# Implementar la lógica para eliminar una instancia de EC2
instance_id = event['pathParameters']['instance_id']
# Crear una conexión con el servicio EC2
ec2_client = boto3.client('ec2')
try:
# Eliminar la instancia
ec2_client.terminate_instances(InstanceIds=[instance_id])
return {
'statusCode': 200,
'body': json.dumps({'message': f'Instancia {instance_id} eliminada con éxito.'})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}
else:
return {
'statusCode': 400,
'body': json.dumps({'error': 'Método HTTP inválido.'})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}

When I test get and post block with curl works well and runs the task but when I try it with put and delete, I get this error:

> Missing Authentication Token

and I don't know why this happens.

I try it to modify and delete ec2 instances

答案1

得分: 1

我们需要查看您的 serverless.yml 文件以检查 HTTP 选项配置。

通常,当路由存在但该路由不支持该 HTTP 方法时,您会看到 missing authentication token 错误。

您可能希望设置 method: ANY,就像这个示例一样:

functions:
  myFunction:
    handler: index.handler
    events:
      - httpApi:
          path: /my-path
          method: ANY

如果您还希望来自该 API Gateway 实例的任何路径都路由到您的函数,您可以使用 proxy 配置:

functions:
  myFunction:
    handler: index.handler
    events:
      - httpApi:
          path: ANY {proxy+}
          method: ANY
英文:

We'd need to see your serverless.yml file to check HTTP option configuration.

Typically, you'll see missing authentication token when the route exists but the HTTP method is not valid for that route.

You'll likely want to set method: ANY, like this example:

functions:
  myFunction:
    handler: index.handler
    events:
      - httpApi:
          path: /my-path
          method: ANY

If you also wanted any path from that API Gateway instance to route to your function, you can use the proxy configuration:

functions:
  myFunction:
    handler: index.handler
    events:
      - httpApi:
          path: ANY {proxy+}
          method: ANY

huangapple
  • 本文由 发表于 2023年8月5日 09:35:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定