Terraform Configuration

With AWS (As of now)

Table of contents
  1. Terraform Block
  2. Provider
  3. Resource
  4. Using variables

Terraform Block

It contains the Terraform settings and has the basic structure of the following

terraform {
  required_providers {
    mylocalname = {
      source = "source/address"
      version = "~> 1.0"
    }
  }
  required_version = ">= 0.14.9"
}

Throughout the module, Terraform refers to providers using a local name. Here I’ve given it a name of mylocalname.

Source address takes the form of [Hostname/]Namespace/Type. If Hostname is ommitted, it defaults to registry.terraform.io which is Terraform’s default provider install source. hashicorp/aws is a shorthand for registry.terraform.io/hashicorp/aws.

For the version constraint syntax, refer to Version Constraint Syntax.


Provider

You can configure each provider using the local name you have provided in the required_providers of the Terraform block.

For example,

provider "mylocalname" {
  # ...
}

Reference Provider Configuration for details.


Resource

Basic syntax is as follows,

resource "aws_instance" "my_server" {
  ami = "ami-a1b2c3d4"
  instance_type = "t2.micro"
}

The example block above declares a resource type "aws_instance" and gives it a local name of "my_server".

Just like the provider local name, resource local name is used to refer to this resource throughout the module.

In addition, the unique ID for the resource becomes aws_instance.my_server.

The resource configuration arguments within the block body are specific to each resource type.

For an example, refer to documentation here for aws_instance.


Using variables

To avoid using hard-coded values in configuration, create a new file variables.tf (name of the file can be anything you want) with the following:

variable "variable_name" {
  description = "Some description of what this is"
  type = string
  default = "This is the value of the variable"
}

You can then use the variables in other .tf files as,

var.variable_name

You can also pass in a new variable value for testing by

terraform apply -var 'variable_name=SomeOtherValue'

It will modify the state so that all the variables use the new value.

This does not update the original variable declaration. If you run terraform apply again without the -var flag, the state will be modified using the original value.


References: