Follow Set up Terraform with AWS from scratch if you don't have these prerequisites configured.
Input Variables serve as parameters for a Terraform module, so users can customize behavior without editing the source. In this tutorial we will learn how to use variables and will create an EC2 instance by using input variables.
Define Variable
mkdir learn-tf-variables
cd learn-tf-variables
variables.tf
.
variables.tf
variable "aws_region" {
description = "AWS region"
type = string
}
variables.tf
variable "ami_id" {
description = "AMI ID"
type = string
}
variables.tf
variable "instance_type" {
description = "EC2 Instance Type"
type = string
}
variables.tf
variable "instance_tags" {
description = "Tags to set for instances"
type = map(string)
}
variables.tf
should look
like as shown below.
variable "aws_region" {
description = "AWS region"
type = string
}
variable "ami_id" {
description = "AMI ID"
type = string
}
variable "instance_type" {
description = "EC2 Instance Type"
type = string
}
variable "instance_tags" {
description = "Tags to set for instances"
type = map(string)
}
Assign Values
We have defined variables to Parameterize aws_region,
ami_id, instance_type and
instance_tags, lets assign values to variables. To assign
values create a file named
terraform.tfvars
and write
below content.
aws_region = "us-east-1"
instance_type = "t2.micro"
ami_id = "ami-033b95fb8079dc481"
instance_tags = {
Name = "Test instance",
Environment = "Test"
}
Create EC2 Instance
Create a file name
main.tf
and write below
configuration.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.27"
}
}
required_version = ">= 0.14.9"
}
provider "aws" {
profile = "default"
region = var.aws_region
}
resource "aws_instance" "test_instance" {
ami = var.ami_id
instance_type = var.instance_type
tags = var.instance_tags
}
Run commands terraform fmt
,
terraform validate
and
finally terraform apply
,
respond to the prompt with
yes
to apply changes.
terraform apply
Category: AWS