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
    • Helm Chart
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log & Monitor
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
  • 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

  • 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] How to create or public a module terraform on the public registry Terraform
[Terraform] Lesson 10: NoSQL Database in GCP with Terraform GCP - Google Cloud
[Terraform] Lesson 2: Create GCS and upload file via terraform GCP - Google Cloud
[Terraform] Lesson 3: GCP Networking with Terraform GCP - Google Cloud
[AWS] Create EKS Cluster and EKS Node Groups in Public and Private Subnets AWS - Amazon Web Service
[Terraform] Lesson 6: Google Cloud Function with Terraform GCP - Google Cloud

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

  • [Smartctl] Instruction check the health disk of Raspberry. January 16, 2023
  • [kubectl/Argocd] How to create a kubectl config file for serviceaccount or from the cluster secret of Argocd January 12, 2023
  • [Helm/Github] Create a public Helm chart repository with GitHub Pages January 8, 2023
  • [AWS] How to increase the disk size of a Windows EC2 machine? January 4, 2023
  • [Redis] ElastiCache-Redis Cross-Region Replication|Global DataStore January 3, 2023

Archives

  • 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
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • Golang
    • Jquery & JavaScript
    • Laravel
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kubernetes
      • Ingress
    • Longhorn – Storage
    • Vault
    • VictoriaMetrics
  • Log & Monitor
    • ELK
      • Kibana
      • Logstash
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2023 NimTechnology.