全球要聞:基于阿里云的 Terraform 入門(mén)實(shí)戰(zhàn)

2023-01-16 11:22:38 來(lái)源:51CTO博客

介紹

Terraform 是一種部署技術(shù),任何想要通過(guò)??基礎(chǔ)設(shè)施即代碼(Infrastructure as Code, IaC)???的方式來(lái)管理基礎(chǔ)設(shè)施的人,都可以使用這種技術(shù)。在這里??基礎(chǔ)設(shè)施???主要是指的是基于??云的基礎(chǔ)設(shè)施???,不過(guò)從技術(shù)上來(lái)說(shuō),只要是能夠通過(guò)??應(yīng)用程序接口???進(jìn)行控制的東西都是可以算基礎(chǔ)設(shè)施。??基礎(chǔ)設(shè)施即代碼???是通過(guò)定義配置代碼來(lái)進(jìn)行配置及管理基礎(chǔ)設(shè)施的過(guò)程。通過(guò)使用??IaC??

Terraform 管理基礎(chǔ)設(shè)施的配置代碼,是 HashiCorp 自研的一種配置語(yǔ)言,稱之為 HashiCorp Configuration Language,簡(jiǎn)稱為 HCL。因此我們也需要學(xué)習(xí)這種配置語(yǔ)言,便于我們編寫(xiě)配置代碼進(jìn)行管理基礎(chǔ)設(shè)施。

同時(shí) HCL 與 JSON 是完全兼容的,這也意味著 HCL 能夠直接轉(zhuǎn)換為 JSON 格式,反之亦然。對(duì) JSON 的兼容,也使得與 Terraform 之外的系統(tǒng)進(jìn)行交互操作或者動(dòng)態(tài)生成配置代碼就變的非常簡(jiǎn)單了。


(資料圖片)

Terraform 還有一個(gè)非常不錯(cuò)的好處就是云無(wú)關(guān)。云無(wú)關(guān)指的是能夠使用一組相同的工具和工作流,無(wú)縫運(yùn)行在任何云平臺(tái)上。也就是說(shuō),使用 Terraform 把基礎(chǔ)設(shè)施部署到??阿里云???與??騰訊云???或者??AWS??

云無(wú)關(guān),在現(xiàn)在這種云廠商林立的情況下是非常重要的,因?yàn)檫@意味著你不必局限于一種云廠商,也不需要為了每次更換云廠商而去學(xué)習(xí)新的管理工具或者技術(shù)。

Terraform 是通過(guò)??provider(提供程序)???與不同的云集成。??provider???是 Terraform 的插件機(jī)制。通過(guò)實(shí)現(xiàn)??provider???來(lái)與云廠商 API 進(jìn)行交互。每個(gè)云廠商都會(huì)維護(hù)自己的??provider???,使??provider????provider???是使用 Go 語(yǔ)言編寫(xiě)的,它會(huì)以二進(jìn)制文件的方式,注冊(cè)到 Terraform 上,當(dāng)我們需要用到的時(shí)候,Terraform 會(huì)將其保存到指定的目錄中進(jìn)行調(diào)用。同時(shí)它也是負(fù)責(zé)進(jìn)行廠商的身份驗(yàn)證、發(fā)出 API 請(qǐng)求等操作的。當(dāng)然你也可以自己實(shí)現(xiàn)一個(gè)??provider??,后續(xù)的有機(jī)會(huì)的話,會(huì)介紹下如何實(shí)現(xiàn)。

Terraform 的表達(dá)能力也是非常強(qiáng)的,它的配置語(yǔ)言也是支持條件語(yǔ)句、for 表達(dá)式、指令、模板文件等等,通過(guò)這些可以輕松的使我們實(shí)現(xiàn)更為復(fù)雜的場(chǎng)景。

Hello Terraform

接下來(lái),以一個(gè)實(shí)戰(zhàn)來(lái)演示一下 Terraform 的使用。

使用 Terraform 代替我們的手動(dòng)操作,進(jìn)行身份驗(yàn)證及 API 調(diào)用,在阿里云上創(chuàng)建一個(gè) ECS 的實(shí)例。并且演示一下如何使用 Terraform 刪除 ECS 實(shí)例。

Terraform 創(chuàng)建阿里云 ECS 實(shí)例的步驟:

編寫(xiě) Terraform 的配置代碼。初始化 Terraform 項(xiàng)目目錄,并安裝阿里云的??provider??。查看并創(chuàng)建 Terraform 的變更計(jì)劃。(非必須)執(zhí)行創(chuàng)建 ECS 實(shí)例的計(jì)劃。清除 ECS 實(shí)例。

編寫(xiě)配置代碼

下面我們來(lái)創(chuàng)建一個(gè)名叫??main.tf???阿里云??provider???相關(guān)文檔地址:???https://registry.terraform.io/providers/aliyun/alicloud/latest/docs??

.tf 為拓展名的文件,表示它是 Terraform 的配置代碼文件。

Terraform 在運(yùn)行的時(shí)候,會(huì)讀取工作目錄下的所有??.tf??

terraform {  required_providers {    alicloud = {      source  = "aliyun/alicloud"    }  }}# 定義云廠商provider "alicloud" {  region     = "cn-shanghai"  access_key = "LTAIxxxxxxxxxxxxxxxxx"  secret_key = "hmbkxxxxxxxxxxxxxxxxxxxxxxxxx"}# 創(chuàng)建vpcresource "alicloud_vpc" "vpc" {  vpc_name   = "vpc_1"  cidr_block = "10.0.0.0/16"}# 創(chuàng)建vswitch# alicloud_vswitch是阿里云的資源字段,vsw_1字段是tf文件中的自定義唯一資源名稱,vswitch_name字段是在阿里云上的自定義備注名resource "alicloud_vswitch" "vsw_1" {  vswitch_name = "vsw_aliyun1"  vpc_id       = alicloud_vpc.vpc.id  cidr_block   = "10.0.0.0/24"  zone_id      = "cn-shanghai-b"}# 新建安全組resource "alicloud_security_group" "nsg1" {  name   = "lanyulei_aliyun_nsg1"  vpc_id = alicloud_vpc.vpc.id}# 將 nsg_rule1 加入安全組 lanyulei_aliyun_nsg1 中resource "alicloud_security_group_rule" "nsg_rule1" {  type              = "ingress"  ip_protocol       = "tcp"  nic_type          = "intranet"  policy            = "accept"  port_range        = "1/65535"  priority          = 1  security_group_id = alicloud_security_group.nsg1.id  cidr_ip           = "0.0.0.0/0"}# 創(chuàng)建ECS實(shí)例resource "alicloud_instance" "instance" {  # cn-shanghai  availability_zone          = "cn-shanghai-b"  security_groups            = ["${alicloud_security_group.nsg1.id}"]  instance_type              = "ecs.n1.small"  system_disk_category       = "cloud_ssd"  image_id                   = "centos_7_9_x64_20G_alibase_20220824.vhd"  instance_name              = "lanyulei-ecs"  vswitch_id                 = alicloud_vswitch.vsw_1.id  internet_max_bandwidth_out = 1  password                   = "4aI5wjyPGUlj"}

初始化工作目錄

執(zhí)行??terraform init???命令,安裝阿里云的??provider??

?  demo $ terraform initInitializing the backend...Initializing provider plugins...- Finding latest version of aliyun/alicloud...- Installing aliyun/alicloud v1.196.0...- Installed aliyun/alicloud v1.196.0 (signed by a HashiCorp partner, key ID 47422B4AA9FA381B)Partner and community providers are signed by their developers.If you"d like to know more about provider signing, you can read about it here:https://www.terraform.io/docs/cli/plugins/signing.htmlTerraform has made some changes to the provider dependency selections recordedin the .terraform.lock.hcl file. Review those changes and commit them to yourversion control system if they represent changes you intended to make.Terraform has been successfully initialized!You may now begin working with Terraform. Try running "terraform plan" to seeany changes that are required for your infrastructure. All Terraform commandsshould 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, othercommands will detect it and remind you to do so if necessary.

查看 Terraform 的變更計(jì)劃

執(zhí)行??terraform plan??

綠色的 +:新增。紅色的 -:刪除。黃色的 ~:變更。
?  demo $ terraform planTerraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:  + createTerraform will perform the following actions:  # alicloud_instance.instance will be created  + resource "alicloud_instance" "instance" {      + availability_zone                  = "cn-shanghai-b"      + credit_specification               = (known after apply)      + deletion_protection                = false      + deployment_set_group_no            = (known after apply)      + dry_run                            = false      + host_name                          = (known after apply)      + http_endpoint                      = (known after apply)      + http_put_response_hop_limit        = (known after apply)      + http_tokens                        = (known after apply)      + id                                 = (known after apply)      + image_id                           = "centos_7_9_x64_20G_alibase_20220824.vhd"      + instance_charge_type               = "PostPaid"      + instance_name                      = "lanyulei-ecs"      + instance_type                      = "ecs.n1.small"      + internet_charge_type               = "PayByTraffic"      + internet_max_bandwidth_in          = (known after apply)      + internet_max_bandwidth_out         = 1      + ipv6_address_count                 = (known after apply)      + ipv6_addresses                     = (known after apply)      + key_name                           = (known after apply)      + maintenance_action                 = (known after apply)      + password                           = (sensitive value)      + private_ip                         = (known after apply)      + public_ip                          = (known after apply)      + role_name                          = (known after apply)      + secondary_private_ip_address_count = (known after apply)      + secondary_private_ips              = (known after apply)      + security_groups                    = (known after apply)      + spot_duration                      = (known after apply)      + spot_strategy                      = "NoSpot"      + status                             = (known after apply)      + stopped_mode                       = (known after apply)      + subnet_id                          = (known after apply)      + system_disk_category               = "cloud_ssd"      + system_disk_performance_level      = (known after apply)      + system_disk_size                   = 40      + volume_tags                        = (known after apply)      + vswitch_id                         = (known after apply)    }  # alicloud_security_group.nsg1 will be created  + resource "alicloud_security_group" "nsg1" {      + id                  = (known after apply)      + inner_access        = (known after apply)      + inner_access_policy = (known after apply)      + name                = "lanyulei_aliyun_nsg1"      + security_group_type = "normal"      + vpc_id              = (known after apply)    }  # alicloud_security_group_rule.nsg_rule1 will be created  + resource "alicloud_security_group_rule" "nsg_rule1" {      + cidr_ip           = "0.0.0.0/0"      + id                = (known after apply)      + ip_protocol       = "tcp"      + nic_type          = "intranet"      + policy            = "accept"      + port_range        = "1/65535"      + prefix_list_id    = (known after apply)      + priority          = 1      + security_group_id = (known after apply)      + type              = "ingress"    }  # alicloud_vpc.vpc will be created  + resource "alicloud_vpc" "vpc" {      + cidr_block            = "10.0.0.0/16"      + id                    = (known after apply)      + ipv6_cidr_block       = (known after apply)      + name                  = (known after apply)      + resource_group_id     = (known after apply)      + route_table_id        = (known after apply)      + router_id             = (known after apply)      + router_table_id       = (known after apply)      + secondary_cidr_blocks = (known after apply)      + status                = (known after apply)      + vpc_name              = "vpc_1"    }  # alicloud_vswitch.vsw_1 will be created  + resource "alicloud_vswitch" "vsw_1" {      + availability_zone = (known after apply)      + cidr_block        = "10.0.0.0/24"      + id                = (known after apply)      + name              = (known after apply)      + status            = (known after apply)      + vpc_id            = (known after apply)      + vswitch_name      = "vsw_aliyun1"      + zone_id           = "cn-shanghai-b"    }Plan: 5 to add, 0 to change, 0 to destroy.────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────Note: You didn"t use the -out option to save this plan, so Terraform can"t guarantee to take exactly these actions if you run "terraform apply" now.

執(zhí)行變更計(jì)劃

執(zhí)行??terraform apply -auto-approve??,開(kāi)始創(chuàng)建 ECS 實(shí)例。

?  demo $ 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:  # alicloud_instance.instance will be created  + resource "alicloud_instance" "instance" {      + availability_zone                  = "cn-shanghai-b"      + credit_specification               = (known after apply)      + deletion_protection                = false      + deployment_set_group_no            = (known after apply)      + dry_run                            = false      + host_name                          = (known after apply)      + http_endpoint                      = (known after apply)      + http_put_response_hop_limit        = (known after apply)      + http_tokens                        = (known after apply)      + id                                 = (known after apply)      + image_id                           = "centos_7_9_x64_20G_alibase_20220824.vhd"      + instance_charge_type               = "PostPaid"      + instance_name                      = "lanyulei-ecs"      + instance_type                      = "ecs.n1.small"      + internet_charge_type               = "PayByTraffic"      + internet_max_bandwidth_in          = (known after apply)      + internet_max_bandwidth_out         = 1      + ipv6_address_count                 = (known after apply)      + ipv6_addresses                     = (known after apply)      + key_name                           = (known after apply)      + maintenance_action                 = (known after apply)      + password                           = (sensitive value)      + private_ip                         = (known after apply)      + public_ip                          = (known after apply)      + role_name                          = (known after apply)      + secondary_private_ip_address_count = (known after apply)      + secondary_private_ips              = (known after apply)      + security_groups                    = (known after apply)      + spot_duration                      = (known after apply)      + spot_strategy                      = "NoSpot"      + status                             = (known after apply)      + stopped_mode                       = (known after apply)      + subnet_id                          = (known after apply)      + system_disk_category               = "cloud_ssd"      + system_disk_performance_level      = (known after apply)      + system_disk_size                   = 40      + volume_tags                        = (known after apply)      + vswitch_id                         = (known after apply)    }  # alicloud_security_group.nsg1 will be created  + resource "alicloud_security_group" "nsg1" {      + id                  = (known after apply)      + inner_access        = (known after apply)      + inner_access_policy = (known after apply)      + name                = "lanyulei_aliyun_nsg1"      + security_group_type = "normal"      + vpc_id              = (known after apply)    }  # alicloud_security_group_rule.nsg_rule1 will be created  + resource "alicloud_security_group_rule" "nsg_rule1" {      + cidr_ip           = "0.0.0.0/0"      + id                = (known after apply)      + ip_protocol       = "tcp"      + nic_type          = "intranet"      + policy            = "accept"      + port_range        = "1/65535"      + prefix_list_id    = (known after apply)      + priority          = 1      + security_group_id = (known after apply)      + type              = "ingress"    }  # alicloud_vpc.vpc will be created  + resource "alicloud_vpc" "vpc" {      + cidr_block            = "10.0.0.0/16"      + id                    = (known after apply)      + ipv6_cidr_block       = (known after apply)      + name                  = (known after apply)      + resource_group_id     = (known after apply)      + route_table_id        = (known after apply)      + router_id             = (known after apply)      + router_table_id       = (known after apply)      + secondary_cidr_blocks = (known after apply)      + status                = (known after apply)      + vpc_name              = "vpc_1"    }  # alicloud_vswitch.vsw_1 will be created  + resource "alicloud_vswitch" "vsw_1" {      + availability_zone = (known after apply)      + cidr_block        = "10.0.0.0/24"      + id                = (known after apply)      + name              = (known after apply)      + status            = (known after apply)      + vpc_id            = (known after apply)      + vswitch_name      = "vsw_aliyun1"      + zone_id           = "cn-shanghai-b"    }Plan: 5 to add, 0 to change, 0 to destroy.alicloud_vpc.vpc: Creating...alicloud_vpc.vpc: Creation complete after 6s [id=vpc-uf6lprsrz6c1cshob79kc]alicloud_security_group.nsg1: Creating...alicloud_vswitch.vsw_1: Creating...alicloud_security_group.nsg1: Creation complete after 1s [id=sg-uf642pxnc6msqptaoctg]alicloud_security_group_rule.nsg_rule1: Creating...alicloud_security_group_rule.nsg_rule1: Creation complete after 0s [id=sg-uf642pxnc6msqptaoctg:ingress:tcp:1/65535:intranet:0.0.0.0/0:accept:1]alicloud_vswitch.vsw_1: Creation complete after 6s [id=vsw-uf6un6zempw6yvrpb9xmz]alicloud_instance.instance: Creating...alicloud_instance.instance: Still creating... [10s elapsed]alicloud_instance.instance: Creation complete after 12s [id=i-uf672vd7e0esv7i4lvjr]Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

銷(xiāo)毀資源實(shí)例

執(zhí)行??terraform destroy -auto-approve??,銷(xiāo)毀資源實(shí)例。

?  demo $ terraform destroy -auto-approvealicloud_vpc.vpc: Refreshing state... [id=vpc-uf6lprsrz6c1cshob79kc]alicloud_security_group.nsg1: Refreshing state... [id=sg-uf642pxnc6msqptaoctg]alicloud_vswitch.vsw_1: Refreshing state... [id=vsw-uf6un6zempw6yvrpb9xmz]alicloud_security_group_rule.nsg_rule1: Refreshing state... [id=sg-uf642pxnc6msqptaoctg:ingress:tcp:1/65535:intranet:0.0.0.0/0:accept:1]alicloud_instance.instance: Refreshing state... [id=i-uf672vd7e0esv7i4lvjr]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:  # alicloud_instance.instance will be destroyed  - resource "alicloud_instance" "instance" {      - availability_zone                  = "cn-shanghai-b" -> null      - deletion_protection                = false -> null      - dry_run                            = false -> null      - host_name                          = "iZuf672vd7e0esv7i4lvjrZ" -> null      - http_put_response_hop_limit        = 0 -> null      - id                                 = "i-uf672vd7e0esv7i4lvjr" -> null      - image_id                           = "centos_7_9_x64_20G_alibase_20220824.vhd" -> null      - instance_charge_type               = "PostPaid" -> null      - instance_name                      = "lanyulei-ecs" -> null      - instance_type                      = "ecs.n1.small" -> null      - internet_charge_type               = "PayByTraffic" -> null      - internet_max_bandwidth_in          = -1 -> null      - internet_max_bandwidth_out         = 1 -> null      - ipv6_address_count                 = 0 -> null      - ipv6_addresses                     = [] -> null      - maintenance_action                 = "AutoRecover" -> null      - maintenance_notify                 = false -> null      - password                           = (sensitive value)      - private_ip                         = "10.0.0.102" -> null      - public_ip                          = "139.224.239.237" -> null      - secondary_private_ip_address_count = 0 -> null      - secondary_private_ips              = [] -> null      - security_groups                    = [          - "sg-uf642pxnc6msqptaoctg",        ] -> null      - spot_duration                      = 0 -> null      - spot_price_limit                   = 0 -> null      - spot_strategy                      = "NoSpot" -> null      - status                             = "Running" -> null      - stopped_mode                       = "Not-applicable" -> null      - subnet_id                          = "vsw-uf6un6zempw6yvrpb9xmz" -> null      - system_disk_category               = "cloud_ssd" -> null      - system_disk_encrypted              = false -> null      - system_disk_size                   = 40 -> null      - tags                               = {} -> null      - volume_tags                        = {} -> null      - vswitch_id                         = "vsw-uf6un6zempw6yvrpb9xmz" -> null    }  # alicloud_security_group.nsg1 will be destroyed  - resource "alicloud_security_group" "nsg1" {      - id                  = "sg-uf642pxnc6msqptaoctg" -> null      - inner_access        = true -> null      - inner_access_policy = "Accept" -> null      - name                = "lanyulei_aliyun_nsg1" -> null      - security_group_type = "normal" -> null      - tags                = {} -> null      - vpc_id              = "vpc-uf6lprsrz6c1cshob79kc" -> null    }  # alicloud_security_group_rule.nsg_rule1 will be destroyed  - resource "alicloud_security_group_rule" "nsg_rule1" {      - cidr_ip           = "0.0.0.0/0" -> null      - id                = "sg-uf642pxnc6msqptaoctg:ingress:tcp:1/65535:intranet:0.0.0.0/0:accept:1" -> null      - ip_protocol       = "tcp" -> null      - nic_type          = "intranet" -> null      - policy            = "accept" -> null      - port_range        = "1/65535" -> null      - priority          = 1 -> null      - security_group_id = "sg-uf642pxnc6msqptaoctg" -> null      - type              = "ingress" -> null    }  # alicloud_vpc.vpc will be destroyed  - resource "alicloud_vpc" "vpc" {      - cidr_block            = "10.0.0.0/16" -> null      - id                    = "vpc-uf6lprsrz6c1cshob79kc" -> null      - name                  = "vpc_1" -> null      - resource_group_id     = "rg-acfm2ogvfexgrly" -> null      - route_table_id        = "vtb-uf6pyfkc87awmxaa4do32" -> null      - router_id             = "vrt-uf69bn1f7xp89m3xfk1f1" -> null      - router_table_id       = "vtb-uf6pyfkc87awmxaa4do32" -> null      - secondary_cidr_blocks = [] -> null      - status                = "Available" -> null      - user_cidrs            = [] -> null      - vpc_name              = "vpc_1" -> null    }  # alicloud_vswitch.vsw_1 will be destroyed  - resource "alicloud_vswitch" "vsw_1" {      - availability_zone = "cn-shanghai-b" -> null      - cidr_block        = "10.0.0.0/24" -> null      - id                = "vsw-uf6un6zempw6yvrpb9xmz" -> null      - name              = "vsw_aliyun1" -> null      - status            = "Available" -> null      - tags              = {} -> null      - vpc_id            = "vpc-uf6lprsrz6c1cshob79kc" -> null      - vswitch_name      = "vsw_aliyun1" -> null      - zone_id           = "cn-shanghai-b" -> null    }Plan: 0 to add, 0 to change, 5 to destroy.alicloud_security_group_rule.nsg_rule1: Destroying... [id=sg-uf642pxnc6msqptaoctg:ingress:tcp:1/65535:intranet:0.0.0.0/0:accept:1]alicloud_instance.instance: Destroying... [id=i-uf672vd7e0esv7i4lvjr]alicloud_security_group_rule.nsg_rule1: Destruction complete after 0salicloud_instance.instance: Still destroying... [id=i-uf672vd7e0esv7i4lvjr, 10s elapsed]alicloud_instance.instance: Destruction complete after 11salicloud_security_group.nsg1: Destroying... [id=sg-uf642pxnc6msqptaoctg]alicloud_vswitch.vsw_1: Destroying... [id=vsw-uf6un6zempw6yvrpb9xmz]alicloud_vswitch.vsw_1: Still destroying... [id=vsw-uf6un6zempw6yvrpb9xmz, 10s elapsed]alicloud_security_group.nsg1: Still destroying... [id=sg-uf642pxnc6msqptaoctg, 10s elapsed]alicloud_security_group.nsg1: Destruction complete after 16salicloud_vswitch.vsw_1: Still destroying... [id=vsw-uf6un6zempw6yvrpb9xmz, 20s elapsed]alicloud_vswitch.vsw_1: Destruction complete after 23salicloud_vpc.vpc: Destroying... [id=vpc-uf6lprsrz6c1cshob79kc]alicloud_vpc.vpc: Destruction complete after 5sDestroy complete! Resources: 5 destroyed.

本文結(jié)束。

標(biāo)簽: 基礎(chǔ)設(shè)施 身份驗(yàn)證 應(yīng)用程序接口

上一篇:前沿?zé)狳c(diǎn):Nginx與LUA(3)
下一篇:世界焦點(diǎn)!Python爬蟲(chóng)-第四章-1-多線程多進(jìn)程并發(fā)爬取Ⅱ