Terraform 安装和环境准备

安装 Terraform

macOS

使用 Homebrew(推荐)

# 安装 Terraform
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# 验证安装
terraform version
# Terraform v1.6.6

手动安装

# 下载
wget https://releases.hashicorp.com/terraform/1.6.6/terraform_1.6.6_darwin_amd64.zip

# 解压
unzip terraform_1.6.6_darwin_amd64.zip

# 移动到系统路径
sudo mv terraform /usr/local/bin/

# 验证
terraform version

Linux

Ubuntu/Debian

# 添加 HashiCorp GPG 密钥
wget -O- https://apt.releases.hashicorp.com/gpg | \
    gpg --dearmor | \
    sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg

# 添加 HashiCorp 仓库
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

# 更新并安装
sudo apt update
sudo apt install terraform

# 验证
terraform version

CentOS/RHEL

# 添加 HashiCorp 仓库
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo \
    https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo

# 安装
sudo yum install terraform

# 验证
terraform version

手动安装(适用于所有 Linux 发行版)

# 下载(替换为最新版本)
wget https://releases.hashicorp.com/terraform/1.6.6/terraform_1.6.6_linux_amd64.zip

# 解压
unzip terraform_1.6.6_linux_amd64.zip

# 移动到系统路径
sudo mv terraform /usr/local/bin/

# 验证
terraform version

Windows

使用 Chocolatey(推荐)

# 安装 Chocolatey(如果未安装)
# 以管理员身份运行 PowerShell

# 安装 Terraform
choco install terraform

# 验证
terraform version

手动安装

  1. 下载:https://www.terraform.io/downloads
  2. 解压到目录,如 C:\terraform
  3. 添加到系统 PATH 环境变量
  4. 打开新的命令提示符,运行 terraform version

配置自动补全

提升命令行使用体验:

Bash

terraform -install-autocomplete
source ~/.bashrc

Zsh

terraform -install-autocomplete
source ~/.zshrc

Fish

terraform -install-autocomplete

配置编辑器

Visual Studio Code

安装 Terraform 扩展:

# 安装 HashiCorp Terraform 扩展
code --install-extension hashicorp.terraform

推荐设置 .vscode/settings.json

{
  "terraform.languageServer": {
    "enabled": true,
    "args": []
  },
  "terraform.experimentalFeatures": {
    "validateOnSave": true,
    "prefillRequiredFields": true
  },
  "[terraform]": {
    "editor.defaultFormatter": "hashicorp.terraform",
    "editor.formatOnSave": true,
    "editor.formatOnSaveMode": "file"
  },
  "[terraform-vars]": {
    "editor.defaultFormatter": "hashicorp.terraform",
    "editor.formatOnSave": true,
    "editor.formatOnSaveMode": "file"
  }
}

IntelliJ IDEA / PyCharm

安装 Terraform 插件:

  1. FileSettingsPlugins
  2. 搜索 "Terraform and HCL"
  3. 安装并重启

Vim

安装 terraform.vim:

# 使用 Vim-Plug
Plug 'hashivim/vim-terraform'

# 在 .vimrc 中添加
let g:terraform_fmt_on_save=1
let g:terraform_align=1

云平台认证配置

AWS

方式 1:环境变量

export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_DEFAULT_REGION="us-east-1"

方式 2:AWS CLI 配置

# 安装 AWS CLI
brew install awscli  # macOS
# 或
pip install awscli   # Python

# 配置凭证
aws configure
# AWS Access Key ID [None]: your-access-key
# AWS Secret Access Key [None]: your-secret-key
# Default region name [None]: us-east-1
# Default output format [None]: json

方式 3:在 Terraform 中指定

provider "aws" {
  region     = "us-east-1"
  access_key = "your-access-key"
  secret_key = "your-secret-key"
}

⚠️ 不推荐在代码中硬编码凭证,使用环境变量或 AWS CLI 配置。

Azure

安装 Azure CLI

# macOS
brew install azure-cli

# Linux
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

# Windows
# 下载安装包: https://aka.ms/installazurecliwindows

登录

az login

在 Terraform 中配置

provider "azurerm" {
  features {}
  
  subscription_id = "your-subscription-id"
  tenant_id       = "your-tenant-id"
}

Google Cloud Platform

安装 gcloud CLI

# macOS
brew install --cask google-cloud-sdk

# Linux
curl https://sdk.cloud.google.com | bash
exec -l $SHELL

# 初始化
gcloud init

认证

gcloud auth application-default login

在 Terraform 中配置

provider "google" {
  project = "your-project-id"
  region  = "us-central1"
  zone    = "us-central1-a"
}

阿里云

安装 Aliyun CLI

# 下载
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz

# 解压
tar xzvf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/

# 配置
aliyun configure

在 Terraform 中配置

provider "alicloud" {
  access_key = "your-access-key"
  secret_key = "your-secret-key"
  region     = "cn-beijing"
}

创建第一个项目

项目结构

my-terraform-project/
├── main.tf           # 主配置文件
├── variables.tf      # 变量定义
├── outputs.tf        # 输出定义
├── terraform.tfvars  # 变量值(不要提交到 Git)
└── .gitignore        # Git 忽略文件

创建项目

# 创建目录
mkdir my-terraform-project
cd my-terraform-project

# 创建 .gitignore
cat > .gitignore <<EOF
# Terraform files
.terraform/
*.tfstate
*.tfstate.backup
*.tfvars
.terraform.lock.hcl

# Crash log files
crash.log

# IDE
.vscode/
.idea/
*.swp
*.swo
EOF

创建 main.tf

terraform {
  required_version = ">= 1.0"
  
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

创建 variables.tf

variable "aws_region" {
  description = "AWS region"
  type        = string
  default     = "us-east-1"
}

创建 outputs.tf

output "region" {
  description = "AWS region"
  value       = var.aws_region
}

初始化项目

terraform init

输出:

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

Terraform has been successfully initialized!

常用命令速查

# 初始化项目
terraform init

# 验证配置语法
terraform validate

# 格式化代码
terraform fmt

# 查看执行计划
terraform plan

# 应用变更
terraform apply

# 显示当前状态
terraform show

# 列出资源
terraform state list

# 销毁所有资源
terraform destroy

# 查看输出
terraform output

# 刷新状态
terraform refresh

# 导入现有资源
terraform import <resource_type>.<resource_name> <resource_id>

环境变量

常用的 Terraform 环境变量:

# 日志级别(TRACE, DEBUG, INFO, WARN, ERROR)
export TF_LOG=DEBUG

# 日志输出文件
export TF_LOG_PATH=./terraform.log

# 数据目录
export TF_DATA_DIR=./.terraform

# 输入禁用(用于 CI/CD)
export TF_INPUT=false

# CLI 配置文件
export TF_CLI_CONFIG_FILE=~/.terraformrc

# 变量文件
export TF_VAR_instance_type=t2.large

版本管理(tfenv)

使用 tfenv 管理多个 Terraform 版本:

安装 tfenv

# macOS
brew install tfenv

# Linux
git clone https://github.com/tfutils/tfenv.git ~/.tfenv
echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

使用 tfenv

# 列出可安装版本
tfenv list-remote

# 安装特定版本
tfenv install 1.6.6

# 设置全局版本
tfenv use 1.6.6

# 列出已安装版本
tfenv list

# 安装最新版本
tfenv install latest

# 项目级版本锁定(创建 .terraform-version 文件)
echo "1.6.6" > .terraform-version

故障排查

常见问题

1. Provider 下载失败

# 使用镜像
export TF_REGISTRY_MIRROR=https://terraform-mirror.example.com

# 或编辑 ~/.terraformrc
provider_installation {
  network_mirror {
    url = "https://terraform-mirror.example.com/"
  }
}

2. 权限错误

# 检查云平台凭证
aws sts get-caller-identity  # AWS
az account show              # Azure
gcloud auth list             # GCP

3. 状态文件锁定

# 强制解锁(谨慎使用)
terraform force-unlock <lock-id>

4. 版本不兼容

# 升级 Provider 版本
terraform init -upgrade

最佳实践

1. 使用版本控制

terraform {
  required_version = ">= 1.6.0"
  
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"  # 允许 5.x 的补丁版本
    }
  }
}

2. 分离敏感信息

# 使用 terraform.tfvars(不提交到 Git)
aws_access_key = "xxx"
aws_secret_key = "xxx"

# 或使用环境变量
export TF_VAR_aws_access_key="xxx"
export TF_VAR_aws_secret_key="xxx"

3. 使用远程状态(团队协作)

terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "prod/terraform.tfstate"
    region = "us-east-1"
  }
}

总结

环境准备清单:

  • ✅ 安装 Terraform
  • ✅ 配置编辑器(VS Code + 扩展)
  • ✅ 设置云平台认证
  • ✅ 创建项目结构
  • ✅ 配置 Git 忽略文件
  • ✅ 初始化第一个项目
  • ✅ 了解常用命令

现在你已经准备好开始学习 Terraform 了!


下一章HCL 语法基础