0
0
Terraformcloud~30 mins

Creating a child module in Terraform - Try It Yourself

Choose your learning style9 modes available
Creating a child module
📖 Scenario: You are managing infrastructure with Terraform. You want to organize your code by creating a reusable child module that provisions an AWS S3 bucket. This helps keep your main configuration clean and modular.
🎯 Goal: Build a Terraform child module that creates an AWS S3 bucket with a specified name, then use this child module in the root configuration to create a bucket named my-terraform-bucket.
📋 What You'll Learn
Create a child module directory with a Terraform configuration to create an AWS S3 bucket.
Define an input variable bucket_name in the child module.
Use the child module in the root Terraform configuration with the module block.
Pass the bucket name my-terraform-bucket to the child module.
💡 Why This Matters
🌍 Real World
Organizing Terraform code into child modules helps teams reuse and maintain infrastructure code efficiently.
💼 Career
Understanding Terraform modules is essential for cloud engineers and DevOps professionals managing infrastructure as code.
Progress0 / 4 steps
1
Create the child module main configuration
In the modules/s3_bucket directory, create a file called main.tf. Write a resource block to create an AWS S3 bucket using the resource type aws_s3_bucket with the name example_bucket. Use the bucket name var.bucket_name for the bucket's bucket attribute.
Terraform
Need a hint?

Use resource "aws_s3_bucket" "example_bucket" {} and set bucket = var.bucket_name.

2
Add an input variable for the bucket name
In the modules/s3_bucket directory, create a file called variables.tf. Define an input variable named bucket_name of type string with no default value.
Terraform
Need a hint?

Use variable "bucket_name" { type = string } to declare the input.

3
Use the child module in the root configuration
In the root directory, create a file called main.tf. Add a module block named s3_bucket that uses the source ./modules/s3_bucket. Pass the value "my-terraform-bucket" to the module's bucket_name input variable.
Terraform
Need a hint?

Use module "s3_bucket" { source = "./modules/s3_bucket" bucket_name = "my-terraform-bucket" }.

4
Add provider configuration for AWS
In the root directory, create a file called provider.tf. Add a provider block for aws with the region set to us-east-1.
Terraform
Need a hint?

Use provider "aws" { region = "us-east-1" } to configure the AWS provider.