Bezideiko
Bezideiko

Reputation: 63

Overriding Name tag in Terraform

For the needs of our projects, we need to automate the AWS instance creation via Terraform (v. 0.13.5). We are using Jenkins pipeline which have a groovy script and call the terraform using this shell:

   sh """
      terraform init
      terraform apply -auto-approve \
        -var-file=${terraform_vars_filename} \
          -var 'vm-state=running' \
          -var 'vm-private-key=${AWS_KEY}' \
    """.stripIndent()

Because we will operate on different AWS instances, we need to have a way to manage the AWS instances Name during creation, so every instance should have unique name (which is managed by field in the Jenkins job. So in other words we need to "import" a groovy variable (let's say ${nameAwsInstance}) into Terraform Name tag (which is used in AWS instance creation).

I have tried different approaches, mostly based with "-var" option, trying to override the Name tag, e.g.:

-var 'var.tags["Name"]=${nameAwsInstance}

however neither of them worked.

So, is it possible to override Name tag and what is the syntax ?

P.S. if there are other ideas, I would be very happy.

Best regards.

Upvotes: 0

Views: 881

Answers (1)

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24251

I don't think there's a way without modifying the .tf file, which you seem to aim at.

So if modifying .tf in fine for you, I suggest to:

  • use a variable in your AWS instance name definition, e.g.
resource "aws_instance" "myserver" {
  ami           = "ami-005e54dee72cc1d00"
  instance_type = "t2.micro"

  tags = {
    Name = var.my_instance_name
  }
}
  • and then call terraform with an environment variable, e.g.
export TF_VAR_my_instance_name=somethingSpecial
terraform apply

Here are the docs for variables in Terraform.

Upvotes: 2

Related Questions