🧰 Built-in Functions (Core Utilities)
1️⃣ file(path)
- Reads a local file → returns string ✔
- Used for: scripts, SSH keys, configs
resource "aws_instance" "cerberus" {
ami = "ami-06178cf087598769c"
instance_type = "m5.large"
key_name = aws_key_pair.cerberus-key.key_name
user_data = file("/root/terraform-projects/project-cerberus/install-nginx.sh")
}
resource "aws_key_pair" "cerberus-key" {
key_name = "cerberus"
public_key = file("/root/terraform-projects/project-cerberus/.ssh/cerberus.pub")
}
2️⃣ templatefile(path, vars)
- Reads a file and renders variables → returns string ✔
- e.g. line in file
echo "Deployed by ${name} in ${region}"
user_data = templatefile("nginx.sh",{
name = "Om"
region = "ap-south-1"
})
3️⃣ jsondecode(string)
- Converts JSON string → map/object 💡
locals { config = jsondecode(file("config.json")) }
4️⃣ yamldecode(string)
- Converts YAML string → map/object 💡
locals { values = yamldecode(file("values.yaml")) }
5️⃣ toset(list)
- Converts list → set (for
for_each) ✔
variable "users" {
type = list(string)
default = [
"nginx",
"docker",
"aws"
]
}
resource "local_file" "setup" {
for_each = toset(var.users)
filename = "${each.value}.txt"
content = "Installing ${each.value}..."
}
6️⃣ tomap(object)
tags = tomap({ Name="app", Env="prod" })
🗂 Data Sources (Read External Data, No Resource Creation)
8️⃣ data "http"
- Calls API/URL → fetches response
data "http" "example" { url = "..." }
9️⃣ data "aws_ssm_parameter"
- Reads value from Parameter Store ✔🔐
data "aws_ssm_parameter" "db_pass" {
name = "/prod/db/pass"
}
resource "local_file" "ssm_debug" {
filename = "db-password-from-ssm.txt"
content = data.aws_ssm_parameter.db_pass.value
}
1️⃣1️⃣ data "aws_secretsmanager_secret_version"
- Reads secret from Secrets Manager ✔🔐
data "aws_secretsmanager_secret_version" "app" {
secret_id = "cerberus-app-secret"
}
resource "local_file" "secret_debug" {
filename = "app-secret.json"
content = data.aws_secretsmanager_secret_version.app.secret_string
}