1

I am provisiong an EC2 instance using Terraform. It also has a startup script. I have vars.tf where I have specified all the variables in it. In my bash.sh script it should pickup one variable from vars.tf

Is it possible to refer the variable in vars.tf from bash script? Below is my use case.

bash.sh

#!/bin/bash

docker login -u username -p token docker.io

vars.tf

variable "username" {
  default = "myuser"
}

variable "token" {
  default = "mytoken"
}

My bash script should pick the variable from vars.tf

If this is not possible any workaround?

Container-Man
  • 434
  • 1
  • 6
  • 17
  • It is unfortunate that Terraform uses its own format for these things. If you can't find an existing parser, you'll have to write your own. – tripleee Apr 23 '22 at 18:41
  • 2
    Is this bash script, user data to be run by cloud init? If so, yes, you can just build your script with those variables rendered in the template using the [templatefile](https://www.terraform.io/language/functions/templatefile) function. – theherk Apr 23 '22 at 18:44
  • 2
    This question was wrongfully closed. The correct answer would be to use a [templatefile](https://www.terraform.io/language/functions/templatefile) with which would be possible to pass variables to the script provided from a `vars.tf` file. – Ervin Szilagyi Apr 23 '22 at 18:46
  • Yes, I can understand @tripleee's confusion, but this probably shouldn't have been closed out of hand as the marked duplicate is for the opposite of what is being asked here. – theherk Apr 23 '22 at 18:54
  • a simple solution could be to use terraform output. Create an output and just add the variable to them. In your bash script, you can then use something like MYVAR=$(terraform output myoutput) – Daniel Seichter Apr 23 '22 at 21:18
  • I would also agree that is the correct answer, so if either of you want to write it up, then we can solve this question. – Matthew Schuchard Apr 24 '22 at 11:15

1 Answers1

3

In order to provide Terraform variables to a script, we can use templatefile function. This function reads to content of a template file and injects Terraform variables in places marked by the templating syntax (${ ... }).

First we want to create a template file with the bash script and save it as init.tftpl:

#!/bin/bash

docker login -u ${username} -p ${token} docker.io

When creating the instance, we can use templatefile to provide the rendered script as user data:

resource "aws_instance" "web" {
  ami           = "ami-xxxxxxxxxxxxxxxxx"
  instance_type = "t2.micro"
  user_data = templatefile("init.tftpl", {
    username = var.username
    token    = var.token
  })
}
Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40