Terraform multirepo
- Create a VPC with a repo.
- export attributes for resources using output.
- output “vpc_id” {
- value = module.vpc.vpc_id
- } –> it exports the vpc_id for a vpc module.
- Create a new resource to be created over the VPC in a different repo structure.
- Read the remote backend:
data “terraform_remote_state” “vpc” {
backend = “s3”
config = {
bucket = “awsterraform-state”
key = “env:/${terraform.workspace}/IaC/bastion-state.tfstateate.tfstate“
region = “us-east-1”
encrypt = true
}
}
Important here: when using workspace, the attribute key in the terraform_remote_state resource has to include the terraform.workspace variable and the format in which the key (tfstate) is created in the bucket when we use workspace, for instance, when we save the tfstate with a key IaC/mytfstate for the workspace production, it really will be saved as env:/production/IaC/mytfstate, notice that env:/production is added to the path, so, when we need to reference the path in a new terraform_remote_state this path has to be considered, I assume that all resources created for a VPC with workspace production or testing or dev, will be created using the same terraform workspace, that’s why I added the key = “env:/${terraform.workspace}/IaC/bastion-state.tfstateate.tfstate” .
6. The attribute can be accessed through the new terraform code calling that output, notice we have to reference the local resource and name and then add “outputs” and the name of the attribute exported.
output “vpc_id” {
value = data.terraform_remote_state.vpc.outputs.vpc_id
} –> it retrieves the vpc_id from a tfstate.