I am trying to learn terraform. I trying to have api gateway pass requests to lambda to do REST CRUD actions to manage a record in Dynamo DB.
at one point I had been able to have the API gateway contact the lambda do create the record. When I tried to get the record I was getting server errors or authorization errors.
Looking at the console. the methods all have NONE for authorizers. one of the recommendations I got was to have API gateway log what is going on.
The log group is getting created but nothing is getting logged.
Any thoughts on how to get API gateway to log what is going on
Any suggestions on how to get API gateway to do basic restful actions?
here is my terraform
# Define the provider
provider "aws" {
region = "us-east-1" # Specify your desired region
}
# Create a DynamoDB table
resource "aws_dynamodb_table" "my_table" {
name = "MyTable"
billing_mode = "PAY_PER_REQUEST"
hash_key = "ID"
attribute {
name = "ID"
type = "S"
}
}
# Create an IAM role for Lambda execution
resource "aws_iam_role" "lambda_execution_role" {
name = "my_lambda_execution_role"
assume_role_policy = jsonencode({
"Version" : "2012-10-17",
"Statement" : [
{
"Action" : "sts:AssumeRole",
"Principal" : {
"Service" : "lambda.amazonaws.com"
},
"Effect" : "Allow",
"Sid" : ""
}
]
})
inline_policy {
name = "lambda_dynamodb_policy"
policy = jsonencode({
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem"
],
"Resource" : "arn:aws:dynamodb:*:*:table/MyTable"
}
]
})
}
}
# Attach the IAM role to the Lambda function
resource "aws_lambda_function" "my_function" {
filename = "${path.module}/my_function.zip" # The path to your Lambda function code
function_name = "MyFunction"
handler = "lambda_function.lambda_handler"
runtime = "python3.11"
source_code_hash = filebase64sha256("${path.module}/my_function.zip")
role = aws_iam_role.lambda_execution_role.arn # Specify the ARN of the IAM role here
environment {
variables = {
DYNAMO_TABLE_NAME = aws_dynamodb_table.my_table.name
}
}
}
# Attach the IAM role to the Lambda function for API Gateway invocation
resource "aws_lambda_permission" "allow_api_gateway" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.my_function.arn
principal = "apigateway.amazonaws.com"
source_arn = "${aws_api_gateway_rest_api.my_api.execution_arn}/*/*/*"
}
# Create an API Gateway
resource "aws_api_gateway_rest_api" "my_api" {
name = "MyAPI"
}
# Create a resource
resource "aws_api_gateway_resource" "my_resource" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
parent_id = aws_api_gateway_rest_api.my_api.root_resource_id
path_part = "myresource"
}
# Create a put method
resource "aws_api_gateway_method" "my_put_method" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = "PUT"
authorization = "NONE"
}
# Integration between API Gateway and Lambda for PUT method
resource "aws_api_gateway_integration" "my_put_integration" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = aws_api_gateway_method.my_put_method.http_method
integration_http_method = "PUT"
type = "AWS_PROXY"
uri = aws_lambda_function.my_function.invoke_arn
}
# Deployment for PUT method
resource "aws_api_gateway_deployment" "my_put_deployment" {
depends_on = [aws_api_gateway_integration.my_put_integration]
rest_api_id = aws_api_gateway_rest_api.my_api.id
#stage_name = "dev"
}
# Create a GET method
resource "aws_api_gateway_method" "my_get_method" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = "GET"
authorization = "NONE"
}
# Integration between API Gateway and Lambda for GET method
resource "aws_api_gateway_integration" "my_get_integration" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
resource_id = aws_api_gateway_resource.my_resource.id
http_method = aws_api_gateway_method.my_get_method.http_method
integration_http_method = "GET"
type = "AWS_PROXY"
uri = aws_lambda_function.my_function.invoke_arn
}
# Deployment for GET method
resource "aws_api_gateway_deployment" "my_get_deployment" {
depends_on = [aws_api_gateway_integration.my_get_integration]
rest_api_id = aws_api_gateway_rest_api.my_api.id
# stage_name = "dev"
}
# Enable logging for the API Gateway stage
# Enable logging for the API Gateway stage
resource "aws_api_gateway_stage" "my_stage" {
rest_api_id = aws_api_gateway_rest_api.my_api.id
stage_name = "dev"
deployment_id = aws_api_gateway_deployment.my_put_deployment.id
access_log_settings {
destination_arn = aws_cloudwatch_log_group.api_logs.arn
format = "$context.requestId $context.extendedRequestId"
}
lifecycle {
ignore_changes = [deployment_id] # Ignore changes to deployment_id
}
}
# CloudWatch Log Group for API Gateway logs
resource "aws_cloudwatch_log_group" "api_logs" {
name = "/aws/api-gateway/my_api_logs"
retention_in_days = 7
}
# Output the API Gateway endpoint
output "api_gateway_endpoint" {
value = aws_api_gateway_deployment.my_put_deployment.invoke_url
}
here is my lambda function
import boto3
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')
def lambda_handler(event, context):
operation = event['httpMethod']
if operation == 'POST':
item = json.loads(event['body'])
response = table.put_item(Item=item)
elif operation == 'GET':
item_id = event['queryStringParameters']['ID']
response = table.get_item(Key={'ID': item_id})
elif operation == 'PUT':
item = json.loads(event['body'])
response = table.update_item(Key={'ID': item['ID']}, UpdateExpression='SET attribute1 = :val1', ExpressionAttributeValues={':val1': item['attribute1']})
elif operation == 'DELETE':
item_id = event['queryStringParameters']['ID']
response = table.delete_item(Key={'ID': item_id})
return {
'statusCode': 200,
'body': json.dumps(response)
}