Getting Started with Terraform Part - 2
This is Part - 2 of the series Getting Started with Terraform. We will check additional features from Terraform such as Locals and Output
Locals
locals is a block of code where we define expressions and assign them to a name, which can be used later. we can define more than one locals block. scope of locals block is restricted to the file in which it is written.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "3.72.0"
}
}
}
locals {
Environment = "Development"
S3 = {
bucket = "terraform-remote-state-test-bucket-example"
}
}
locals {
default_tags = {
Environment = local.Environment
}
}
# Configure the AWS Provider
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "bucket" {
bucket = local.S3.bucket
tags = local.default_tags
}
Click here see the code difference from the previous section to this.
Output
outputs.tf file prints the metadata like arn, id and, etc of the resources you created. let’s look at the syntax
output name_of_the_output {
value = "<resource_or_module>"
sensitive = true
description = "description"
}
let’s create outputs.tf file with following content.
output "bucket_domain" {
value = aws_s3_bucket.bucket.bucket_domain_name
}
Run following commands to create an S3 bucket
terraform init
terraform plan
terraform apply
Once you apply, you can observe we have the Outputs section with bucket_domain with the respective value.
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
bucket_domain = "terraform-remote-state-test-bucket-example.s3.amazonaws.com"
Go to the AWS console to confirm if the S3 bucket has been created
