I am aware this is probably a VERY dumb question. But I can’t seem to find the answer!
I’ve been studying Terraform for a few days now, and I’ve created a script to set up various infrastructure/resources like VMs, Resource Groups, VNets, Subnets, NSGs, etc. The script takes a name as a variable and creates everything I need – which is great.
My problem is, how do I make this script reusable? Currently, I am running it in VS Code, but I plan to move it to a DevOps pipeline soon. However, at the moment, I can only run it once.
For example, if I run the script with the client name “Yellow”:
resource "azurerm_resource_group" "NewTest-RG1" {
name = "${var.Client_name}-RG01"
location = "UK South"
}
Then, if I run the script again with the client name “Blue”, I want it to create a new resource group called “Blue-RG01”. Instead, it tries to destroy the “Yellow” resource group and then create the “Blue” one.
I want to be able to run this script repeatedly for many different clients without destroy any of the previous infrastructure created; but it seems I can only run it for one client at a time. I’ve come across mentions of Modules and Workspaces as possible solutions, but I haven’t found a clear answer.
Any help would be greatly appreciated.
Thanks!
5
You can use a remote state
file with a module to switch the workspace instead of deleting existing
resources. By using this method, you can create new resources without destroying the existing ones.
├── 1.main.tf
├── modules/
│ └── my-module/
│ ├── resource.tf
│ ├── variables.tf
│
- main.tf
provider "azurerm" {
features {}
}
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
}
}
backend "azurerm" {
resource_group_name = "Automation_RG"
storage_account_name = "sampledemotest"
container_name = "demo"
key = "terraform.tfstate"
access_key = "=="
}
}
locals {
current_workspace = terraform.workspace
}
module "Block_client" {
source = "./my-module"
client_name = "Block"
location = "eastus"
count = local.current_workspace == "Block" ? 1 : 0
}
module "blue_client" {
source = "./my-module"
client_name = "Blue"
location = "eastus2"
count = local.current_workspace == "blue" ? 1 : 0
}
module "Green_client" {
source = "./my-module"
client_name = "Green"
location = "eastus2"
count = local.current_workspace == "Green" ? 1 : 0
}
module "Red_client" {
source = "./my-module"
client_name = "Red"
location = "eastus"
count = local.current_workspace == "Red" ? 1 : 0
}
my-module
resource.tf
resource "azurerm_resource_group" "rg" {
name = "${var.client_name}-RG01"
location = var.location
}
variables.tf
variable "client_name" {
type = string
}
variable "location" {
type = string
default = "eastus"
}
Terrafrom output:
If you want to create another resource group, just change the workspace using the commands below.
terraform workspace new Red
terraform workspace select Red
terraform apply
Output:
2