Python key error in Lambda function

1

This is my first lambda function but the python code should be correct yet I am getting an error. Python code:

import json
import boto3

def get_volume_id_from_arn(volume_arn):
    #Split the ARN using the colon (':') separator
    arn_parts = volume_arn.split(':')
    #The Volume ID is the last part of the ARN after the 'volume/' prefix
    volume_id = arn_parts[-1].split('/')[-1]
    return volume_id

def lambda_handler(event, context):
    print(event)
    #Grab the event and look for resources
    #Grab the first resource line
    volume_arn = event['resources'][0]

    #Call get_volume_id_from_arn and pass it the arn for conversion
    volume_id = get_volume_id_from_arn(volume_arn)
    #Create an ec2 client for boto3
    ec2_client = boto3.client('ec2')
    #Use boto3 to call the modify_volume function to convert the volume to gp3
    responce = client.modify_volume(
        VolumeId=volume_id,
        VolumeType='gp3'
    )

When I deploy and test I get this result:

Response
{
  "errorMessage": "'resources'",
  "errorType": "KeyError",
  "requestId": "3d116529-e903-4b49-9014-c00a5d23a7ca",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 16, in lambda_handler\n    volume_arn = event['resources'][0]\n"
  ]
}

Function Logs
START RequestId: 3d116529-e903-4b49-9014-c00a5d23a7ca Version: $LATEST
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
[ERROR] KeyError: 'resources'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 16, in lambda_handler
    volume_arn = event['resources'][0]END RequestId: 3d116529-e903-4b49-9014-c00a5d23a7ca
REPORT RequestId: 3d116529-e903-4b49-9014-c00a5d23a7ca	Duration: 1.55 ms	Billed Duration: 2 ms	Memory Size: 128 MB	Max Memory Used: 60 MB

Request ID
3d116529-e903-4b49-9014-c00a5d23a7ca

Why does it not like resources as a key name?

질문됨 6달 전725회 조회
2개 답변
0
수락된 답변

It looks like you're using the "Test" functionality in the Lambda console and that you've accepted the default test event format which is {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}.

If you want your code to work with an event where resources is a part of the event then you need to configure the test event to be formatted that way. Creating a new test event gives you the ability to create any test event you like; but it also has a bunch of examples events that can come from other AWS services which might trigger your Lambda function. You can edit the examples once you've selected them in order to fully test your Lambda function.

profile pictureAWS
전문가
답변함 6달 전
0

Hello.

What kind of information is included in the event?
Does "resources" exist in event?
An error will occur if this does not exist.

profile picture
전문가
답변함 6달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠