Evan Gertis
Evan Gertis

Reputation: 2062

Creating a StringLike condition with Terraform

I am trying to generate some terraform for an aws IAM policy. The condition in the policy looks like this

"StringLike": {
 "kms:EncryptionContext:aws:cloudtrail:arn": [
 "arn:aws:cloudtrail:*:aws-account-id:trail/*"
 ]

I am looking at the documentation for aws_iam_policy_document: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document, but it's not clear to me as to how to write this in terraform. Any help would be greatly apprecaited. This is my attempt

condition {
        test = "StringLike"
        variable = "kms:EncryptionContext:aws:cloudtrail:arn"

        values = [
            "arn:aws:cloudtrail:*:aws-account-id:trail/*"
        ]
    }

Upvotes: 0

Views: 7325

Answers (1)

Montassar Bouajina
Montassar Bouajina

Reputation: 1652

Hello Evan you logic is correct just to add :

Each document configuration may have one or more statement

data "aws_iam_policy_document" "example" {
  statement {
    actions = [
      "*", *//specify your actions here*
    ]

    resources = [
      "*", *//specify your resources here*
    ]
    condition {
     test = "StringLike"
     variable = "kms:EncryptionContext:aws:cloudtrail:arn"

     values = [
        "arn:aws:cloudtrail:*:aws-account-id:trail/*"
     ]
    }
}

Each policy statement may have zero or more condition blocks, which each accept the following arguments:

  • test (Required) The name of the IAM condition operator to evaluate.
  • variable (Required) The name of a Context Variable to apply the condition to. Context variables may either be standard AWS variables starting with aws:, or service-specific variables prefixed with the service name.
  • values (Required) The values to evaluate the condition against. If multiple values are provided, the condition matches if at least one of them applies. (That is, the tests are combined with the "OR" boolean operation.)

When multiple condition blocks are provided, they must all evaluate to true for the policy statement to apply. (In other words, the conditions are combined with the "AND" boolean operation.)

Here's the REF from terraform

IN Addition to create the policy from the document you created you use it like this:

resource "aws_iam_policy" "example" {
  policy = data.aws_iam_policy_document.example.json
}

Here's A ref from Hashicorp

Upvotes: 5

Related Questions