This project creates the following AWS resources:
- S3 bucket (for storing Terraform state files)
- VPC and subnets
- Internet Gateway
- Route tables
- EC2 instance
- Security groups
.
├── backend.tf # Backend configuration
├── bucket.tf # S3 bucket configuration
├── vpc.tf # VPC and network configuration
├── ec2.tf # EC2 instance configuration
├── variables.tf # Variable definitions
└── terraform.tfvars # Variable values
-
Clean up existing resources (if needed)
# Delete existing state files (if local) rm -f terraform.tfstate terraform.tfstate.backup # Delete existing .terraform directory rm -rf .terraform
-
Backend configuration
- Modify
backend.tf
file to use local backend:
terraform { required_version = ">= 1.0.0" # Use local backend backend "local" {} # Required providers required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } }
- Modify
-
Initialize Terraform
terraform init
-
Create S3 bucket
terraform apply -target=aws_s3_bucket.terraform_state
-
Why create S3 bucket first?
- I created the S3 bucket first because it will be used as the backend for storing the Terraform state file.
- This approach solves a "chicken and egg" problem: I needed the S3 bucket to store the state file, but I can't create the bucket if we're already using it as a backend.
- By creating the bucket first with a local backend, then migrating to the S3 backend, I ensure a smooth transition without state file conflicts.
-
Verify S3 bucket settings
- Server-side encryption enabled
- Public access blocked
- Versioning enabled
-
Change backend configuration
- Modify
backend.tf
file to use S3 backend:
terraform { required_version = ">= 1.0.0" # Use S3 backend backend "s3" { bucket = "gunsu-private-bucket-8926937-state" key = "terraform.tfstate" region = "us-east-1" encrypt = true } # Required providers required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } }
- Modify
-
Migrate state file
terraform init -migrate-state
-
Create all resources
terraform apply
-
Verify created resources
- Check in AWS Console that the following resources have been created:
- S3 bucket (gunsu-private-bucket-8926937-state)
- terraform.tfstate file in the S3 bucket
- VPC (gunsu-vpc)
- Public subnet (terraform-project-public-subnet)
- Internet Gateway (terraform-project-igw)
- Route table (terraform-project-public-rt)
- EC2 instance (terraform-project-web-server)
- Security group (terraform-project-ec2-sg)
- Check in AWS Console that the following resources have been created:
-
Delete all resources
terraform destroy
-
S3 bucket deletion issues
- S3 bucket must be empty before deletion.
- If versioning is enabled, all versions of objects must be deleted.
- IAM permission issues
- Problem: Cannot create resources due to insufficient IAM permissions.
- Solution: Add necessary permissions in AWS IAM console.
- Required permissions:
s3:CreateBucket
,ec2:CreateVpc
, etc.