0
0
TerraformHow-ToBeginner · 3 min read

How to Create a VPC with Terraform: Simple Guide

To create a VPC in Terraform, define a resource block using the aws_vpc resource type with required attributes like cidr_block. Then run terraform init, terraform plan, and terraform apply to deploy the VPC.
📐

Syntax

The basic syntax to create a VPC in Terraform uses the resource block with the aws_vpc resource type. You must specify a cidr_block which defines the IP address range for the VPC.

  • resource: declares a resource to create
  • aws_vpc: the resource type for AWS VPC
  • name: a unique name for the resource in Terraform
  • cidr_block: the IP range for the VPC in CIDR notation
  • tags: optional labels for the VPC
terraform
resource "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "example-vpc"
  }
}
💻

Example

This example creates a VPC with the IP range 10.0.0.0/16 and tags it with the name "example-vpc". After writing this code in a file named main.tf, run terraform init to initialize, terraform plan to preview, and terraform apply to create the VPC.

terraform
provider "aws" {
  region = "us-east-1"
}

resource "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "example-vpc"
  }
}
Output
aws_vpc.example: Creating... aws_vpc.example: Creation complete after 3s [id=vpc-0abc123def456ghij]
⚠️

Common Pitfalls

Common mistakes when creating a VPC with Terraform include:

  • Forgetting to specify the cidr_block, which is required.
  • Using an invalid CIDR format like "10.0.0.0" without the mask.
  • Not setting the AWS provider region, causing deployment errors.
  • Not tagging the VPC, which can make resource management harder.

Always validate your CIDR and provider settings before applying.

terraform
resource "aws_vpc" "wrong" {
  # Missing cidr_block causes error
  tags = {
    Name = "wrong-vpc"
  }
}

# Correct way
resource "aws_vpc" "right" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "right-vpc"
  }
}
📊

Quick Reference

Remember these key points when creating a VPC with Terraform:

  • Always define cidr_block in CIDR notation.
  • Set the AWS provider region before creating resources.
  • Use tags to name and organize your VPC.
  • Run terraform init, terraform plan, and terraform apply in order.

Key Takeaways

Define an aws_vpc resource with a valid cidr_block to create a VPC.
Always configure the AWS provider with a region before deploying.
Use tags to label your VPC for easier management.
Run terraform init, plan, and apply in sequence to deploy infrastructure.
Check CIDR format carefully to avoid deployment errors.