雲原生之旅 - 3)Terraform - Create and Maintain Infrastructure as Code

来源:https://www.cnblogs.com/wade-xu/archive/2022/09/21/16709133.html
-Advertisement-
Play Games

前言 工欲善其事,必先利其器。本篇文章我們介紹下 Terraform,為後續創建各種雲資源做準備,比如Kubernetes 關鍵詞:IaC, Infrastructure as Code, Terraform, 基礎架構即代碼,Terraform 例子, Terraform 入門,Terraform ...


前言

工欲善其事,必先利其器。本篇文章我們介紹下 Terraform,為後續創建各種雲資源做準備,比如Kubernetes

 

關鍵詞:IaC, Infrastructure as Code, Terraform, 基礎架構即代碼,Terraform 例子, Terraform 入門,Terraform 簡介

 

Terraform 是什麼?

Terraform 是一種安全有效地構建、更改和版本控制基礎設施的工具(基礎架構自動化的編排工具)。它的目標是 "Write, Plan, and create Infrastructure as Code", 基礎架構即代碼。Terraform 幾乎可以支持所有市面上能見到的雲服務。具體的說就是可以用代碼來管理維護 IT 資源,把之前需要手動操作的一部分任務通過程式來自動化的完成,這樣的做的結果非常明顯:高效、不易出錯。

Terraform 絕對是一個非常好用的工具,目前各大雲平臺也都支持的不錯,我很看好它的未來。Terraform 也是用 Go 語言開發的開源項目,你可以在 github 上訪問到它的源代碼以及各種文檔。

###  https://www.cnblogs.com/wade-xu/p/16709133.html ###  

安裝

我這裡強烈推薦tfenv, 下麵介紹如何在Mac上利用 tfenv 來安裝Terraform。

安裝 tfenv

brew install tfenv

brew link tfenv

利用tfenv 安裝 Terraform

# install latest version
tfenv install latest

# install specific version
tfenv install 1.2.9

列出所有版本

% tfenv list                                                                                                
  1.2.9
  1.0.0
  0.14.2
  0.13.7
* 0.13.5 (set by /usr/local/Cellar/tfenv/2.0.0/version)

* 表示當前使用的版本

切換版本 

# switch to 1.2.9
tfenv use 1.2.9

Switching default version to v1.2.9
Switching completed

卸載

tfenv uninstall 0.14.2

tfenv uninstall latest

 ###  https://www.cnblogs.com/wade-xu/p/16709133.html ###

 

Provider

我們公司主要用GCP 谷歌雲, 所以這裡也用 google 的 provider 來入門Terraform

安裝 Google Cloud SDK Install https://cloud.google.com/sdk/docs/quickstarts

Configure the environment for gcloud:

gcloud auth login

gcloud auth list

確保你的賬號有許可權操作GCP的Project

 

我的目錄結構如下

 

providers.tf

 1 terraform {
 2   required_version = ">= 1.2.9"
 3 
 4   required_providers {
 5     google = {
 6       source  = "hashicorp/google"
 7       version = "~> 4"
 8     }
 9   }
10 }
11 
12 provider "google" {
13   project = local.project.project_id
14   region  = local.project.region
15 }

backend.tf

terraform {
  backend "gcs" {
    bucket = "wadexu007"
    prefix = "demo/state"
  }
}

這裡的bucket要提前建好用來存放Terraform state文件。

 

network.tf

resource "google_compute_network" "default" {
  project                 = local.project.project_id
  name                    = local.project.network_name
  auto_create_subnetworks = true
  routing_mode            = "GLOBAL"
}

Network資源各個參數參考官方文檔

 

locals.tf

locals {
  # project details
  project = {
    project_id       = "demo-eng-cn-dev"
    region           = "asia-east2"
    network_name     = "wade-test-network"
  }
}

 ###  https://www.cnblogs.com/wade-xu/p/16709133.html ###

 

init

在此目錄下執行

terraform init

此目錄下會生成 .terraform 文件夾,init其實就安裝依賴插件到 .terraform 目錄中:

 

Plan

plan 命令會檢查配置文件並生成執行計劃,如果發現配置文件中有錯誤會報錯。

terraform plan

結果如下

 % terraform plan
Acquiring state lock. This may take a few moments...

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # google_compute_network.default will be created
  + resource "google_compute_network" "default" {
      + auto_create_subnetworks         = true
      + delete_default_routes_on_create = false
      + gateway_ipv4                    = (known after apply)
      + id                              = (known after apply)
      + internal_ipv6_range             = (known after apply)
      + mtu                             = (known after apply)
      + name                            = "wade-test-network"
      + project                         = "xperiences-eng-cn-dev"
      + routing_mode                    = "GLOBAL"
      + self_link                       = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

 

Apply

在使用 apply 命令執行實際的部署時,預設會先執行 plan 命令併進入交互模式等待用戶確認操作。

terraform apply

輸入 Yes

Tips: 可以使用 -auto-approve 選項跳過這些步驟直接執行部署操作。

terraform apply -auto-approve

 

GCS bucket 裡面的 Terraform 狀態文件  gs://wadexu007/demo/state/default.tfstate 如下

{
  "version": 4,
  "terraform_version": "1.2.9",
  "serial": 1,
  "lineage": "30210d18-6dd5-a542-5b0d-xxxxxxxx",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "google_compute_network",
      "name": "default",
      "provider": "provider[\"registry.terraform.io/hashicorp/google\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "auto_create_subnetworks": true,
            "delete_default_routes_on_create": false,
            "description": "",
            "enable_ula_internal_ipv6": false,
            "gateway_ipv4": "",
            "id": "projects/demo-eng-cn-dev/global/networks/wade-test-network",
            "internal_ipv6_range": "",
            "mtu": 0,
            "name": "wade-test-network",
            "project": "demo-eng-cn-dev",
            "routing_mode": "GLOBAL",
            "self_link": "https://www.googleapis.com/compute/v1/projects/demo-eng-cn-dev/global/networks/wade-test-network",
            "timeouts": null
          },
          "sensitive_attributes": [],
          "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2xxxxxxxxxxxxxxxxxxxxx9"
        }
      ]
    }
  ]
}

GCP控制台查看新建的資源

 

Destory

terraform destroy 

銷毀資源,務必小心

% terraform destroy 
Acquiring state lock. This may take a few moments...
google_compute_network.default: Refreshing state... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # google_compute_network.default will be destroyed
  - resource "google_compute_network" "default" {
      - auto_create_subnetworks         = true -> null
      - delete_default_routes_on_create = false -> null
      - enable_ula_internal_ipv6        = false -> null
      - id                              = "projects/demo-eng-cn-dev/global/networks/wade-test-network" -> null
      - mtu                             = 0 -> null
      - name                            = "wade-test-network" -> null
      - project                         = "demo-eng-cn-dev" -> null
      - routing_mode                    = "GLOBAL" -> null
      - self_link                       = "https://www.googleapis.com/compute/v1/projects/demo-eng-cn-dev/global/networks/wade-test-network" -> null
    }

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

google_compute_network.default: Destroying... [id=projects/xperiences-eng-cn-dev/global/networks/wade-test-network]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 10s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 20s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 30s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 40s elapsed]
google_compute_network.default: Still destroying... [id=projects/demo-eng-cn-dev/global/networks/wade-test-network, 50s elapsed]
google_compute_network.default: Destruction complete after 54s
Releasing state lock. This may take a few moments...

Destroy complete! Resources: 1 destroyed.

 

附上我的learning by doing 代碼 供參考。

 

總結

Terraform 用法很簡單,支持的雲廠商也很多,只要查看對應文檔創建你的資源就行, 上述例子僅僅入門,玩法很多,還可以module化,這樣不同的環境只需要source一下module,傳入不同的參數就行。

除了建雲資源,其它比如 Jenkins,Spinnaker, DNS,Vault 都可以用Terraform來建,所有infra 用代碼來實現,人管代碼,代碼管基礎設施,避免管理員直接控制台操作基礎設施,後面再運用上Atlantis 將Terraform 在Git上運行,所有change走PR, review之後apply change, 這也是GitOps的一種最佳實踐。

另外,Terraform 也支持開發自己的provider。


感謝閱讀,如果您覺得本文的內容對您的學習有所幫助,您可以打賞和推薦,您的鼓勵是我創作的動力。

 

Learning by Doing
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 蒼穹之邊,浩瀚之摯,眰恦之美; 悟心悟性,善始善終,惟善惟道! —— 朝槿《朝槿兮年說》 寫在開頭 在併發編程領域,有兩大核心問題:一個是互斥,即同一時刻只允許一個線程訪問共用資源;另一個是同步,即線程之間如何通信、協作。主要原因是,對於多線程實現實現併發,一直以來,多線程都存在2個問題: 線程之間 ...
  • 一、前言 Caffeine是一個高性能的 Java 緩存庫,底層數據存儲採用ConcurrentHashMap 優點:因為Caffeine面向JDK8,在jdk8中ConcurrentHashMap增加了紅黑樹,在hash衝突嚴重時也能有良好的讀性能。多線程環境中,不同的key可以併發寫,相同的ke ...
  • 簡述 類型:創建型 目標:通過拷貝快速創建相同或相似對象。 接下來我們看一個需要改進的案例。 優化案例 話不多說,先來看一個創建相同或相似對象的傳統寫法。 原版v0 public class Department { private String name; private String count ...
  • 多用戶即時通訊系統02 4.編碼實現01 4.1功能實現-用戶登錄 4.1.1功能說明 因為還沒有學習資料庫,我們人為規定 用戶名/id = 100,密碼為 123456 就可以登錄,其他用戶不能登錄,後面使用HashMap模擬資料庫,這樣就可以多個用戶登錄。 4.1.2思路分析+框架圖 用戶的登錄 ...
  • 前言 secure boot 和FIT Image是前段時間接觸到的,其實早就該總結下了,奈何懶癌犯了,拖了好久才寫出來。 之前也有人問我,工作後最大的感受是什麼?我的回答是:“快速學習”。 就嵌入式來講,大多數應屆生在校期間可能都沒做過完整的項目,僅憑在校期間學習的內容很難勝任公司的要求。 就底層 ...
  • 寫在前面 其實media配置也可以完全用static代替(看你自己的選擇),static代替的方法是直接在mobles.py里設置用戶上傳頭像的時候,修改一下用戶上傳頭像時的保存位置 當設置成static/avatar/之後,我們後期在獲取用戶上傳的文件時就可以在其前面加一個static就可以獲取到 ...
  • 註冊中心可以說是微服務架構中的”通訊錄“,它記錄了服務和服務地址的映射關係。在分散式架構中,服務會註冊到這裡,當服務需要調用其它服務時,就到這裡找到服務的地址,進行調用。 ...
  • 案例 學習網址:https://seaborn.pydata.org/examples/errorband_lineplots.html import seaborn as sns import pandas as pd sns.set_theme(style="darkgrid") # 導入數據 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...