Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Terraform/Init] Starting to learn Terraform easily.

Posted on March 24, 2022April 24, 2022 By nim No Comments on [Terraform/Init] Starting to learn Terraform easily.

Contents

Toggle
  • 1) Install terraform.
  • 2) Practise the basic example.
    • 2.1) Terraform init, plan, apply
    • 2.2) Terraform – local_file arguments
    • 2.3) Terraform – Multiple Resources
    • 2.4) Random Provider
      • 2.4.1) random_integer
      • 2.4.2) random_string
    • 2.5) Variables
      • 2.5.1) Introduction to Variables
      • 2.5.2) Types of variables
        • 2.5.2.1) Variable block
      • 2.5.3) Using Variables
        • 2.5.3.1) Interactive Mode
        • 2.5.3.2) Command Line Flag
        • 2.5.3.3) Environment Variable.
        • 2.5.3.4) Variable Definition Files
        • 2.5.3.5) Which Variable will load first
    • 2.6) Multiple Providers
    • 2.7) Dependency
      • 2.7.1) Implicit Dependency (calling is Resource Attributes)
      • 2.7.2) Explicit Dependency
    • 2.8) Output Block
    • 2.9) Lifecycle Rules
    • 2.10) Provider Version
    • 2.11) Data Source – Read File
    • 2.12) Resource Attributes

1) Install terraform.

Đầu tiên chúng ta cần download terraform.
https://www.terraform.io/downloads

Mình download và chạy trên window.
thực hiện giải nén và bạn sẽ có 1 thư muc
Đố các bác mình đang chạy máy j

Bước tiếp theo là bạn đi vào thư mục giải nén và gõ ./terraform là sẽ ok rồi nhé!

Hoặc nếu bạn cần thận có thể add thêm Environment Windows để gõ ở chỗ nào cũng được

Bạn phải khởi động lại mấy để có thể ăn config ở trên nhé

2) Practise the basic example.

2.1) Terraform init, plan, apply

Giờ làm 1 bài lab đơn giản với terraform là tạo 1 file

resource local_file sample_res {
  content = "Nimtechnology Love Terraform"
  filename = "sample.txt"
}

Giờ bạn làm như ảnh. KO cần giải thích nhiều

terraform init
Bước đầu tiên khi bạn muốn chạy 1 file .tf
terraform plan
show các step chạy ntn
terraform apply
cái này là chạy thật oi đó

GIờ tạo file như ý

2.2) Terraform – local_file arguments

Giờ làm sao biết 1 resource là local_file
thì nó có những arguments nào?

Giờ chúng ta lên google.
Ok he

Giờ chúng ta thử argument là sensitive_content

resource local_file sample_res {
  filename = "sample.txt"
  sensitive_content = "Sensitive -  Nimtechnology Love Terraform"
}

sensitive_content: thì nó sẽ không print value ra màn hình console:

khi các bạn apply các bạn sẽ thấy

2.3) Terraform – Multiple Resources

Ngoài ra bạn có thể khai báo multiple Resource

từ 1 file main.tf ta chạy 2 resource và nó tạo ra 2 file.

2.4) Random Provider

Bước đâu tiên là google

Random Provider

The “random” provider allows the use of randomness within Terraform configurations.
This is a logical provider, which means that it works entirely within Terraform’s logic, and doesn’t
interact with any other services.

2.4.1) random_integer

resource random_integer rint {
  min = 1
  max = 50000
}

Tiếp đến là bạn CD vào folder chưa file main.tf

terraform init
terraform plan
terraform apply
khi bạn này sẽ nhận về 1 id có số random
Nếu bạn chạy apply lại thì thấy ko có j sảy ra cả
Nếu vậy bạn cần change min or max thì apply ở lần tiếp theo sẽ có sử thay đổi.

Giờ mình sử dụng thêm output

resource random_integer rint {
  min = 1
  max = 100
}

output name {
  value       = random_integer.rint.id
}

2.4.2) random_string

Bạn sẽ đọc thêm ở link này:
https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/string

resource random_string rstring {
  length = 15
}

output name {
  value       = random_string.rstring.result
}

2.5) Variables

2.5.1) Introduction to Variables

Đầu tiên chúng ta có 1 file variables variables.tf

variable filename1 {
  type        = string
  default     = "sample1.txt"
}

variable content1 {
  type        = string
  default     = "Nimtechnology is loving Terraform"
}

Tiếp đến là file main.tf

resource local_file sample_res {
  filename = var.filename1
  content = var.content1
}
Nó sẽ liên kết như trên ảnh
terraform init
terraform plan
terraform apply

Ok vậy là chúng ta có thể tạo ra 1 file có tên là variables.tf
Xong rồi chúng ta add các variable mà chúng ta muốn
xong bên file main.tf thì chúng ta gọi qua.

Trên này là simle và understand easily
chúng ta tham khảo link này thêm
https://www.terraform.io/language/values/variables

2.5.2) Types of variables

string — “cat”

number — 234, 6.5

bool – true/false

list — sequence of value

list(string) =>[“red”, “green”, ‘blue”]

Mô tả cách sử dụng list

Tuple – Group non homogeneous data type

tuple([string, number, bool]) => [“dog”, 23, true

2 hình bên dưới là khai báo sai

map — like key value : Dictionary

{name = “Ankit”, age = 32}

set — only unique values

Bên left là good
Bên phải sẽ lỗi vì set thì ko cho phép Duplicate.

object — complex data tye

2.5.2.1) Variable block
Ta thấy mỗi variable đền có 3 thành phần
default: data của variable đó>
type là liểu dữ liệu
description: là mô tả của bạn về variable đó
Cái ảnh mà mình để chữ wrong
bạn value type của nó là string.
Nếu bạn định nghĩ type là number sẽ bị lỗi

2.5.3) Using Variables

Bạn có thể thao khảo chi tiết ở đây:
https://www.terraform.io/language/values/variables

2.5.3.1) Interactive Mode

Như mình đã chỉ ở phần trên
Introduction to Variables

Bạn sẽ tạo 1 file variables.tf
sau đó để sử dụng các argument trong file thì bạn gọi var.xxx
2.5.3.2) Command Line Flag

Bạn sẽ khai báo các variables ngày trong command line để sử dụng:

terraform apply -var="image_id=ami-abc123"
terraform apply -var='image_id_list=["ami-abc123","ami-def456"]' -var="instance_type=t2.micro"
terraform apply -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def456"}'
2.5.3.3) Environment Variable.
export TF_VAR_image_id=ami-abc123
terraform plan
...

Nếu bạn muốn sử dụng trong file main.tf là

resource local_file sample_res {
  filename = var.filename1
}

thì Environment phải là:
export TF_VAR_filename1=ami-abc123

2.5.3.4) Variable Definition Files

Vậy nó sẽ có thử tự load và ghi đè

2.5.3.5) Which Variable will load first
  1. export TF_VAR_filename=sample.txt
  2. terraform.tfvars file
  3. variable.auto.tfvars file
  4. terraform apply -var “filename=sample.txt”

2.6) Multiple Providers

Bạn có thể sử dụng nhiều provider trong 1 file main.tf

resource local_file name {
  content = "This is HCL"
  filename = "sample.txt"
}

resource random_string name {
  length  = 10
}

Các bạn tự run nhé!
mình lười quá

2.7) Dependency

2.7.1) Implicit Dependency (calling is Resource Attributes)

resource local_file name1 {
  filename = "explicit.txt"
  content = "This is random String from RP : ${random_string.name2.id}"
}

resource random_string name2 {
  length  = 10
}

sau khi chạy

Tạo ra 1 file lấy kết quả random_string đửa vào làm variable cho local_file
Cuối cùng là ghi vào file

2.7.2) Explicit Dependency

Ở phần này để rõ ràng Dependency thì chúng ta sài depends_on

resource local_file name1 {
  filename = "explicit.txt"
  content = "This is random String from RP : ${random_string.name2.id}"
  depends_on =  [random_string.name2]
}

resource random_string name2 {
  length  = 10
}

Cái này bạn có thể hiểu đơn giản là resource name1 sẽ cần giá trị từ resource name2
Vậy resource name2(first run) -> resource name1(second run)

2.8) Output Block

data local_file foo {
  filename = "sample1.txt"
}

output name1 {
  value       = data.local_file.foo.content
}

Giờ chúng ta đọc content của file sample1.txt
rồi output ra screen

Output ngoài việc để chúng ta nhìn thì chúng ta con để đưa các variable trang ansible hoặc shell

2.9) Lifecycle Rules

resource random_integer name {
  min = 20
  max = 350

    lifecycle{
        #create_before_destroy = true
        #prevent_destroy = true
        ignore_changes = [min, max]
    }
}

Bạn có thể chạy thử từng case nhé

2.10) Provider Version

Mặc định các mục ở trên khi màn bạn chạy init thì terraform sẽ lấy các latest packages.
Giờ bạn múa chỉ định version cho package thì như thế nào

terraform {
  required_providers {
    random = {
      source = "hashicorp/random"
      version = "2.3.1"
    }
  }
}

provider "random" {
  # Configuration options
}

2.11) Data Source – Read File

data local_file foo {
  filename = "sample1.txt"
}

output name1 {
  value       = data.local_file.foo.content
}

Cái này thì Y chang múc output

2.12) Resource Attributes

Terraform

Post navigation

Previous Post: [Spinnaker] Spin CLI
Next Post: [Harbor] Install Private Docker Hub on Ubuntu

More Related Articles

[Terraform] – Terraform Beginner – Lesson 7: Terraform Modules AWS - Amazon Web Service
[Terraform] Lesson 7: Cloud BigQuery with Terraform GCP - Google Cloud
[Terraform] Lesson 8: Cloud PubSub with Terraform GCP - Google Cloud
[Terraform] How to create or public a module terraform on the public registry Terraform
[Terraform/GCP] Registering a Google Cloud Account is Free! GCP - Google Cloud
[Terraform] Online Lab Terraform (FREE). Terraform

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.