Konfigurasi Dasar
Membuat konfigurasi Terraform pertama
File Konfigurasi Terraform
Terraform menggunakan sintaks HCL (HashiCorp Configuration Language).
Contoh: EC2 Instance
providers.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-southeast-1"
}main.tf
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "WebServer"
}
}variables.tf
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
}
variable "region" {
description = "AWS region"
type = string
default = "ap-southeast-1"
}outputs.tf
output "instance_ip" {
description = "Public IP dari EC2"
value = aws_instance.web.public_ip
}Tipe Data HCL
- string:
"hello" - number:
42 - bool:
true,false - list:
["a", "b", "c"] - map:
{ name = "web", port = 80 } - object: Tipe data terstruktur
Resource dan Data Source
Resource
- Membuat atau mengubah infrastruktur
resource "aws_s3_bucket" "example" { ... }
Data Source
- Membaca data resource yang sudah ada
- Tidak mengubah resource
data "aws_ami" "latest" { ... }
Contoh: S3 Bucket
resource "aws_s3_bucket" "assets" {
bucket = "my-app-assets-123"
}
resource "aws_s3_bucket_public_access_block" "assets" {
bucket = aws_s3_bucket.assets.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}Menggunakan Variabel
Dari Command Line
terraform apply -var="instance_type=t3.small"Dari File
terraform apply -var-file="production.tfvars"tfvars File
instance_type = "t3.medium"
region = "ap-southeast-1"