Is it possible to reference the resource name inside the resource itself

Viewed 1518

I'd like to use a resource name inside the resource itself to avoid string duplication and copy/paste errors.

resource "aws_instance" "bastion-euw3-infra-01" {
  ami           = "ami-078db6d55a16afc82"
  instance_type = "t2.micro"
  key_name      = "sylvain"

  user_data = templatefile("./scripts/cloudinit.yaml", {
    hostname          = "bastion-euw3-infra-01"
    tailscale_authkey = var.tailscale_authkey
  })

  network_interface {
    device_index         = 0
    network_interface_id = aws_network_interface.bastion-euw3-infra-01.id
  }

  tags = {
    Name        = "bastion-euw3-infra-01"
    Environment = "infra"
  }

  lifecycle {
    ignore_changes = [user_data]
  }
}

Basically I'd like to replace "bastion-euw3-infra-01" inside the resource with some kind of var, e.g.:

resource "aws_instance" "bastion-euw3-infra-01" {
  ...

  user_data = templatefile("./scripts/cloudinit.yaml", {
    hostname          = ___name___
    tailscale_authkey = var.tailscale_authkey
  })

  ...

  tags = {
    Name        = ___name___
    Environment = "infra"
  }

  ...
}

Does terraform provide a way to do this ?

0 Answers
Related