ใช้ Remote State และ Locking State ใน Terraform ด้วย S3 และ DynamoDB
Using Remote State and Locking State in Terraform with S3 and DynamoDB
— — — — — — — — — — — — — — —
สารบัญเนื้อหาทั้งหมด (My Contents)
— — — — — — — — — — — — — — —
สิ่งที่ต้องมี
- พื้นฐานการใช้งาน Terraform เบื้องต้น
- เข้าใจเรื่อง Terraform State เบื้องต้น
สร้าง S3 bucket
- Bucket name: nopnithi-terraform-state-demo
- Region: ap-southeast-1
- Bucket Versioning: Enable
- Default encryption: Enable (SSE-S3)
- ที่เหลือปล่อยเป็น default
สร้าง DynamoDB table
- Table name: nopnithi-terraform-state-demo
- Primary key: LockID (เป็น string)
- Table settings: ติ๊ก Use default settings
คอนฟิก Terraform Backend
เพิ่มส่วนนี้เข้าไปใน main.tf ใต้ Terraforn setting block
backend "s3" {
bucket = "nopnithi-terraform-state-demo"
key = "demo/terraform.tfstate"
region = "ap-southeast-1"
# Enable State Locking
dynamodb_table = "nopnithi-terraform-state-demo"
}
จะได้…
ไฟล์ 01-main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
backend "s3" {
bucket = "nopnithi-terraform-state-demo"
key = "demo/terraform.tfstate"
region = "ap-southeast-1"
# Enable State Locking
dynamodb_table = "nopnithi-terraform-state-demo"
}
}provider "aws" {
profile = "default"
region = "ap-southeast-1"
}
ทดลอง Provision EC2 ด้วย Terraform
ไฟล์ 02-ec2-instance.tf
resource "aws_instance" "ec2_demo" {
ami = "ami-0f511ead81ccde020"
instance_type = "t2.micro"
tags = {
Name = "EC2-Demo"
}
}
รัน terraform init
$ terraform initInitializing the backend...Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 3.0"...
- Installing hashicorp/aws v3.53.0...
- Installed hashicorp/aws v3.53.0 (signed by HashiCorp)Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.Terraform has been successfully initialized!You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
รัน terraform apply
$ terraform apply -auto-approveTerraform used the selected providers to generate the following execution plan. Resource
actions are indicated with the following symbols:
+ createTerraform will perform the following actions:# aws_instance.ec2_demo will be created
+ resource "aws_instance" "ec2_demo" {
+ ami = "ami-0f511ead81ccde020"
+ arn = (known after apply)
+ associate_public_ip_address = (known after apply)
+ availability_zone = (known after apply)
+ cpu_core_count = (known after apply)
+ cpu_threads_per_core = (known after apply)
+ disable_api_termination = (known after apply)
+ ebs_optimized = (known after apply)
+ get_password_data = false
+ host_id = (known after apply)
+ id = (known after apply)
+ instance_initiated_shutdown_behavior = (known after apply)
+ instance_state = (known after apply)
+ instance_type = "t2.micro"
+ ipv6_address_count = (known after apply)
+ ipv6_addresses = (known after apply)
+ key_name = (known after apply)
+ monitoring = (known after apply)
+ outpost_arn = (known after apply)
+ password_data = (known after apply)
+ placement_group = (known after apply)
+ primary_network_interface_id = (known after apply)
+ private_dns = (known after apply)
+ private_ip = (known after apply)
+ public_dns = (known after apply)
+ public_ip = (known after apply)
+ secondary_private_ips = (known after apply)
+ security_groups = (known after apply)
+ source_dest_check = true
+ subnet_id = (known after apply)
+ tags = {
+ "Name" = "EC2-Demo"
}
+ tags_all = {
+ "Name" = "EC2-Demo"
}
+ tenancy = (known after apply)
+ user_data = (known after apply)
+ user_data_base64 = (known after apply)
+ vpc_security_group_ids = (known after apply)+ capacity_reservation_specification {
+ capacity_reservation_preference = (known after apply)+ capacity_reservation_target {
+ capacity_reservation_id = (known after apply)
}
}+ ebs_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ snapshot_id = (known after apply)
+ tags = (known after apply)
+ throughput = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}+ enclave_options {
+ enabled = (known after apply)
}+ ephemeral_block_device {
+ device_name = (known after apply)
+ no_device = (known after apply)
+ virtual_name = (known after apply)
}+ metadata_options {
+ http_endpoint = (known after apply)
+ http_put_response_hop_limit = (known after apply)
+ http_tokens = (known after apply)
}+ network_interface {
+ delete_on_termination = (known after apply)
+ device_index = (known after apply)
+ network_interface_id = (known after apply)
}+ root_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ tags = (known after apply)
+ throughput = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}
}Plan: 1 to add, 0 to change, 0 to destroy.
aws_instance.ec2_demo: Creating...
aws_instance.ec2_demo: Still creating... [10s elapsed]
aws_instance.ec2_demo: Still creating... [20s elapsed]
aws_instance.ec2_demo: Still creating... [30s elapsed]
aws_instance.ec2_demo: Creation complete after 33s [id=i-08daab717c124dcbb]Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
เมื่อเช็คดูจะเห็นว่าไฟล์ terraform.tfstate ถูกเก็บบน S3 แล้ว และมีไฟล์ถูกสร้างขึ้นใน DynamoDB table ด้วย (เพื่อทำ state locking)
รัน terraform destroy
$ terraform destroy -auto-approve
aws_instance.ec2_demo: Refreshing state... [id=i-08daab717c124dcbb]Terraform used the selected providers to generate the following execution plan. Resource
actions are indicated with the following symbols:
- destroyTerraform will perform the following actions:# aws_instance.ec2_demo will be destroyed
- resource "aws_instance" "ec2_demo" {
- ami = "ami-0f511ead81ccde020" -> null
- arn = "arn:aws:ec2:ap-southeast-1:xxx:instance/i-08daab717c124dcbb" -> null
- associate_public_ip_address = true -> null
- availability_zone = "ap-southeast-1a" -> null
- cpu_core_count = 1 -> null
- cpu_threads_per_core = 1 -> null
- disable_api_termination = false -> null
- ebs_optimized = false -> null
- get_password_data = false -> null
- hibernation = false -> null
- id = "i-08daab717c124dcbb" -> null
- instance_initiated_shutdown_behavior = "stop" -> null
- instance_state = "running" -> null
- instance_type = "t2.micro" -> null
- ipv6_address_count = 0 -> null
- ipv6_addresses = [] -> null
- monitoring = false -> null
- primary_network_interface_id = "eni-00406cb8eca92afd1" -> null
- private_dns = "ip-172-31-42-81.ap-southeast-1.compute.internal" -> null
- private_ip = "172.31.42.81" -> null
- public_dns = "ec2-13-229-211-190.ap-southeast-1.compute.amazonaws.com" -> null
- public_ip = "13.229.211.190" -> null
- secondary_private_ips = [] -> null
- security_groups = [
- "default",
] -> null
- source_dest_check = true -> null
- subnet_id = "subnet-b663b7fe" -> null
- tags = {
- "Name" = "EC2-Demo"
} -> null
- tags_all = {
- "Name" = "EC2-Demo"
} -> null
- tenancy = "default" -> null
- vpc_security_group_ids = [
- "sg-f80d3db1",
] -> null- capacity_reservation_specification {
- capacity_reservation_preference = "open" -> null
}- credit_specification {
- cpu_credits = "standard" -> null
}- enclave_options {
- enabled = false -> null
}- metadata_options {
- http_endpoint = "enabled" -> null
- http_put_response_hop_limit = 1 -> null
- http_tokens = "optional" -> null
}- root_block_device {
- delete_on_termination = true -> null
- device_name = "/dev/xvda" -> null
- encrypted = false -> null
- iops = 100 -> null
- tags = {} -> null
- throughput = 0 -> null
- volume_id = "vol-0e4f926dc18284d63" -> null
- volume_size = 8 -> null
- volume_type = "gp2" -> null
}
}Plan: 0 to add, 0 to change, 1 to destroy.
aws_instance.ec2_demo: Destroying... [id=i-08daab717c124dcbb]
aws_instance.ec2_demo: Still destroying... [id=i-08daab717c124dcbb, 10s elapsed]
aws_instance.ec2_demo: Still destroying... [id=i-08daab717c124dcbb, 20s elapsed]
aws_instance.ec2_demo: Still destroying... [id=i-08daab717c124dcbb, 30s elapsed]
aws_instance.ec2_demo: Destruction complete after 31sDestroy complete! Resources: 1 destroyed.
หลังจากใช้ terraform destroy มันก็จะมีการอัพเดท terraform.tfstate อีกรอบถูกมั้ยครับ? ทีนี้เมื่อเปิด show versions บน S3 จะเห็นว่ามีไฟล์ทั้งหมด 2 เวอร์ชั่น
- ไฟล์ปัจจุบันเป็น state ล่าสุด (หลังจาก terraform destroy)
- ไฟล์ก่อนหน้าจะเป็น state ตอนใช้ terraform apply
ซึ่งตรงนี้แหละเราสามารถใช้ความสามารถของ S3 ในการ rollback ไฟล์ กรณีที่ไฟล์ terraform.tfstate เกิดเสียหายขึ้นมาได้
ถ้าคิดว่าบทความนี้มีประโยชน์ ฝากกด clap, follow และ share บทความนี้ให้ผมด้วยนะครับ ขอบคุณมากครับ ^_^