环境安装与配置
本章将指导你如何安装 Terraform 并配置访问云平台的凭证,为编写第一个基础设施配置做好准备。
安装 Terraform
macOS 安装
使用 Homebrew 安装(推荐):
# 安装 Terraform
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
# 验证安装
terraform -version
Linux 安装
使用官方仓库安装(Ubuntu/Debian):
# 安装依赖
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
# 添加 HashiCorp GPG 密钥
wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null
# 添加官方仓库
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
sudo tee /etc/apt/sources.list.d/hashicorp.list
# 安装 Terraform
sudo apt-get update
sudo apt-get install terraform
# 验证安装
terraform -version
使用官方仓库安装(CentOS/RHEL/Fedora):
# 添加仓库
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
# 安装 Terraform
sudo yum install terraform
# 验证安装
terraform -version
Windows 安装
使用 Chocolatey 安装:
# 安装 Terraform
choco install terraform
# 验证安装
terraform -version
或使用 Scoop 安装:
# 安装 Scoop(如果尚未安装)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression
# 安装 Terraform
scoop install terraform
# 验证安装
terraform -version
手动安装
从 Terraform 官方下载页面 下载适合你系统的二进制文件,解压后将可执行文件添加到系统 PATH 中。
配置云提供商凭证
Terraform 需要访问云平台的凭证才能创建和管理资源。以下是主流云平台的凭证配置方法。
AWS 凭证配置
Terraform 支持多种方式配置 AWS 凭证,按优先级排序:
方式一:环境变量(推荐用于 CI/CD)
export AWS_ACCESS_KEY_ID="your-access-key-id"
export AWS_SECRET_ACCESS_KEY="your-secret-access-key"
export AWS_REGION="us-east-1"
方式二:AWS 凭证文件(推荐用于本地开发)
# 编辑 ~/.aws/credentials 文件
[default]
aws_access_key_id = your-access-key-id
aws_secret_access_key = your-secret-access-key
# 编辑 ~/.aws/config 文件
[default]
region = us-east-1
output = json
方式三:在 Terraform 配置中指定(不推荐用于生产)
provider "aws" {
region = "us-east-1"
access_key = "your-access-key-id"
secret_key = "your-secret-access-key"
}
安全提示:永远不要在代码中硬编码凭证,也不要将凭证文件提交到版本控制。
阿里云凭证配置
环境变量方式
export ALICLOUD_ACCESS_KEY="your-access-key-id"
export ALICLOUD_SECRET_KEY="your-access-key-secret"
export ALICLOUD_REGION="cn-hangzhou"
凭证文件方式
# 编辑 ~/.aliyun/config.json
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "your-access-key-id",
"access_key_secret": "your-access-key-secret",
"region_id": "cn-hangzhou"
}
]
}
Azure 凭证配置
使用 Azure CLI 登录
# 安装 Azure CLI 后登录
az login
# 设置默认订阅
az account set --subscription "your-subscription-id"
使用服务主体
export ARM_CLIENT_ID="your-client-id"
export ARM_CLIENT_SECRET="your-client-secret"
export ARM_SUBSCRIPTION_ID="your-subscription-id"
export ARM_TENANT_ID="your-tenant-id"
Google Cloud Platform 凭证配置
# 使用 gcloud CLI 登录
gcloud auth application-default login
# 或设置服务账户密钥环境变量
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"
初始化 Terraform 项目
安装完成并配置好凭证后,让我们创建一个简单的 Terraform 项目。
步骤 1:创建项目目录
mkdir terraform-demo
cd terraform-demo
步骤 2:创建主配置文件
创建 main.tf 文件:
# 配置 AWS 提供商
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
# 创建一个 S3 存储桶
resource "aws_s3_bucket" "example" {
bucket = "my-terraform-demo-bucket-12345"
tags = {
Name = "My bucket"
Environment = "Demo"
}
}
步骤 3:初始化项目
terraform init
这个命令会:
- 下载并安装配置中指定的 Provider 插件
- 初始化后端存储(默认是本地)
- 创建
.terraform目录存放插件
输出示例:
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 5.0"...
- Installing hashicorp/aws v5.31.0...
- Installed hashicorp/aws v5.31.0 (signed by HashiCorp)
Terraform has been successfully initialized!
步骤 4:验证配置
terraform validate
这个命令会检查配置文件的语法是否正确。
步骤 5:预览变更
terraform plan
这个命令会显示 Terraform 将要执行的操作,但不会实际创建资源。
输出示例:
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:
# aws_s3_bucket.example will be created
+ resource "aws_s3_bucket" "example" {
+ acceleration_status = (known after apply)
+ acl = (known after apply)
+ arn = (known after apply)
+ bucket = "my-terraform-demo-bucket-12345"
+ bucket_domain_name = (known after apply)
+ bucket_regional_domain_name = (known after apply)
+ force_destroy = false
+ hosted_zone_id = (known after apply)
+ id = (known after apply)
+ region = (known after apply)
+ request_payer = (known after apply)
+ tags = {
+ "Environment" = "Demo"
+ "Name" = "My bucket"
}
+ tags_all = {
+ "Environment" = "Demo"
+ "Name" = "My bucket"
}
+ website_domain = (known after apply)
+ website_endpoint = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
步骤 6:应用配置
terraform apply
Terraform 会再次显示执行计划,并询问是否确认执行。输入 yes 后,Terraform 将开始创建资源。
步骤 7:销毁资源(可选)
测试完成后,可以使用以下命令销毁创建的资源:
terraform destroy
常用命令速览
| 命令 | 说明 |
|---|---|
terraform init | 初始化工作目录,下载 Provider 插件 |
terraform validate | 验证配置文件的语法 |
terraform plan | 预览将要执行的变更 |
terraform apply | 应用配置,创建或更新资源 |
terraform destroy | 销毁所有管理的资源 |
terraform show | 显示当前状态或计划详情 |
terraform state list | 列出所有管理的资源 |
terraform output | 显示输出变量的值 |
terraform fmt | 格式化配置文件 |
terraform version | 显示 Terraform 版本 |
项目结构建议
一个典型的 Terraform 项目结构如下:
terraform-project/
├── main.tf # 主配置文件,定义资源和数据源
├── variables.tf # 变量定义
├── outputs.tf # 输出定义
├── providers.tf # 提供商配置
├── terraform.tfvars # 变量值(不提交到版本控制)
├── modules/ # 本地模块目录
│ └── vpc/
├── environments/ # 多环境配置
│ ├── dev/
│ └── prod/
└── .gitignore # 忽略 terraform 状态文件
.gitignore 文件内容:
# 本地 Terraform 状态文件
*.tfstate
*.tfstate.*
# 崩溃日志
crash.log
crash.*.log
# 敏感变量文件
*.tfvars
*.tfvars.json
# 覆盖文件
override.tf
override.tf.json
*_override.tf
*_override.tf.json
# CLI 配置文件
.terraformrc
terraform.rc
# 插件目录
.terraform/
下一步
环境配置完成后,我们将深入学习 Terraform 基础语法,了解 HCL 语言的详细用法。