Passing region name as variable to templatefile?

I have the following script and would like to pass the region name as a variable to the templatefile() call.

How can I do that ?

provider "aws" {
  region = "ca-central-1"
}

data "aws_iam_role" "example" {
  name = "s3fsmountingrole"
}

data "aws_region" "current" {}

resource "aws_s3_bucket" "mybucket" {
  bucket = "nicholas-yue-my-tf-test-bucket"
}

resource "aws_s3_bucket_policy" "mypolicy" {
  bucket = aws_s3_bucket.mybucket.id

  policy = templatefile("${path.module}/s3_bucket_policy.tpl", {
    iam_role_arn = data.aws_iam_role.example.arn
    s3_arn = aws_s3_bucket.mybucket.arn
  })
}

resource "aws_security_group" "mysg_allow_ssh" {
  name        = "mysg_allow_ssh"
  description = "Allow SSH inbound traffic"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "user_data" {
  ami             = "ami-0a269ca7cc3e3beff"
  instance_type   = "t2.micro"
  security_groups = [aws_security_group.mysg_allow_ssh.name]
  key_name        = "testssh"
  user_data       = templatefile("${path.module}/user_data.sh",{
    region_name = "ca-central-1"
    iam_role_name = data.aws_iam_role.example.name
  })
  iam_instance_profile = data.aws_iam_role.example.name

  tags = {
    Name = "HelloWorld"
  }

  connection {
    host        = self.public_ip
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("~/.ssh/testssh.pem")
  }

  # Need to wait for user_data to complete which might take time
  provisioner "remote-exec" {
    inline = [
      "sudo cloud-init status --wait"
    ]
  }
}


output "IP" {
  value = aws_instance.user_data.public_ip
}


output "S3-ARN" {
  value = aws_s3_bucket.mybucket.arn
}

output "IAM-ARN" {
  value = data.aws_iam_role.example.arn
}

Hi @nyue,

Assuming that when you say “the region” you mean the region specified in the provider configuration, it looks like you’re already using the aws_region data source to read that name and so the remaining step is to pass that result into the object given as the second argument to templatefile, similar to the other attributes you’ve already set:

  policy = templatefile("${path.module}/s3_bucket_policy.tpl", {
    iam_role_arn = data.aws_iam_role.example.arn
    s3_arn       = aws_s3_bucket.mybucket.arn
    region       = data.aws_region.current.name
  })

Inside the template you can then use region to refer to that name. For example, ${region} to just interpolate that region name directly into surrounding literal text.

1 Like