DEV Community

Abhishek Anand Amralkar
Abhishek Anand Amralkar

Posted on

String Functions

format

format function produces a string by formatting a number of other values according to a specification string. Let's see an example

Note:- From now on we will refer Terraform as TF

We can use format function as a printf function in many other languages. I heavily used them in tagging my resources
in cloud.

  tags = merge(
    {
      "Name" = format("%s-%03d-%s", var.namespace, count.index, var.environment)
    },
    var.tags,
  )

or

name = format("%s-%s-%s", "elastic", var.environment, "SG")

consider variables are defined as below

variable "environment" {
  description = "Name of the Environment"
  type        = string
  default     = "Stage"
}


variable "namespace" {
  description = "Name to be used with identifier"
  type        = string
  default     = "elastic"
}

The above first code will generate the tag elastic-000-Stage and with count.index it will keep incrementing the %d depending upon the number defined and the second code block will generate elastic-Stage-SG.

join

join takes 2 input the separator and the list of string and concatenate them and returns the strings

For example, see below code block


role  = join("", aws_iam_role.elastic_iam_role.*.name)

The above code will generate the IAM role name as a string separated by blank space.

split

split function produces the list when given input as a string lets see example below


availability_zone = element(split(",", var.azs), count.index)

with the above code, we will get a list of all the availability zones (azs).

replace

replace function in TF is like sed in Linux it searches for the given string and replaces it.

is_t_instance_type = replace(var.instance_type, "/^t[23]{1}\\..*$/", "1") == "1" ? true : false

Your substring wrapped in // like /foo/ will be considered as a regular expression

In above example the value of var.instance_type will be replace by the regular expression which will match t2 and t3 instance families in aws.

Above functions are just very few out of mmany String Functions by Terraform.

Top comments (0)