Write Terraform that reads outputs from another state (the network stack) in the app stack.
AdvancedHands-onWrite-Terraform tasks
Answer
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "devopsshack-tfstate"
key = "network/prod/terraform.tfstate"
region = "ap-south-1"
}
}
resource "aws_instance" "app" {
ami = var.ami_id
instance_type = "t3.small"
subnet_id = data.terraform_remote_state.network.outputs.private_subnet_ids[0]
}
Key trick → This couples the stacks and needs read access to the whole network state file, secrets included. Many teams prefer publishing values to SSM Parameter Store and reading them with aws_ssm_parameter, or using data source lookups by tag.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a VPC with public and private subnets across 3 AZs using `count` or `for_each`.IntermediateWrite a reusable module for an EC2 instance with inputs, outputs and validation.AdvancedWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.Beginner