In order to automate the creation of the resource group, I want to use a generic Terraform script
As an example, the below script creates the resource group in Azure based on the input values provided in the *.tfvars.json
file
main.tf
# Configure the Microsoft Azure provider
provider "azurerm" {
features {}
}
# Create a Resource Group if it doesn’t exist
resource "azurerm_resource_group" "example" {
name = var.resource_group_name
location = "West US"
}
vars.tf
# Input variable: image sku
variable "resource_group_name" {
description = "Name of the resource group"
default = "example-resources"
}
testing.tfvars.json
{
"resource_group_name":"example-resources-testing"
}
and executed like
terraform apply –auto-approve -var-file="testing.tfvars.json"
Before creating the new resource group, it destroys the existing one. I don’t want to destroy the existing resource group, just create a new one.
I don’t want to clone the script. What should I do to use the generic Terraform script repeatedly without destroying the existing one? Is it just a matter of disabling or removing the state before execution?
The purpose is to automate the resource group creation using ITSM ticketing system, ITSM ticketing tool will provide the input to the terraform script to create the required resource. It should not impact the existing resource groups.
2
Answers
You need to create a workspace for each environment.
Workspaces are managed with the terraform workspace set of commands. To create a new workspace and switch to it, you can use
terraform workspace new
; to switch workspaces you can useterraform workspace select
; more info about Managing Workspaces.Within your Terraform configuration, you may include the name of the current workspace using the
${terraform. Workspace}
interpolation sequence.Firstly, let’s answer why changing variable is removing old resource group (if you’re not interested, just skip to last section)
Why does terraform destroy resource group on changing variable
Terraform code isn’t "script".
It’s infrastructure state that you desire.
So if you change variable you change your desire from having
resource-group-1
to havingresource-group-2
. And your current desire is stored in something called state file. And to fulfil your desire, terraform have to remove first one and create another one. But there are few ways to do what you want to.Solution
To have multiple resource group in single terraform code you either have to:
Multiple state files (many small desires)
To have it first way you have two options:
Single state files (one big desire)
Terraform also allows you to store multiple resource groups in a single state file, so the only thing is to iterate through the list of resource group names. And your iteration operator is
for_each
. It should look something like that:and variable would be:
each
keyword gives youkey
andvalue
but in sets its same. For more abouteach
,for_each
, etc. you can read here