Terraform 安装与配置 #

安装概述 #

Terraform 是一个独立的二进制文件,安装非常简单。它支持所有主流操作系统,包括 macOS、Linux 和 Windows。

text
┌─────────────────────────────────────────────────────────────┐
│                    安装方式                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 官方二进制包    → 手动下载安装                          │
│  2. 包管理器       → Homebrew / apt / yum / choco          │
│  3. tfenv         → Terraform 版本管理器                   │
│  4. Docker        → 容器化运行                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

macOS 安装 #

方法一:Homebrew(推荐) #

bash
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

brew upgrade hashicorp/tap/terraform

方法二:手动安装 #

bash
cd /tmp

wget https://releases.hashicorp.com/terraform/1.6.6/terraform_1.6.6_darwin_arm64.zip

unzip terraform_1.6.6_darwin_arm64.zip

sudo mv terraform /usr/local/bin/

rm terraform_1.6.6_darwin_arm64.zip

方法三:tfenv(版本管理) #

bash
brew install tfenv

tfenv install 1.6.6

tfenv use 1.6.6

tfenv list

Linux 安装 #

Ubuntu/Debian #

bash
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg

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

CentOS/RHEL/Fedora #

bash
sudo yum install -y yum-utils

sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo

sudo yum -y install terraform

手动安装(通用) #

bash
cd /tmp

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/

chmod +x /usr/local/bin/terraform

rm terraform_1.6.6_linux_amd64.zip

Windows 安装 #

方法一:Chocolatey #

powershell
choco install terraform

方法二:手动安装 #

powershell
# 1. 下载 ZIP 文件
# 访问 https://www.terraform.io/downloads
# 下载 Windows amd64 版本

# 2. 解压到目标目录
Expand-Archive terraform_1.6.6_windows_amd64.zip -DestinationPath C:\terraform

# 3. 添加到 PATH
$env:Path += ";C:\terraform"

# 或永久添加
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\terraform", "User")

方法三:Scoop #

powershell
scoop install terraform

Docker 运行 #

bash
docker run --rm -it \
  -v $(pwd):/workspace \
  -w /workspace \
  hashicorp/terraform:1.6.6 \
  init
dockerfile
FROM hashicorp/terraform:1.6.6

WORKDIR /infra

COPY . .

RUN terraform init

CMD ["terraform", "plan"]

验证安装 #

检查版本 #

bash
terraform version

输出示例:

text
Terraform v1.6.6
on darwin_arm64
+ provider registry.terraform.io/hashicorp/aws v5.31.0

检查安装路径 #

bash
which terraform

启用 Shell 自动补全 #

bash
terraform -install-autocomplete

对于 zsh:

bash
echo 'autoload -Uz compinit && compinit' >> ~/.zshrc
terraform -install-autocomplete
source ~/.zshrc

对于 bash:

bash
echo 'complete -C /usr/local/bin/terraform terraform' >> ~/.bashrc
source ~/.bashrc

CLI 基础命令 #

核心命令 #

text
┌─────────────────────────────────────────────────────────────┐
│                    Terraform 核心命令                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  terraform init      初始化工作目录                         │
│  terraform plan      生成执行计划                           │
│  terraform apply     执行变更                               │
│  terraform destroy   销毁资源                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

辅助命令 #

text
┌─────────────────────────────────────────────────────────────┐
│                    辅助命令                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  terraform validate   验证配置语法                          │
│  terraform fmt        格式化代码                            │
│  terraform show       查看状态                              │
│  terraform state      状态管理                              │
│  terraform output     查看输出                              │
│  terraform graph      生成依赖图                            │
│  terraform providers  查看 Provider 信息                    │
│  terraform version    查看版本                              │
│  terraform workspace  工作空间管理                          │
│  terraform import     导入已有资源                          │
│  terraform taint      标记资源为需重建                      │
│  terraform untaint    取消标记                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

命令详解 #

terraform init #

bash
terraform init

terraform init -upgrade

terraform init -backend=false

terraform init -reconfigure

terraform plan #

bash
terraform plan

terraform plan -out=tfplan

terraform plan -var="region=us-east-1"

terraform plan -var-file="prod.tfvars"

terraform plan -target=aws_instance.example

terraform plan -destroy

terraform apply #

bash
terraform apply

terraform apply tfplan

terraform apply -auto-approve

terraform apply -var="instance_type=t2.micro"

terraform apply -target=aws_instance.example

terraform destroy #

bash
terraform destroy

terraform destroy -auto-approve

terraform destroy -target=aws_instance.example

terraform fmt #

bash
terraform fmt

terraform fmt -recursive

terraform fmt -check

terraform fmt -diff

terraform validate #

bash
terraform validate

terraform validate -json

terraform show #

bash
terraform show

terraform show tfplan

terraform show -json tfplan

terraform output #

bash
terraform output

terraform output instance_ip

terraform output -json

terraform graph #

bash
terraform graph

terraform graph -type=plan

terraform graph | dot -Tpng > graph.png

环境变量配置 #

常用环境变量 #

bash
export TF_VAR_region="us-east-1"

export TF_VAR_instance_type="t2.micro"

export TF_CLI_ARGS="-no-color"

export TF_LOG=INFO

export TF_LOG_PATH="./terraform.log"

export TF_INPUT=0

export TF_DATA_DIR="./.terraform"

Provider 认证环境变量 #

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

export ARM_SUBSCRIPTION_ID="subscription-id"
export ARM_CLIENT_ID="client-id"
export ARM_CLIENT_SECRET="client-secret"
export ARM_TENANT_ID="tenant-id"

export GOOGLE_CREDENTIALS='{"type":"service_account",...}'
export GOOGLE_PROJECT="my-project"
export GOOGLE_REGION="us-central1"

配置文件 #

bash
export TF_CLI_CONFIG_FILE="$HOME/.terraformrc"
text
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"

disable_checkpoint = true

provider_installation {
  filesystem_mirror {
    path    = "/usr/share/terraform/providers"
    include = ["*/*/*"]
  }
  direct {
    exclude = ["hashicorp/*/*"]
  }
}

开发环境推荐 #

VS Code 扩展 #

text
┌─────────────────────────────────────────────────────────────┐
│                    推荐扩展                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  HashiCorp Terraform                                        │
│  ├── 语法高亮                                               │
│  ├── 代码补全                                               │
│  ├── 格式化                                                 │
│  └── 错误提示                                               │
│                                                             │
│  Terraform Doc Snippets                                     │
│  └── 文档片段快速插入                                       │
│                                                             │
│  Terraform Info                                             │
│  └── 显示资源信息                                           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

settings.json 配置 #

json
{
  "terraform.languageServer": {
    "enabled": true,
    "args": []
  },
  "terraform.format": {
    "enable": true
  },
  "terraform.lint": {
    "enable": true
  },
  "[terraform]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "hashicorp.terraform"
  }
}

.editorconfig #

text
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.tf]
indent_size = 2

[*.json]
indent_size = 2

.gitignore #

text
.terraform/
.terraform.lock.hcl
*.tfstate
*.tfstate.*
*.tfvars
*.tfplan
crash.log
override.tf
override.tf.json
*_override.tf
*_override.tf.json
.terraformrc
terraform.rc

版本管理 #

使用 tfenv #

bash
tfenv install 1.6.6

tfenv install latest

tfenv use 1.6.6

tfenv list

tfenv list-remote

tfenv uninstall 1.5.0

版本约束 #

在配置中指定版本:

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

故障排除 #

常见问题 #

text
┌─────────────────────────────────────────────────────────────┐
│                    常见问题                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. terraform: command not found                            │
│     → 检查 PATH 环境变量                                    │
│     → 确认安装路径正确                                      │
│                                                             │
│  2. Plugin cache directory doesn't exist                    │
│     → 创建缓存目录                                          │
│     → mkdir -p ~/.terraform.d/plugin-cache                  │
│                                                             │
│  3. Provider authentication failed                           │
│     → 检查云服务凭证                                        │
│     → 确认环境变量设置正确                                  │
│                                                             │
│  4. State locked                                             │
│     → 等待其他操作完成                                      │
│     → terraform force-unlock                                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

调试模式 #

bash
TF_LOG=DEBUG terraform plan

TF_LOG=TRACE terraform apply

TF_LOG=JSON terraform plan

重置环境 #

bash
rm -rf .terraform
rm -rf .terraform.lock.hcl
terraform init

下一步 #

安装完成后,接下来学习 HCL 语法基础,了解 Terraform 配置语言的基本语法!

最后更新:2026-03-29