使用 Terraform 移动块来重构资源

  • Introduction: Terraform introduced the moved block in version 1.1.0 to refactor resources by mapping old to new addresses, reducing state loss and import management risks.
  • What Is the Terraform Moved Block?: Used within a module's moved section to declare resource or data source migration, preserving state and handling renaming/movement across modules. Syntax: moved { from = "<old_address>", to = "<new_address>" }.
  • When to use the Terraform Moved Block?: Useful for renaming resources, reorganizing modules, refactoring module names, changing resource block types, and splitting/consolidating configurations.
  • How to Use the Terraform Moved Block:

    • Example 1: Renaming a Resource: Declare the old and new resource names in separate configurations and use the moved block to map them.
    • Example 2: Moving Resources Between Modules: Update the resource location in the new configuration and use the moved block to reflect the change.
    • Example 3: Using Moved With for_each: Map resources with for_each loops using multiple moved blocks.
    • Example 4: Moving a Resource With a Changed Identifier: Map old and new identifiers using moved blocks when the for_each key expression changes.
    • Example 5: Moving a Resource Between Providers: Ensure the resource is associated with the new provider using the moved block.
  • Terraform Moved Block Limitations: Requires manual specification, is only for resource renaming/moving, is static with no conditional logic, is only applied during plan and apply, requires state compatibility, and is only supported in Terraform 1.1+.
  • Key Points: The moved block is a useful tool for resource restructuring, ensuring seamless state updates and maintaining operational stability.
阅读 8
0 条评论