Skip to content

1. Terraform CLI

bash
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform -help
Usage: terraform [global options] <subcommand> [args]

The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.

Main commands:
  init          Prepare your working directory for other commands
  validate      Check whether the configuration is valid
  plan          Show changes required by the current configuration
  apply         Create or update infrastructure
  destroy       Destroy previously-created infrastructure

All other commands:
  console       Try Terraform expressions at an interactive command prompt
  fmt           Reformat your configuration in the standard style
  force-unlock  Release a stuck lock on the current workspace
  get           Install or upgrade remote Terraform modules
  graph         Generate a Graphviz graph of the steps in an operation
  import        Associate existing infrastructure with a Terraform resource
  login         Obtain and save credentials for a remote host
  logout        Remove locally-stored credentials for a remote host
  metadata      Metadata related commands
  modules       Show all declared modules in a working directory
  output        Show output values from your root module
  providers     Show the providers required for this configuration
  refresh       Update the state to match remote systems
  show          Show the current state or a saved plan
  state         Advanced state management
  taint         Mark a resource instance as not fully functional
  test          Execute integration tests for Terraform modules
  untaint       Remove the 'tainted' state from a resource instance
  version       Show the current Terraform version
  workspace     Workspace management

Global options (use these before the subcommand, if any):
  -chdir=DIR    Switch to a different working directory before executing the
                given subcommand.
  -help         Show this help output, or the help for a specified subcommand.
  -version      An alias for the "version" subcommand.
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform -help
Usage: terraform [global options] <subcommand> [args]

The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.

Main commands:
  init          Prepare your working directory for other commands
  validate      Check whether the configuration is valid
  plan          Show changes required by the current configuration
  apply         Create or update infrastructure
  destroy       Destroy previously-created infrastructure

All other commands:
  console       Try Terraform expressions at an interactive command prompt
  fmt           Reformat your configuration in the standard style
  force-unlock  Release a stuck lock on the current workspace
  get           Install or upgrade remote Terraform modules
  graph         Generate a Graphviz graph of the steps in an operation
  import        Associate existing infrastructure with a Terraform resource
  login         Obtain and save credentials for a remote host
  logout        Remove locally-stored credentials for a remote host
  metadata      Metadata related commands
  modules       Show all declared modules in a working directory
  output        Show output values from your root module
  providers     Show the providers required for this configuration
  refresh       Update the state to match remote systems
  show          Show the current state or a saved plan
  state         Advanced state management
  taint         Mark a resource instance as not fully functional
  test          Execute integration tests for Terraform modules
  untaint       Remove the 'tainted' state from a resource instance
  version       Show the current Terraform version
  workspace     Workspace management

Global options (use these before the subcommand, if any):
  -chdir=DIR    Switch to a different working directory before executing the
                given subcommand.
  -help         Show this help output, or the help for a specified subcommand.
  -version      An alias for the "version" subcommand.

1.1 基本命令

init✅

terraform init:初始化一个包含Terraform代码的工作目录。

bash
 $Hsuin: D:/Terraform_project/tf_aliyun  ls -al
total 28
drwxr-xr-x 1 Hsuin 197609     0 Jul  9 14:49 .
drwxr-xr-x 1 Hsuin 197609     0 Jul  8 17:39 ..
drwxr-xr-x 1 Hsuin 197609     0 Jul  9 14:26 .terraform
-rw-r--r-- 1 Hsuin 197609  1083 Jul  9 14:26 .terraform.lock.hcl
-rw-r--r-- 1 Hsuin 197609  1856 Jul  9 14:45 main.tf
 $Hsuin: D:/Terraform_project/tf_aliyun  ls -al
total 28
drwxr-xr-x 1 Hsuin 197609     0 Jul  9 14:49 .
drwxr-xr-x 1 Hsuin 197609     0 Jul  8 17:39 ..
drwxr-xr-x 1 Hsuin 197609     0 Jul  9 14:26 .terraform
-rw-r--r-- 1 Hsuin 197609  1083 Jul  9 14:26 .terraform.lock.hcl
-rw-r--r-- 1 Hsuin 197609  1856 Jul  9 14:45 main.tf

执行init会产生这两个文件 .terraform .terraform.lock.hcl

  • .terraform 里面内容
bash
 $Hsuin: D:/Terraform_project/tf_aliyun  tree -L 7 .terraform
.terraform
`-- providers
    `-- registry.terraform.io
        `-- hashicorp
            `-- alicloud
                `-- 1.253.0
                    `-- windows_amd64
                        `-- terraform-provider-alicloud_v1.253.0.exe
 $Hsuin: D:/Terraform_project/tf_aliyun  tree -L 7 .terraform
.terraform
`-- providers
    `-- registry.terraform.io
        `-- hashicorp
            `-- alicloud
                `-- 1.253.0
                    `-- windows_amd64
                        `-- terraform-provider-alicloud_v1.253.0.exe
bash
#升级providers,查看帮助terraform init -help
terraform init -upgrade
#升级providers,查看帮助terraform init -help
terraform init -upgrade

plan✅

terraform plan:查看并创建变更计划。

apply✅

terraform apply:生成并执行计划(重要)。

show✅

terraform show:展示(Read)当前所有归Terraform控制的资源的状态信息。

destroy✅

terraform destroy:销毁并回收所有Terraform管理的基础设施资源。

1.2 高级命令

非交互模式✅

bash
#创建
terraform apply -auto-approve

#删除
terraform destroy -auto-approve
#创建
terraform apply -auto-approve

#删除
terraform destroy -auto-approve

格式化输出代码✅

terraform fmt
terraform fmt

导入已有资源✅

不建议导入

验证语法✅

bash
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform validate
Success! The configuration is valid.
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform validate
Success! The configuration is valid.

列出当前state中的所有资源✅

bash
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform state list
alicloud_instance.instance
alicloud_security_group.nsg1
alicloud_security_group_rule.nsg_rule1
alicloud_vpc.vpc
alicloud_vswitch.vsw_1
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform state list
alicloud_instance.instance
alicloud_security_group.nsg1
alicloud_security_group_rule.nsg_rule1
alicloud_vpc.vpc
alicloud_vswitch.vsw_1

展示某一个资源的属性✅

bash
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform state show alicloud_vpc.vpc
# alicloud_vpc.vpc:
resource "alicloud_vpc" "vpc" {
    cidr_block                                  = "10.0.0.0/16"
    classic_link_enabled                        = false
    create_time                                 = "2025-07-09T08:09:59Z"
    description                                 = null
    dns_hostname_status                         = "DISABLED"
    enable_ipv6                                 = false
    id                                          = "vpc-uf6bixk1cerh0wle6lenl"
    ipv6_cidr_block                             = null
    ipv6_cidr_blocks                            = []
    name                                        = "vpc_1"
    region_id                                   = "cn-shanghai"
    resource_group_id                           = "rg-acfm2qdjwer4h7y"
    route_table_id                              = "vtb-uf6bfqpwqarlqt1zne6ib"
    router_id                                   = "vrt-uf6hmffff01b4wojxi2r6"
    router_table_id                             = "vtb-uf6bfqpwqarlqt1zne6ib"
    secondary_cidr_blocks                       = []
    status                                      = "Available"
    system_route_table_description              = null
    system_route_table_name                     = null
    system_route_table_route_propagation_enable = true
    user_cidrs                                  = []
    vpc_name                                    = "vpc_1"
}
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform state show alicloud_vpc.vpc
# alicloud_vpc.vpc:
resource "alicloud_vpc" "vpc" {
    cidr_block                                  = "10.0.0.0/16"
    classic_link_enabled                        = false
    create_time                                 = "2025-07-09T08:09:59Z"
    description                                 = null
    dns_hostname_status                         = "DISABLED"
    enable_ipv6                                 = false
    id                                          = "vpc-uf6bixk1cerh0wle6lenl"
    ipv6_cidr_block                             = null
    ipv6_cidr_blocks                            = []
    name                                        = "vpc_1"
    region_id                                   = "cn-shanghai"
    resource_group_id                           = "rg-acfm2qdjwer4h7y"
    route_table_id                              = "vtb-uf6bfqpwqarlqt1zne6ib"
    router_id                                   = "vrt-uf6hmffff01b4wojxi2r6"
    router_table_id                             = "vtb-uf6bfqpwqarlqt1zne6ib"
    secondary_cidr_blocks                       = []
    status                                      = "Available"
    system_route_table_description              = null
    system_route_table_name                     = null
    system_route_table_route_propagation_enable = true
    user_cidrs                                  = []
    vpc_name                                    = "vpc_1"
}

生成关系图✅

bash
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform graph
digraph G {
  rankdir = "RL";
  node [shape = rect, fontname = "sans-serif"];
  "alicloud_instance.instance" [label="alicloud_instance.instance"];
  "alicloud_security_group.nsg1" [label="alicloud_security_group.nsg1"];
  "alicloud_security_group_rule.nsg_rule1" [label="alicloud_security_group_rule.nsg_rule1"];
  "alicloud_vpc.vpc" [label="alicloud_vpc.vpc"];
  "alicloud_vswitch.vsw_1" [label="alicloud_vswitch.vsw_1"];
  "alicloud_instance.instance" -> "alicloud_security_group.nsg1";
  "alicloud_instance.instance" -> "alicloud_vswitch.vsw_1";
  "alicloud_security_group.nsg1" -> "alicloud_vpc.vpc";
  "alicloud_security_group_rule.nsg_rule1" -> "alicloud_security_group.nsg1";
  "alicloud_vswitch.vsw_1" -> "alicloud_vpc.vpc";
}
 $Hsuin: D:/Terraform_project/tf_aliyun  terraform graph
digraph G {
  rankdir = "RL";
  node [shape = rect, fontname = "sans-serif"];
  "alicloud_instance.instance" [label="alicloud_instance.instance"];
  "alicloud_security_group.nsg1" [label="alicloud_security_group.nsg1"];
  "alicloud_security_group_rule.nsg_rule1" [label="alicloud_security_group_rule.nsg_rule1"];
  "alicloud_vpc.vpc" [label="alicloud_vpc.vpc"];
  "alicloud_vswitch.vsw_1" [label="alicloud_vswitch.vsw_1"];
  "alicloud_instance.instance" -> "alicloud_security_group.nsg1";
  "alicloud_instance.instance" -> "alicloud_vswitch.vsw_1";
  "alicloud_security_group.nsg1" -> "alicloud_vpc.vpc";
  "alicloud_security_group_rule.nsg_rule1" -> "alicloud_security_group.nsg1";
  "alicloud_vswitch.vsw_1" -> "alicloud_vpc.vpc";
}

生成图片✅

bash
#安装图形
yum install-y graphviz

terraform graph丨dot -Tsvg > graph.svg
#安装图形
yum install-y graphviz

terraform graph丨dot -Tsvg > graph.svg

image-20250709170144910

或者,Graphviz Official Site.

terraform graph > graph.dot

#使用 Graphviz 渲染 DOT 文件
dot -Tpng graph.dot -o graph.png
terraform graph > graph.dot

#使用 Graphviz 渲染 DOT 文件
dot -Tpng graph.dot -o graph.png

箭头:依赖关系从一个资源流向另一个资源,显示创建顺序。

1.3 state命令

https://www.fdevops.com/2023/01/19/terraform-31240

1.4 分块运行

比如:

vim main.tf

yaml
module "vpc" {

source = "terraform-aws-modules/vpc/aws"
name = "myvpc"
cidr = "10.10.0.0/16"

azs              = ["cn-north-1a", "cn-north-1b"]

public_subnets   = ["10.10.0.0/24", "10.10.10.0/24"]

private_subnets  = ["10.10.1.0/24", "10.10.11.0/24"]

database_subnets = ["10.10.2.0/24", "10.10.12.0/24"]

create_database_subnet_group = true
enable_dns_hostnames         = true
enable_dns_support           = true
enable_dynamodb_endpoint     = true
enable_s3_endpoint           = true

tags = {
Owner       = "user"
Environment = "staging"
}

}
module "vpc" {

source = "terraform-aws-modules/vpc/aws"
name = "myvpc"
cidr = "10.10.0.0/16"

azs              = ["cn-north-1a", "cn-north-1b"]

public_subnets   = ["10.10.0.0/24", "10.10.10.0/24"]

private_subnets  = ["10.10.1.0/24", "10.10.11.0/24"]

database_subnets = ["10.10.2.0/24", "10.10.12.0/24"]

create_database_subnet_group = true
enable_dns_hostnames         = true
enable_dns_support           = true
enable_dynamodb_endpoint     = true
enable_s3_endpoint           = true

tags = {
Owner       = "user"
Environment = "staging"
}

}
  • 执行
bash
terraform apply -target=module.vpc ### 创建VPC及相关资源
terraform apply -target=module.vpc ### 创建VPC及相关资源

1.5 alias

bash
alias tfmt='terraform fmt -recursive'
alias tinit='terraform init -plugin-dir=${TERRAFORM_PLUGIN}'
alias tapply='terraform apply -auto-approve'
alias tdestroy='terraform destroy -auto-approve'
alias tplan='terraform plan'
alias tfmt='terraform fmt -recursive'
alias tinit='terraform init -plugin-dir=${TERRAFORM_PLUGIN}'
alias tapply='terraform apply -auto-approve'
alias tdestroy='terraform destroy -auto-approve'
alias tplan='terraform plan'

1.6 debug调试

Terraform 日志级别有 TRACEDEBUGINFOWARNERRORTRACE 包含的信息最多也最冗长,如果 TF_LOG 被设定为这五级以外的值时 Terraform 会默认使用 TRACE

特别是在遇到权限不足的时候,如果想检查是具体哪个 service 权限不足。就需要 debug 输出详细的过程

bash
export TF_LOG=DEBUG
terraform plan
export TF_LOG=DEBUG
terraform plan

追踪资源变更

bash
export TF_LOG=INFO
terraform plan 2> plan.log
export TF_LOG=INFO
terraform plan 2> plan.log

1.7 配置日志

该环境变量可以设定日志文件保存的位置。注意,如果TF_LOG_PATH被设置了,那么 TF_LOG 也必须被设置。举例来说,想要始终把日志输出到当前工作目录,可以这样:

bash
$ export TF_LOG_PATH=./terraform.log
$ export TF_LOG_PATH=./terraform.log