Prerequisites
Installation on Linux
https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli
link for installation
Install VS Code also the extensions for Terraform.
Make a new folder.
Check if Terraform is installed.
How to write with HCL - Language for writing terraform
Syntax
#blocks and arguments
<block> <arguments> {
key1 = value1
}
Example:
resource "local_file" "batch3" {
filename = "ash_new.txt"
content = "this is my first script of terraform"
}
resource "random_string" "batch3_string" {
length = 15
}
output "batch_string" {
value = random_string.batch3_string[*].result
}
terraform init # Intializing terraform in the folder
terraform apply #A new file ash.txt is created with specific content
For changing the file as the name is already batch 3 it is defined in the state page, hence only the file name will be changed by re-entering the init command. init command has to be initialized every time we add something new
How to create a Docker Container using HCL
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 3.0.1"
}
}
}
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:latest"
keep_locally = false
}
resource "docker_container" "nginx" {
image = docker_image.nginx.image_id
name = "tutorial"
ports {
internal = 80
external = 80
}
}
Inspect the current state using terraform show
. Terraform has a built-in command called terraform state
for advanced state management. Use the list
subcommand to list the resources in your project's state. After applying check in local host with port 8000.
How to create Instances in AWS
Prerequisites:-
Create a Terraform admin user and configure it in the terminal:
aws configure
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 3.0.1"
}
}
}
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:latest"
keep_locally = false
}
resource "docker_container" "nginx" {
image = docker_image.nginx.image_id
name = "tutorial"
ports {
internal = 80
external = 8000
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "batch9_bucket"{
bucket = "batch-9-test-bucket"
tags = {
Name = "batch-9-test-bucket"
}
}
resource "aws_instance" "batch3_instance" {
count = 5
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
tags = {
Name = "btach-3-test-instance"
}
}
terraform apply # for creating the instances
terraform destroy # for terminating the instances