「Terraform」- 云平台的基础设施自动化 | 基础设施即代码工具

认识

使用 Terraform 实现任何云平台的基础设施自动化,可在任何云平台或数据中心配置和管理资源。简而言之,其为云平台的统一管理工具,但又不止如此,……

Terraform is an infrastructure as code tool that lets you build, change, and version infrastructure safely and efficiently. This includes low-level components like compute instances, storage, and networking; and high-level components like DNS entries and SaaS features.

官网:https://www.terraform.io/
文档:https://developer.hashicorp.com/terraform?product_intent=terraform
仓库:https://github.com/hashicorp/terraform

组成

Configuration Language

https://developer.hashicorp.com/terraform/language

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region  = "us-west-2"
}

resource "aws_instance" "app_server" {
  ami           = "ami-830c94e3"
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleAppServerInstance"
  }
}

terraform {}

  • source | defines an optional hostname, a namespace, and the provider type. Terraform installs providers from the Terraform Registry by default. In this example configuration, the aws provider’s source is defined as hashicorp/aws, which is shorthand for registry.terraform.io/hashicorp/aws.
  • You can also set a version constraint for each provider defined in the required_providers block. The version attribute is optional, but we recommend using it to constrain the provider version so that Terraform does not install a version of the provider that does not work with your configuration.

provider {} | The provider block configures the specified provider, in this case aws.

  • A provider is a plugin that Terraform uses to create and manage your resources.
  • You can use multiple provider blocks in your Terraform configuration to manage resources from different providers.

resource {} | Use resource blocks to define components of your infrastructure.

  • Resource blocks have two strings before the block: the resource type and the resource name. 针对 resource type 参数,其由 Provider 定义,无法随意修改。针对 resource name 参数,其为 resource type 的命令,可以根据需求进行定义任意名称。

Terraform CLI

https://developer.hashicorp.com/terraform/cli

Terraform loads all files in the current directory ending in .tf, so you can name your configuration files however you choose.

terraform init

  • Initializing a configuration directory downloads and installs the providers defined in the configuration. Terraform downloads providers and installs it in a hidden subdirectory of your current working directory, named .terraform.
  • Terraform also creates a lock file named .terraform.lock.hcl which specifies the exact provider versions used, so that you can control when you want to update the providers used for your project.

terraform plan 是 Terraform 的核心命令之一,主要用于 生成执行计划。每次修改 Terraform 配置后,必须先执行 plan 确认变更符合预期。在团队协作中,作为变更审批的依据。在 Terraform 的 plan 输出中,# forces replacement 是一个关键标记,表示该资源无法就地更新,必须先销毁旧资源,再创建新资源来应用变更。

terraform apply

  • Before it applies any changes, Terraform prints out the execution plan which describes the actions Terraform will take in order to change your infrastructure to match the configuration.
  • When the value displayed is (known after apply), it means that the value will not be known until the resource is created.
  • Terraform will now pause and wait for your approval before proceeding. If anything in the plan seems incorrect or dangerous, it is safe to abort here before Terraform modifies your infrastructure. 即输入 yes 才会执行。
  • When you applied your configuration, Terraform wrote data into a file called terraform.tfstate. Terraform stores the IDs and properties of the resources it manages in this file, so that it can update or destroy those resources going forward.

HCP Terraform

HCP Terraform builds on these features by managing Terraform runs in a consistent and reliable environment instead of on your local machine. It securely stores state and secret data, and can connect to version control systems so that you can develop your infrastructure using a workflow similar to application development. The HCP Terraform UI provides a detailed view into the resources managed by a Terraform project and gives enhanced visibility into each Terraform operation. —— 所以,大概率,我们不需要使用 HCP Terraform 服务。

Terraform Enterprise

Terraform Enterprise is HashiCorp’s self-hosted distribution of HCP Terraform. Terraform Enterprise offers a private instance of HCP Terraform application, with no resource limits and additional enterprise-grade architectural features like audit logging and SAML single sign-on.

CDK for Terraform

Cloud Development Kit for Terraform (CDKTF) allows you to use familiar programming languages to define and provision infrastructure. This gives you access to the entire Terraform ecosystem without learning HashiCorp Configuration Language (HCL) and lets you leverage the power of your existing toolchain for testing, dependency management, etc.

Plugin

Plugins are executable binaries written in Go that communicate with Terraform Core over an RPC interface.

Terraform currently supports one type of plugin called providers. Each provider plugin exposes an implementation for a specific service or tool, such as the AWS provider or the cloud-init provider.

Registry

Terraform Registry | https://registry.terraform.io/?product_intent=terraform

Discover Terraform providers that power all of Terraform’s resource types, or find modules for quickly deploying common infrastructure configurations.

The Terraform Registry is an interactive resource for discovering a wide selection of integrations (providers), configuration packages (modules), and security rules (policies) for use with Terraform. The Registry includes solutions developed by HashiCorp, third-party vendors, and our Terraform community. Our goal with the Registry is to provide plugins to manage any infrastructure API, pre-made modules to quickly configure common infrastructure components, and examples of how to write quality Terraform code.

Integration Program

The Terraform Integration Program facilitates prospect partners in creating and publishing Terraform integrations validated by HashiCorp. —— 官方希望更多的人能够加入 Terraform 生态中。

terraform.tfstate

Terraform stores information about your infrastructure in a state file. To update your infrastructure, you first modify your configuration, and then use Terraform to plan and apply the required changes. Terraform uses the data in your state file to determine the changes it needs to make to your infrastructure.

terraform state rm <resource-type>.<resource-name>

构建

—— 该部分将记录构建 Terraform 工具栈的方法,作为用户,我们更加关注于 Terraform 的使用,而非从零开始构建 Terraform 体系。

官方提供三种版本:

  • Terraform Community Edition,我们将学习和使用的版本。
  • HCP Terraform
  • Terraform Enterprise

官方提供的方法

https://developer.hashicorp.com/terraform/install

通过 asdf 安装

asdf plugin list all | grep terraform
asdf list all terraform

asdf install terraform 1.11.4
asdf global terraform 1.11.4

terraform -install-autocomplete # for bash completion

性质

Configuration Language

Customize Terraform configuration with variables | https://developer.hashicorp.com/terraform/tutorials/configuration-language/variables

Import Existing Resources | Import Terraform Configuration

应用

Terraform Use Cases | https://developer.hashicorp.com/terraform/intro/use-cases

Multi-Cloud Deployment
https://developer.hashicorp.com/terraform/tutorials/networking/multicloud-kubernetes

Application Infrastructure Deployment, Scaling, and Monitoring Tools

Self-Service Clusters

Policy Compliance and Management

PaaS Application Setup

Software Defined Networking

Kubernetes

Parallel Environments

Software Demos

管理 AWS 云服务

官方提供 AWS OCI GCP 示例,我们将学习 AWS 示例。如下内容为学习笔记,详细内容参考官方文档。

What is Infrastructure as Code with Terraform? | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/infrastructure-as-code | 该文档介绍 Terraform 基本功能、基本特性、……

Install Terraform | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli | 安装 CLI 工具,并通过 CLI 运行 Nginx 容器的基本方法、……

touch main.tf

terraform init

terraform apply

terraform destroy

Build infrastructure | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-build | 该文档介绍编写 main.tf 文件的方法、常见术语及概念、……

terraform init // Initialize the directory

terraform fmt // Format your configuration.

terraform validate // Validate your configuration.

terraform apply // Create infrastructure

terraform show // Inspect state

terraform state list // Manually Managing State

Change infrastructure | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-change | 该文档介绍修改已有基础设施的方法、相关概念、……

修改 main.tf 文件,

terraform apply // 输出的 -/+ 表示先删除后新增;输出的 ~ 表示仅更新;

Destroy infrastructure | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-destroy | 该文档介绍删除资源的方法。

terraform destroy

Define input variables | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-variables | 该文档介绍如何在 .tf 文件中使用变量,以避免硬编码问题

variable “instance_name” {} // 定义

var.instance_name // 引用

terraform apply -var “instance_name=YetAnotherName” // 通过命令行传入

Query data with outputs | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-outputs | 除了修改 Infrastructure 外,Terraform 还能从云商提取信息。

创建 outputs.tf 文件,加入 output “instance_id” {} 代码

terraform apply

terraform output

虽然 terraform show 命令能够查看信息,但是其输出内容较多,不便于查看。

Store remote state | https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-remote | 该部分内容是在介绍 HCP Terraform 工具,针对我们的场景,我们暂时不需要关注该部分的内容。

管理 Tencent Cloud 环境

TencentCloud Provider | https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/latest/docs

实现 Security Group 配置

  • Virtual Private Cloud(VPC) /