Terraform状态管理Skill terraform-state

这个技能用于管理和维护Terraform状态文件、远程后端以及状态锁定机制,确保基础设施资源的一致性和协调性。它支持最佳实践如加密、备份和分离状态,防止并发修改。关键词:Terraform、状态管理、远程后端、状态锁定、基础设施即代码、DevOps、云计算、自动化。

DevOps 0 次安装 0 次浏览 更新于 3/25/2026

名称: terraform-state 用户可调用: false 描述: 用于管理Terraform状态文件、远程后端和状态锁定,以实现基础设施协调。 允许的工具: []

Terraform 状态

管理Terraform状态文件和远程后端。

状态基础

Terraform 状态跟踪资源映射和元数据。

本地状态

# Default location
terraform.tfstate
terraform.tfstate.backup

远程状态

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

状态命令

# List resources
terraform state list

# Show resource
terraform state show aws_instance.web

# Move resource
terraform state mv aws_instance.web aws_instance.app

# Remove resource
terraform state rm aws_instance.old

# Pull state
terraform state pull > terraform.tfstate

# Push state
terraform state push terraform.tfstate

# Replace provider
terraform state replace-provider hashicorp/aws registry.terraform.io/hashicorp/aws

远程后端

S3 后端

terraform {
  backend "s3" {
    bucket         = "terraform-state-bucket"
    key            = "path/to/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-state-lock"
    
    # Optional: state locking
    kms_key_id     = "arn:aws:kms:us-east-1:123456789:key/..."
  }
}

Terraform Cloud

terraform {
  cloud {
    organization = "my-org"
    
    workspaces {
      name = "my-workspace"
    }
  }
}

Azure 后端

terraform {
  backend "azurerm" {
    resource_group_name  = "terraform-rg"
    storage_account_name = "tfstate"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

状态锁定

防止并发修改:

# S3 + DynamoDB locking
terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
  }
}

导入资源

# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0

# Import with module
terraform import module.vpc.aws_vpc.main vpc-12345678

工作空间

# List workspaces
terraform workspace list

# Create workspace
terraform workspace new staging

# Switch workspace
terraform workspace select production

# Delete workspace
terraform workspace delete staging

最佳实践

启用状态锁定

始终使用状态锁定来防止并发修改。

加密状态

backend "s3" {
  encrypt = true
  kms_key_id = "arn:aws:kms:..."
}

分离状态文件

为不同环境使用不同的状态文件:

states/
├── prod/terraform.tfstate
├── staging/terraform.tfstate
└── dev/terraform.tfstate

备份状态

# Backup before dangerous operations
cp terraform.tfstate terraform.tfstate.backup.$(date +%Y%m%d_%H%M%S)

切勿手动编辑状态

始终使用 terraform state 命令。