terraform 에서 aws IAM policy 깔끔하게 templatefile로 말아넣기!

templatefile()
함수 쓰기
templatefile - Functions - Configuration Language | Terraform by HashiCorp
The templatefile function reads the file at the given path and renders itscontent as a template.

Terraform 0.12 부터 사용할 수 있는 templatefile()
을 쓰면 IAM을 잘 말아 쓸 수 있습니다. 원래는 테라폼 코드에 EOF
를 쓰며 지저분하고 유지보수하기 어려운 상태를 유지하고 있었다. 예를 들면 이런 식으로.
resource "aws_iam_role" "hello" {
name = "hello-iam-role"
path = "/"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
}
resource "aws_iam_role_policy" "hello_s3" {
name = "hello-s3-download"
role = aws_iam_role.hello.id
policy = <<EOF
{
"Statement": [
{
"Sid": "AllowAppArtifactsReadAccess",
"Action": [
"s3:GetObject"
],
"Resource": [
"*"
],
"Effect": "Allow"
}
]
}
EOF
}
resource "aws_iam_instance_profile" "hello" {
name = "hello-profile"
role = aws_iam_role.hello.name
}
그러므로 templatefile
함수와 함께 이 지저분한 코드를 정리하자.
람다를 위한 policy를 선언해보자.
resource "aws_iam_policy" "policy_for_iam" {
name = "policy_${var.service_name}"
policy = templatefile("policy.json.tftpl", {
aws_account_id = data.aws_caller_identity.current.account_id
aws_region = var.aws_region,
function_name = var.function_name
})
}
간단하다. policy.json.tftpl
파일에 렌더링할 데이터를 함수 변수로 넣어주면 끝이다. 이 템플릿 파일은 아래와 같다.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:${aws_region}:${aws_account_id}:*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:${aws_region}:${aws_account_id}:log-group:/aws/lambda/${function_name}:*"
]
}
]
}
에디터에서도 깔끔하게 Json 을 사용할 수 있는 장점도 있고, resource 선언이 훨씬 보기 쉽다.