Suppose I have two environment Production and Staging and Now I want to provision t2.large in Staging and m5.large in Production. How to write a terraform script without using any conditional format.
different instance in different environment provision using terraform
23 Views Asked by Ram R At
2
There are 2 best solutions below
0
On
This can be controlled by using the terraform workspace feature. The code would look similar to what Mohammed Ehab posted, but with some slight changes:
resource "aws_instance" "this" {
.
.
.
instance_type = terraform.workspace == "staging" ? "t2.large" : "m5.large"
.
.
.
tags = {
Name = "${terraform.workspace}_instance"
Environment = terraform.workspace
}
}
You could also create local variables that would help you control what gets deployed:
locals {
instance_type = terraform.workspace == "staging" ? "t2.large" : "m5.large"
tags = {
Environment = terraform.workspace
Name = "${terraform.workspace}_instance"
}
}
resource "aws_instance" "this" {
.
.
.
instance_type = local.instance_type
.
.
.
tags = local.tags
}
If you are going to use workspaces, make sure to switch between them when applying to the environment you want:
terraform workspace select <name of the workspace>
You would of course have to create the workspace first:
terraform workspace new <name of the workspace>
Alternatively, as workspaces come with their set of limitations, you could just create two different directories, define a variable and use that, e.g. for staging:
variable "env" {
type = string
description = "Environment to deploy the code into."
}
variable "instance_type" {
type = string
description = "EC2 instance type to deploy."
}
And then have a terraform.tfvars file in each of the directories with the following values:
# staging directory
env = "staging"
instance_type = "t2.large"
# production directory
env = "production"
instance_type = "m5.large"
The code for the instance would look like this:
resource "aws_instance" "this" {
.
.
.
instance_type = var.instance_type
.
.
.
tags = {
Name = "${var.env}_instance"
Environment = var.env
}
}
you can use workspaces: create your resources, for example:
initialize Terroform:
create a workspace:
plan and apply as usual.