Home > Net >  How can I use variables in terraform module when call data/resources?
How can I use variables in terraform module when call data/resources?

Time:01-18

I got a basic Terraform code where the main.tf call a module to create an AWS organization policy.

** main.tf **

module "SCP-L2-RegionRestriction" {
  source        = "github.com/awsmodulecode/scps.git"
  scp_name      = "SCP-L2-RegionRestriction"
} 

** module **

resource "aws_organizations_policy" "SCP-L2-RegionRestriction" {
  name    = var.scp_name
  content = data.aws_iam_policy_document."${var.scp.name}".json
}

** variables.tf **

variable "scp_name" {
  description = "Policy name."
}

** The error **

╷
│ Error: Invalid attribute name
│ 
│ On .terraform/modules/SCP-L2-RegionRestriction/main.tf line 4: An attribute name is required after a dot.
╵

Is there a way to manage variable "${var.scp.name}" inside of a data call?

This is my data source content:

data "aws_iam_policy_document" "scp_fulladmin_deny" {
    statement {
            actions = ["*"]
            resources = ["*"]
            effect = "Deny"
            }
}
data "aws_iam_policy_document" "scp_fulladmin_allow" {
    statement {
            actions = ["*"]
            resources = ["*"]
            effect = "Allow"
            }
}

CodePudding user response:

You can not use variables to reference data or resources; but you can do something like this:

locals {
    policy_map = {
        scp_fulladmin_deny = data.aws_iam_policy_document.scp_fulladmin_deny.json,
        scp_fulladmin_allow = data.aws_iam_policy_document.scp_fulladmin_allow.json,
    }
}

resource "aws_organizations_policy" "this" {
    name = var.scp_name
    content = local.policy_map[var.scp_name]
}
  • Related