Bootstrap FreeKB - Terraform - Replace function
Terraform - Replace function

Updated:   |  Terraform articles

Here is an example of how the replace function can be used. Let's say you have the following files on your Terraform server.

├── locals.tf
├── modules.tf
├── outputs.tf
├── provider.tf
├── terraform.tfstate
├── variables.tf
├── child (directory, child module)
│   ├── data.tf
│   ├── outputs.tf
│   ├── resources.tf

 

Let's say variables.tf contains the "environment" variable.

variable "environment" {
  type = string
  sensitive = false
  default = "dev"
}

 

And locals.tf replaces "dev" to "prod".

locals {
  environment = replace(var.environment, "/[a-zA-Z0-9].*/", "prod")
}

 

Perhaps resources.tf uses the aws_vpc resource to create an Amazon Web Services (AWS) Virtual Private Cloud (VPC) named prod-my-vpc, including the var.environment variable.

variable "environment" {
  type = string
  sensitive = false
  default = "dev"
}

locals {
  environment = replace(var.environment, "/[a-zA-Z0-9].*/", "prod")
}

resource "aws_vpc" "my-vpc" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "${var.environment}-my-vpc"
  }
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 85449f in the box below so that we can be sure you are a human.