Amazon Web Services, AWS, Cloud, Infrastructure as a Code, open source, Server, Terraform

Using variables in Terraform

September 14, 2017

I hope my previous article on Terraform was helpful and you were able to create your first AWS EC2 instance using Terraform.

Further in this article we are going to talk about variables. Variables are important part of Terraform. There would be elements which would change or reused. Based on different requirements some decisions need to be made. Also, you don’t want to keep your credentials in plain text files. Different AMIs need to used depending upon region and requirement. Variables are always helpful to remove ambiguity in code.

In last article we used values directly in “instance.tf”. Here we will split the content to different files. The first file we would be using is “provider.tf”. We will assign variables to properties we want. We will assign access key,secret key and region variable. Content of file would look like.

 

provider “aws” {
          access_key = “${var.VirtualSingh_ACCESS_KEY}”
          secret_key = “${var.VirtualSingh_SECRET_KEY}”
          region = “${var.VirtualSingh_REGION}”
         }

The next file we will create is vars.tf. In this file we will declare all the variable we will use in our environment.

The contents of the file would look like as below:

provider “aws” {
     access_key = “${var.VirtualSingh_ACCESS_KEY}”
     secret_key = “${var.VirtualSingh_SECRET_KEY}”
     region = “${var.VirtualSingh_REGION}”
}

 

 

The third file we will create is terraform.tfvars file. This file will contain values of our variables. This file should be in your git ignore so that this is never part of your repository. You can leave “VirtualSingh_REGION” in this file because we have already set default value for it. You can use it if you want to overwrite it.

The content of the file would look like as below:

 

VirtualSingh_ACCESS_KEY = “”
VirtualSingh_SECRET_KEY = “”
VirtualSingh_REGION=”eu-central-1″

There are empty values but you can fill in your values here.

The new “instance.tf” would be like:

resource “aws_instance” “VirtualSingh ” {
     ami = “ami-958128fa”
     instance_type = “t2.micro”
}

We moved the provider part to new file here.

You can simply go to the folder in which all this files are saved and hit “Terraform apply”. Your new instance would be created using variables here.

If you are using free tier or using this for educational purpose dont”t forget to hit “terraform destroy” before you close it.

Happy Coding!

You Might Also Like

No Comments

Leave a Reply