'How to pick variables in vars.tf from BASH script

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?



Solution 1:[1]

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
  })
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1