Lab 01: Create VPC and Subnet Using Terraform
Requirements
To ensure proper resource provisioning order, the DevOps team wants to explicitly define the dependency between an AWS VPC and a Subnet. The objective is to create a VPC and then a Subnet that explicitly depends on it using Terraform's depends_on argument.
Please complete the following tasks:
- Create a VPC named
devops-vpc. - Create a Subnet named
devops-subnet. - Ensure the Subnet uses the
depends_onargument to explicitly depend on the VPC resource. - Create the
main.tffile (do not create a separate.tffile) to provision a VPC and Subnet. - Use
variables.tf, define the following variables:KKE_VPC_NAMEfor the VPC name.KKE_SUBNET_NAMEfor the Subnet name.
- Use
terraform.tfvarsto input the names of the VPC and subnet. - In
outputs.tf, output the following:kke_vpc_name: The name of the VPC.kke_subnet_name: The name of the Subnet.
Note
This document focuses on the implementation approach. The task statement above is preserved as the original requirement source.
Prerequisites
- The Terraform working directory is
/home/bob/terraform. - Right-click under the
EXPLORERsection inVS Codeand selectOpen in Integrated Terminalto launch the terminal.
Steps
Create variables.tf:
# /home/bob/terraform/variables.tf
# Variables for VPC and Subnet names
variable "KKE_VPC_NAME" {
description = "The name tag for the AWS VPC."
type = string
}
variable "KKE_SUBNET_NAME" {
description = "The name tag for the AWS Subnet."
type = string
}
Create or update main.tf:
# /home/bob/terraform/main.tf
# AWS VPC and Subnet Resources
# 1. Create the VPC
resource "aws_vpc" "devops_vpc" {
cidr_block = "10.0.0.0/16"
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = var.KKE_VPC_NAME
}
}
# 2. Create the Subnet with explicit dependency
resource "aws_subnet" "devops_subnet" {
vpc_id = aws_vpc.devops_vpc.id
cidr_block = "10.0.1.0/24"
map_public_ip_on_launch = true
availability_zone = "us-east-1a"
# Explicitly define dependency on the VPC resource
depends_on = [
aws_vpc.devops_vpc,
]
tags = {
Name = var.KKE_SUBNET_NAME
}
}
Create terraform.tfvars:
# /home/bob/terraform/terraform.tfvars
# Input values for variables
KKE_VPC_NAME = "devops-vpc"
KKE_SUBNET_NAME = "devops-subnet"
Create outputs.tf:
# /home/bob/terraform/outputs.tf
# Output values
output "kke_vpc_name" {
description = "The name of the created VPC."
value = aws_vpc.devops_vpc.tags.Name
}
output "kke_subnet_name" {
description = "The name of the created Subnet."
value = aws_subnet.devops_subnet.tags.Name
}
Run Terraform:
terraform init
# or apply forcefully without creating plan and applying it
terraform apply -auto-approve
Verification
- Before submitting the task, ensure
terraform planreturnsNo changes. Your infrastructure matches the configuration.
terraform plan