Crossing the Ts: Bootstrapping Terraform with Terragrunt

by Howard Hill
May 28, 2024
by Howard Hill
May 28, 2024

It’s been a while since I peered into the Terraform release sphere. Some related news recently is that an infrastructure-as-code tool called OpenTofu has achieved GA since being forked from the opensource version of Terraform

The Linux Foundation took over the management of OpenTofu and formally released it for general availability on January 10th, 2024. OpenTofu offers features that could help address some long-standing Terraform limitations and it’s compatible with Terraform versions 1.5.x and most of 1.6.x.. We’re keeping an eye on potential adoption. While Terraform remains the dominant option, OpenTofu could gain momentum down the road as a mature alternative.

For now, Terraform is still the leader, and I wanted to get caught up on a key capability – bootstrapping the Terraform state. It’s easy to stick with a working version rather than staying current on releases, so let’s discuss what TF feature I liked in 2023. 

With Terragrunt  it gives you the option of creating the remote state automatically. That’s fantastic because we don’t want to get into this chicken and egg scenario and it does this by prompting for the option to create the remote state.# env/staging/terragrunt.hcl

locals{

 environment = find_in_parent_folders("env")

}

remote_state {

 backend = "s3"

 generate = {

path   = "backend.tf"

if_exists = "overwrite"

 }

 config = {

bucket     = "staging-tfs-${basename(get_repo_root())}"

key         = "env/staging/${path_relative_to_include()}/terraform.tfstate"

region     = "eu-west-2"

encrypt     = true

dynamodb_table = "tf3-lock-table"

 }

}Sample hcl to instruct terragrunt of a remote stateWhen run, It will use the assumed role passed; in my case in AWS to create the S3 bucket automatically. This would also work with a service principal in Azure for example.Now we could leave it at that . We have a remote state in S3 with locking handled by the dynamodb table. # Useful commands to handle recreation of the state

aws dynamodb list-tables

aws dynamodb delete-table --table-name tfs3-lock-tableBut what if we wanted to do more stuff with the s3 bucket state. With the release of Terraform 1.5 brings config-driven import and checks.I have updated the sample code bootstrap import  to wait 20s to 30s after the bucket has been created by Terragrunt and import that resource in one execution plan with Terraform

PART 1

PART 2

In part 2 we can see that the plan has one to import and 8 to add. Success !!Thanks for reading and checking out my code here !!

This blog is written exclusively by the OpenCredo team. We do not accept external contributions.