CodexBloom - Programming Q&A Platform

Terraform how to to properly configure AWS Lambda function with VPC and security group settings

👀 Views: 1 💬 Answers: 1 📅 Created: 2025-06-05
terraform aws lambda HCL

I've searched everywhere and can't find a clear answer. I've looked through the documentation and I'm still confused about I'm trying to deploy an AWS Lambda function using Terraform, and I'm working with an scenario when configuring it to run within a VPC. Despite following the documentation, I keep getting the behavior: `InvalidParameterValueException: The security group 'sg-0123456789abcdef0' is not associated with the VPC 'vpc-0123456789abcdef0'`. Here's a snippet of my Terraform configuration: ```hcl provider "aws" { region = "us-east-1" } resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" } resource "aws_security_group" "lambda_sg" { vpc_id = aws_vpc.main.id name = "lambda_security_group" } resource "aws_subnet" "lambda_subnet" { vpc_id = aws_vpc.main.id cidr_block = "10.0.1.0/24" availability_zone = "us-east-1a" } resource "aws_lambda_function" "example_lambda" { function_name = "example_lambda" handler = "index.handler" runtime = "nodejs14.x" role = aws_iam_role.lambda_exec.arn vpc_config { subnet_ids = [aws_subnet.lambda_subnet.id] security_group_ids = [aws_security_group.lambda_sg.id] } } ``` I've double-checked the security group and VPC IDs, and they do match. One thing I noticed is that I didn't explicitly define the `aws_iam_role` resource in the configuration, as I was testing without it for simplicity. When I include the role, I still see the same behavior when deploying. I’ve tried running `terraform plan` and `terraform apply` multiple times and made sure to destroy any previous configurations, but the behavior continues. Any suggestions on what I might be missing here or how to troubleshoot this scenario effectively? Thanks in advance! This is part of a larger web app I'm building. Is there a better approach? I'm working on a application that needs to handle this.