Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform: Conditional statement blocks in aws_iam_policy_document?

Is there a way to conditionally add statement blocks in aws_iam_policy_document? I'm looking for something like:

data "aws_iam_policy_document" "policy" {
  statement {
    sid = "PolicyAlways"

    ...
  }

  if (var.enable_optional_policy) {
    statement {
      sid = "PolicySometimes"

      ...
    }
  }
}
like image 522
jbreed Avatar asked May 26 '20 18:05

jbreed


People also ask

How do I use AWS IAM policy variables with terraform?

In order to use AWS policy variables with this data source, use & {...} notation for interpolations that should be processed by AWS rather than by Terraform. For more information about building AWS IAM policy documents with Terraform, see the AWS IAM Policy Document Guide.

What is a condition block in AWS?

A condition constrains whether a statement applies in a particular situation. Conditions can be specific to an AWS service. When using multiple condition blocks, they must all evaluate to true for the policy statement to apply. In other words, AWS evaluates the conditions as though with an "AND" boolean operation.

How do I render an AWS principal in TerraForm?

To have Terraform render JSON containing "Principal": "*", use type = "*" and identifiers = ["*"]. To have Terraform render JSON containing "Principal": {"AWS": "*"}, use type = "AWS" and identifiers = ["*"]. For more information about AWS principals, refer to the AWS Identity and Access Management User Guide: AWS JSON policy elements: Principal.

What is a dynamic block in TerraForm?

Terraform has a cool resource block called the 'dynamic' block that allows generating multiple nested blocks for a resource. This tutorial will show you how to generate multiple IAM policy statements using this dynamic block.


1 Answers

Yes. You can (ab)use a dynamic block with a boolean to optionally include the block.

data "aws_iam_policy_document" "policy" {
  statement {
    sid = "PolicyAlways"

    ...
  }

  dynamic "statement" {
    # The contents of the list below are arbitrary, but must be of length one. 
    # It is only used to determine whether or not to include this statement.
    for_each = var.enable_optional_policy ? [1] : []

    content {
      sid = "PolicySometimes"
      ...
    }
  }
}
like image 94
Ben Whaley Avatar answered Sep 21 '22 21:09

Ben Whaley