Reputation: 129
Im new to Terraform and I have this doubt. I've created a set of multiple resources for GCP (instances, vpc, subnet, secret manager, etc), so far so good, but the requirement is to re-use the same code for multiple future deployments (not environments). That means, this week I'll deploy the whole set for an specific region with specific names, next week I might need to deploy the same set for another region with different names and two weeks later another (but the previous ones won't be deleted), the resources will always remain the same and will be used for PROD activities.
What would be the best way to achieve this? Thanks.
Upvotes: 1
Views: 431
Reputation: 1
It is better to split terraform code and infrastructure metadata (json-files with per-region/env/org configuration) like I did in https://github.com/alt-dima/tofugu
Upvotes: 0
Reputation: 129
I solved this by using workspaces, simple creating a new workspace for each deployment with terraform workspace new and deploying from that workspace in particular. If another set of infra needed to be deploy, I create a new one, change and re-deploy again, using the same code for all deploys.
Upvotes: -1
Reputation: 629
Lets say you have Terraform code looks like example below and want to reuse that code across environments:
├── modules
│ ├── module1
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ └── variables.tf
│ ├── module2
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ └── variables.tf
module1
and module1
contains your reusable code.
Create per environment directories so you directory looks like that:
├── environments
│ └── env1
│ │ ├── main.tf
│ │ ├── terraform.tfvars
│ │ └── variables.tf
│ ...
├── modules
│ ├── module1
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ └── variables.tf
│ ├── module2
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ └── variables.tf
Inside each environment you need to include reusable modules into env1/main.tf
file:
module "module1-env1" {
source = "../../modules/module1"
vpc = var.vpc <- list all you variables like that
subnet = var.subnet
...
}
module "module2-env1" {
source = "../../modules/module2"
vpc = var.vpc <- list all you variables like that
subnet = var.subnet
...
}
All variables should be defined in env1/variables.tf
and values provided in env1/terraform.tfvars
.
All other environments should be configured in a similar way.
Congratulation! Now you can provision multiple infrastructure using the same code.
Upvotes: 3