terraform function - ghdrako/doc_snipets GitHub Wiki

https://www.terraform.io/docs/configuration/functions.html.

terraform console

by using the Terraform console, you can test all the Terraform functions.

the Terraform console never makes any changes to the state file. If you have opened a terminal in the current directory where you have the Terraform configuration file, then it will load the current state so that you get access to the state data and you can test functions accordingly.

lookup

lookup retrieves the value of a single element from a map, given its key. If the given key does not exist, the given default value is returned instead.

lookup(map, key, default)
> lookup({a="ay", b="bee"}, "a", "what?")
ay
> lookup({a="ay", b="bee"}, "c", "what?")
what?

format

help format string

locals {
  hostname = "${format("%s-%s-%s-%s-%04d-%s", var.region, var.env. var.app, var.type, var.cluster_id, var.id)}"
}

matchkeys

  1. https://www.terraform.io/language/functions/matchkeys
  2. https://nedinthecloud.com/2018/08/16/terraform-fotd-matchkeys

Filters a list of values with corrosponding keys and returms onyl values that have keys in the search list

matchkeys(valueslist, keyslist, searchset)
instances = [
  "${matchkeys(
    google_compute_instance.compute_instance.*.self_link,
    google_compute_instance.compute_instance.*.zone,
    data.google_compute_zones.avaliable.name[0])
    }"
]

element

to access element in the list

list = ["ala","ela","ola"]
# ${element(var.list, 0)} == ala
# ${element(var.list, 1)} == ela
# ${element(var.list, 2)} == ola
# ${element(var.list, 3)} == ala  - rotuje znowu od zera

Conversion function

tobool(), tolist(),tomap(), tonumber(), toset(), and tostring()

for_each = toset(var.remote_access_ports)  # for_each (it accepts only sets and maps types of value) but not list

one

function takes a list, set, or tuple value with either zero or one element and returns either null or that one element in the form of string.

It’s useful in cases when a resource created using conditional expression is represented as either a zero- or one-element list, and you need to get a single value which may be either null or string,

resource "aws_kms_key" "main" {
  count               = var.ebs_encrypted ? 1 : 0

  enable_key_rotation = true
  tags                = var.tags
}

resource "aws_kms_alias" "main" {
  count         = var.ebs_encrypted ? 1 : 0

  name          = "alias/encrypt-ebs"
  target_key_id = one(aws_kms_key.main[*]key_id)
}

templatefile

resource "aws_instance" "web" {
  ami           = var.my_ami_id
  instance_type = var.instance_type
  ...
  user_data = templatefile("${path.module}/instance-init.tftpl", {
    system_hostname     = var.system_hostname
    register_monitoring = var.add_to_monitoring
  })
  ...
}

jsonencode() or yamlencode()

trim

  • trim - trim(string, str_character_set) removes the specified set of characters from the start and end of the given string.
  • trimprefix - trimprefix("helloworld", "hello") removes a word from the start of a string.
  • trimsuffix - trimsuffix("helloworld", "world") removes a word from the end of a string.
  • trimspace - trimspace(" hello\n\n") removes all types of whitespace from both the start and the end of a string.

join(separator, list)

join(", ", ["foo", "bar", "baz"]) # foo, bar, baz
join(", ", ["foo"]) # foo

split(separator, string)

split(",", "foo,bar,baz")
[
  "foo",
  "bar",
  "baz",
]
> split(",", "foo")
[
  "foo",
]
> split(",", "")
[
  "",
]

[»](https://www.terraform.io/language/functions/split#related-functions)Related Fu

format(spec, values...)

https://www.terraform.io/language/functions/format

format("%s/%s",var.string,"string2")
format("Hello, %s!", "Ander")  # Hello, Ander!
format("There are %d lights", 4) # There are 4 lights
format("Hello, %s!", var.name) # Hello, Valentina!
"Hello, ${var.name}!" # Hello, Valentina!

chomp

removes newline characters at the end of a string

> chomp("hello\n")
hello
> chomp("hello\r\n")
hello
> chomp("hello\n\n")
hello

regex

variable "location_4" {
  type = string
  description = "Location of Device"
  default = "Rack 3, Position 12"
}
locals {
  location_4 = regex("(Rack [0-9]+), (Position [0-9]+)",var.location_4)
}
output "location_4_1" {
  description = "(sanitized) Location of Device"
  value = local.location_4
}

The output of the above function will look like this:

location_4_1 = [
"Rack 3",
"Position 12",
]

Note that the string changed into a list with two items. These items correspond to the search pattern groups that we defined.

replace

variable "sensitive_location" {
type = string
description = "(unsanitized) Location of Device"
default = "Rack 3, Position 12"
}
output "sensitive_location" {
description = "(sanitized) Location of Device"
value = replace(var.sensitive_location, "Rack ", "")
}
# or
output "combined_location" {
description = "(sanitized) Location of Device"
value = replace(var.sensitive_location, "/Rack | Position
/", "")

cidrsubnet cidrsubnets

generate subnets with a single base CIDR block

variable "cidr" {
type = string
default = "10.0.0.0/16"
description = "A network address prefix in CIDR notation"
}
locals {
private_subnets = [
cidrsubnet(var.cidr, 8, 1),
cidrsubnet(var.cidr, 8, 2),
cidrsubnet(var.cidr, 8, 3)
]
public_subnets = [
cidrsubnet(var.cidr, 8, 4),
 cidrsubnet(var.cidr, 8, 5),
cidrsubnet(var.cidr, 8, 6)
]
}
output "public_subnets" {
value = local.public_subnets
description = "Computed public subnet CIDR blocks"
}
output "private_subnets" {
value = local.private_subnets
description = "Computed private subnet CIDR blocks"
}
$ terraform plan
Changes to Outputs:
+ private_subnets = [
+ "10.0.1.0/24",
+ "10.0.2.0/24",
+ "10.0.3.0/24",
]
+ public_subnets = [
+ "10.0.4.0/24",
+ "10.0.5.0/24",
+ "10.0.6.0/24",

HashiCorp’s subnets module


### merge
Takes an arbitrary number of maps or objects, and returns a single map or object that contains a merged set of elements from all arguments.
If more than one given map or object defines the same key or attribute, then the one that is **later in the argument sequence takes precedence**.

merge({a="b"}, {a=[1,2], c="z"}, {d=3}) { "a" = [ 1, 2, ] "c" = "z" "d" = 3 }


Example uses the expansion symbol (...) to transform the value into separate arguments

merge([{a="b", c="d"}, {}, {e="f", c="z"}]...) { "a" = "b" "c" = "z" "e" = "f" }



### Expanding Function Arguments

If the arguments to pass to a function are available in a list or tuple value, that value can be expanded into separate arguments. Provide the list value as an argument and follow it with the ... symbol:

min([55, 2453, 2]...) # ---> konwertuje na min (55,2453, 2)