StevieHyperB
StevieHyperB

Reputation: 347

Terraform - Interpolating variable values

I am trying to call a variable within the below, but having to enter it in manually at the moment, a little stuck. How do I get Terraform to automatically insert the variable's value.

resource "aws_iam_role" "aws-admin-role" {
  name        = "AWS-AdminAccess"
  description = "Administration of Account from AWSxx"

  assume_role_policy = <<EOF
{  
  "Version":"2012-10-17",
  "Statement":[  
    {  
      "Effect":"Allow",
      "Principal":{  
        "AWS":"arn:aws:iam::INSERTACCOUNTMANUALLY:root"
      },
      "Action":"sts:AssumeRole",
      "Condition":{  

      }
    }
  ]
}
EOF
}

Upvotes: 0

Views: 1366

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56849

Terraform allows you to interpolate values that it knows about such as variables or outputs from data sources, resources or modules.

In your case you could use the aws_caller_identity data source to dynamically fetch the account ID of the caller and insert that into your IAM policy with something like this:

data "aws_caller_identity" "current" {}

resource "aws_iam_role" "aws-admin-role" {
  name        = "AWS-AdminAccess"
  description = "Administration of Account from AWSxx"

  assume_role_policy = <<EOF
{  
  "Version":"2012-10-17",
  "Statement":[  
    {  
      "Effect":"Allow",
      "Principal":{  
        "AWS":"arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"
      },
      "Action":"sts:AssumeRole",
      "Condition":{  

      }
    }
  ]
}
EOF
}

If, instead, you wanted to use a variable to refer to a different AWS account you could do something like this:

variable "account_id" {}

resource "aws_iam_role" "aws-admin-role" {
  name        = "AWS-AdminAccess"
  description = "Administration of Account from AWSxx"

  assume_role_policy = <<EOF
{  
  "Version":"2012-10-17",
  "Statement":[  
    {  
      "Effect":"Allow",
      "Principal":{  
        "AWS":"arn:aws:iam::${var.account_id}:root"
      },
      "Action":"sts:AssumeRole",
      "Condition":{  

      }
    }
  ]
}
EOF
}

Upvotes: 1

Related Questions