Home > front end >  Create Assume Role Policy with dynamic blocks
Create Assume Role Policy with dynamic blocks

Time:10-24

I am trying to create a Data Source for Assume Role Policy according to the terraform documentation,

Defining the "PRINCIPALS" code block and assigning the harcoded data works without a problem, but I want to assign the dynamic values from a tfvars file. When using the same dynamic block for "STATEMENT" it does not recognize the values even though it is similar to the initial block, I hope I have made myself understood.

variables.tf
variable "assume_role" {
  description = "Assume  example"
  type = map(object({
    sid     = string
    effect  = string
    actions = list(string)
    principals = map(string)
  }))
}
main.tf
data "aws_iam_policy_document" "assume-role-policy" {

  dynamic "statement" {
    for_each = var.assume_role
    content {
      actions = lookup(statement.value, "actions")
      effect  = lookup(statement.value, "effect")
      sid     = lookup(statement.value, "sid")

      
      # this way works fine.. but with the dynamic block doesn't 
      # principals {
      #   type        = "Service"
      #   identifiers = ["glue.amazonaws.com"]
      # }

      dynamic "principals" {
        for_each = lookup(statement.value, "principals", {})
        content {
          type        = lookup(principals.value, "type")
          identifiers = lookup(principals.value, "identifiers")
        }
      }
    }
  }
}


resource "aws_iam_role" "instance" {
  name               = "instance_role_example"
  assume_role_policy = data.aws_iam_policy_document.assume-role-policy.json
}



inn.tfvars

assume_role = {
  assume = ({
    sid     = "1010"
    effect  = "Allow"
    actions = ["sts:AssumeRole"]
    principals = {
      type        = "Service"
      identifiers = "glue.amazonaws.com"
    }
  })
}

Result:

enter image description here

enter image description here

Thank you very much in advance

CodePudding user response:

It does not work, because there is nothing in principals to iterate over. You have only a single map, not a list of maps, nor a map of maps. You just directly access the fields (no iteration required):

      dynamic "principals" {
        for_each = lookup(statement.value, "principals", {})
        content {
          type        = lookup(statement.value.principals, "type")
          identifiers = [lookup(statement.value.principals, "identifiers")]
        }
      }     
  • Related