Terraform formatlist example

ismail yenigül
1 min readAug 14, 2020

--

formatlist produces a list of strings by formatting a number of other values according to a specification string. Here is an example to create parametric policy based on formatlist instead of typing all permissions manually for each policy.

provider "aws" {
region = "eu-west-1"
}
variable policy_permissions {
type = list(string)
default = ["ec2", "ecs", "eks", "rds", "elasticache","s3"]
}
data "aws_iam_policy_document" "mypolicy" {
statement {
sid = "GrantAccessForsomebody"
actions = formatlist("%s:*", var.policy_permissions)
resources = ["*"]
}
}
resource "aws_iam_role_policy" "myrole" {
name = "myrole"
role = "iam-test"policy = data.aws_iam_policy_document.mypolicy.json
}

and here is the terraform plan output

Terraform will perform the following actions:# aws_iam_role_policy.myrole will be created+ resource "aws_iam_role_policy" "myrole" {
+ id = (known after apply)
+ name = "myrole"
+ policy = jsonencode(
{
+ Statement = [
+ {
+ Action = [
+ "s3:*",
+ "rds:*",
+ "elasticache:*",
+ "eks:*",
+ "ecs:*",
+ "ec2:*",
]

+ Effect = "Allow"
+ Resource = "*"
+ Sid = "grantAccess"
},
]
+ Version = "2012-10-17"
}
)
+ role = "iam-test"
}
Plan: 1 to add, 0 to change, 0 to destroy.

Ismail YENIGUL

Devops Engineer

--

--

ismail yenigül
ismail yenigül

Written by ismail yenigül

CKA/CKAD,AWS certified Freelancer DevOps Engineer

No responses yet