ad4469dc-7beb-4b7f-90b1-7de.../docs/06_nested_modules_vpc_ec2.md

45 lines
920 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 6) Nested Modules: VPC + EC2 (1015 min)
Create a minimal VPC module and keep EC2 separate for clarity.
```bash
mkdir -p ~/terraform-modules-lab/modules/vpc
cd ~/terraform-modules-lab
```
**modules/vpc/main.tf**
```hcl
resource "aws_vpc" "this" { cidr_block = "10.0.0.0/16" }
resource "aws_subnet" "public" {
vpc_id = aws_vpc.this.id
cidr_block = "10.0.1.0/24"
availability_zone = "ap-south-1a"
}
```
**modules/vpc/outputs.tf**
```hcl
output "vpc_id" { value = aws_vpc.this.id }
output "subnet_id" { value = aws_subnet.public.id }
```
Update **root main.tf** to include both modules:
```hcl
provider "aws" { region = "ap-south-1" }
module "vpc" { source = "./modules/vpc" }
module "ec2_instance" {
source = "./modules/ec2-instance"
instance_type = "t2.micro"
instance_name = "Nested-App"
instance_count = 1
}
```
Apply:
```bash
terraform apply -auto-approve
```