I have the Terraform code (below) that is suppose to create an IAM policy. However, on terraform apply
, I get the error:
Error: creating IAM Policy autoscale-policy: MalformedPolicyDocument: The policy failed legacy parsing
Terraform code:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.52.0"
}
}
}
provider "aws" {
region = "us-west-2"
}
resource "aws_iam_policy" "autoscale_policy" {
name = "autoscale-policy"
description = "EBS Autoscaling Policy"
policy = <<EOT
{
"Version": "2012-10-17",
"Statement": {
"Action": [
"ec2:AttachVolume",
"ec2:DescribeVolumeStatus",
"ec2:DescribeVolumes",
"ec2:ModifyInstanceAttribute",
"ec2:DescribeVolumeAttribute",
"ec2:CreateVolume",
"ec2:DeleteVolume",
"ec2:CreateTags",
"kms:Decrypt",
"kms:CreateGrant",
"kms:Encrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*",
"Effect": "Allow"
}
}
EOT
}
However, when I use the AWS cli with the exact same policy, the policy is created in AWS with no issue:
--policy-name TestPolicy \
--policy-document \
'{
"Version": "2012-10-17",
"Statement": {
"Action": [
"ec2:AttachVolume",
"ec2:DescribeVolumeStatus",
"ec2:DescribeVolumes",
"ec2:ModifyInstanceAttribute",
"ec2:DescribeVolumeAttribute",
"ec2:CreateVolume",
"ec2:DeleteVolume",
"ec2:CreateTags",
"kms:Decrypt",
"kms:CreateGrant",
"kms:Encrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*",
"Effect": "Allow"
}
}'
Does anyone see where there might be a difference between the TF code and the CLI command? How come my TF code returns a MalformedPolicyDocument
error when the policy works fine from the cli?
CodePudding user response:
Statement should be an array.
resource "aws_iam_policy" "autoscale_policy" {
name = "autoscale-policy"
description = "EBS Autoscaling Policy"
policy = <<EOT
{
"Version": "2012-10-17",
"Statement": [{
"Action": [
"ec2:AttachVolume",
"ec2:DescribeVolumeStatus",
"ec2:DescribeVolumes",
"ec2:ModifyInstanceAttribute",
"ec2:DescribeVolumeAttribute",
"ec2:CreateVolume",
"ec2:DeleteVolume",
"ec2:CreateTags",
"kms:Decrypt",
"kms:CreateGrant",
"kms:Encrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*",
"Effect": "Allow"
}]
}
EOT
}
tested it works
OR you can you data
resource to define your policies.
resource "aws_iam_policy" "autoscale_policy" {
name = "autoscale-policy"
description = "EBS Autoscaling Policy"
policy = data.aws_iam_policy_document.example.json
}
data "aws_iam_policy_document" "example" {
statement {
actions = [
"ec2:AttachVolume",
"ec2:DescribeVolumeStatus",
"ec2:DescribeVolumes",
"ec2:ModifyInstanceAttribute",
"ec2:DescribeVolumeAttribute",
"ec2:CreateVolume",
"ec2:DeleteVolume",
"ec2:CreateTags",
"kms:Decrypt",
"kms:CreateGrant",
"kms:Encrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
]
resources = ["*"]
effect = "Allow"
}
}