### List with Custom Config Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Demonstrates how to specify a custom configuration file for the list command. ```bash tfmigrate list --config prod.hcl ``` -------------------------------- ### Install tfmigrate from Source Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Install tfmigrate from source if you have a Go development environment. This involves cloning the repository, navigating into the directory, and running 'make install'. ```bash $ git clone https://github.com/minamijoyo/tfmigrate $ cd tfmigrate/ $ make install $ tfmigrate --version ``` -------------------------------- ### Apply with Custom Config Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Demonstrates applying a migration using a custom configuration file named 'production.hcl'. ```bash tfmigrate apply --config production.hcl migration.hcl ``` -------------------------------- ### List Migrations with Custom Config Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Example of listing migrations using a specific configuration file. ```bash tfmigrate list --config .tfmigrate.prod.hcl ``` -------------------------------- ### Apply with Backend Config Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Shows how to apply a migration while specifying backend configurations for the Terraform state. ```bash tfmigrate apply \ --backend-config='bucket=terraform-state' \ --backend-config='region=ap-northeast-1' migration.hcl ``` -------------------------------- ### StateMigrator Example Usage Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Example of creating a StateMigrator with a StateMvAction. This demonstrates how to instantiate the migrator for a simple move operation. ```go action := tfmigrate.NewStateMvAction("aws_sg.old", "aws_sg.new") migrator := tfmigrate.NewStateMigrator(".", "default", []tfmigrate.StateAction{action}, option, false, false) ``` -------------------------------- ### HCL Configuration Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Example of HCL syntax for tfmigrate configuration. Shows nested blocks and inline comments for optional parameters and defaults. ```hcl tfmigrate { migration_dir = "./migrations" # string, optional, default "." is_backend_terraform_cloud = false # bool, optional, default false history { ... } # optional } ``` -------------------------------- ### Example Output for Listing Unapplied Migrations Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Shows the typical output when listing only unapplied migrations. ```text 20240120_add_resources.hcl 20240125_rename.hcl ``` -------------------------------- ### Apply Specific Migration in History Mode Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Example of applying a single, named migration file (e.g., '20240120_add_resources.hcl') while operating in history mode. ```bash tfmigrate apply 20240120_add_resources.hcl ``` -------------------------------- ### Example Output of tfmigrate list Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Illustrates the expected output format when listing migration files. ```text 20240115_init.hcl 20240120_add_resources.hcl 20240125_rename.hcl ``` -------------------------------- ### Example: Running ApplyCommand Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Demonstrates how to instantiate and run the ApplyCommand with a basic UI and a migration file argument. Ensure the UI and command are properly initialized before calling Run. ```go ui := &cli.BasicUi{Writer: os.Stdout} cmd := &command.ApplyCommand{Meta: command.Meta{UI: ui}} exitCode := cmd.Run([]string{"migration.hcl"}) ``` -------------------------------- ### Programmatic Usage Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md Demonstrates how to use tfmigrate programmatically by loading configuration, creating a runner, and executing plan or apply operations. ```go // Load configuration config, _ := config.LoadConfigurationFile(".tfmigrate.hcl") // Create runner runner, _ := command.NewFileRunner("migration.hcl", config, option) // Execute runner.Plan(ctx) // or runner.Apply(ctx) ``` -------------------------------- ### GCS Storage Example with Service Account Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/storage-and-tfexec.md Example of setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to use a service account for GCS authentication before running tfmigrate. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json tfmigrate apply migration.hcl ``` -------------------------------- ### Bash CLI Command Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Example of a tfmigrate CLI command invocation with arguments and flags. Used for documenting command-line usage. ```bash tfmigrate plan [PATH] [--config PATH] [--backend-config VALUE] [--out PATH] ``` -------------------------------- ### Error Handling: History not configured Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Example error message when the history setting is missing in the configuration. ```text no history setting ``` -------------------------------- ### Install tfmigrate with Homebrew Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Use this command to install tfmigrate if you are a macOS user with Homebrew. ```bash $ brew install tfmigrate ``` -------------------------------- ### Build and Run Sandbox Environment Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Clone the repository, build the Docker image, and start a bash session within the sandbox environment to safely experiment with tfmigrate. ```bash # git clone https://github.com/minamijoyo/tfmigrate # cd tfmigrate/ # docker compose build # docker compose run --rm tfmigrate /bin/bash ``` -------------------------------- ### State Push Failure Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Example error message indicating a failure to push the state to the remote backend. ```bash failed to push state to remote ``` -------------------------------- ### Display command-specific help Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Use the --help flag with specific commands like plan, apply, or list to get detailed help for those commands. ```bash tfmigrate plan --help ``` ```bash tfmigrate apply --help ``` ```bash tfmigrate list --help ``` -------------------------------- ### tfmigrate Local Storage Configuration Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md HCL2 configuration for tfmigrate using local filesystem storage for migration history. ```hcl tfmigrate { migration_dir = "./tfmigrate" history { storage "local" { path = "tmp/history.json" } } } ``` -------------------------------- ### Configure Local Storage Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Defines the configuration structure for local storage and provides an example of its usage in HCL. ```go type local.Config struct { Path string `hcl:"path"` } ``` ```hcl tfmigrate { history { storage "local" { path = "tmp/history.json" } } } ``` -------------------------------- ### Example Multi-State Migration Configuration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Illustrates how to configure a multi-state migration using HCL, specifying source and destination directories and the actions to perform, such as moving resources. ```hcl migration "multi_state" "split_resources" { from_dir = "monorepo" to_dir = "microservice" actions = [ "mv aws_lambda_function.api aws_lambda_function.api", "mv aws_iam_role.api_role aws_iam_role.api_role", ] } ``` -------------------------------- ### Migration File Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md Defines a state migration operation, specifying actions to be performed. Multiple migration files can be applied in sequence. ```hcl migration "state" "task_name" { actions = ["mv old new"] } ``` -------------------------------- ### History Save Failure Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Example error message when the state is applied successfully, but saving the history record fails. ```bash apply succeed, but failed to save history: error ``` -------------------------------- ### NewStateMvAction Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Creates a StateMvAction to move a resource from a source address to a destination address within the same tfstate. Use this when renaming or relocating resources. ```go action := tfmigrate.NewStateMvAction("aws_sg.old", "aws_sg.new") ``` -------------------------------- ### Migration File Example Structure Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/history-package.md Migration files are discovered by reading the migration directory, filtering for .hcl and .json files, excluding hidden files, and sorting alphabetically. Using timestamps as prefixes ensures consistent ordering. ```tree migrations/ ├── 20240115_init.hcl ├── 20240120_add_resources.hcl ├── 20240125_rename_resources.hcl └── .gitignore ``` -------------------------------- ### Migration with Force and Skip Plan Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Configure a migration to forcefully apply changes and skip the plan phase. Use with caution, as this bypasses safety checks. ```hcl migration "state" "force_migration" { dir = "." force = true skip_plan = true actions = [ "rm aws_instance.deleted", ] } ``` -------------------------------- ### State XMV Action Examples Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Shows the 'xmv' action for moving resources using wildcard pattern matching. Supports capturing groups for dynamic destination paths and merging resources. ```hcl actions = [ "xmv aws_security_group.* aws_security_group.$${1}_v2", "xmv aws_instance.temp_* aws_instance.prod_$1", ] ``` ```hcl # Rename all security groups with suffix "xmv aws_security_group.* aws_security_group.$${1}2" # Move all temp resources to prod "xmv aws_instance.temp_* aws_instance.prod_$1" # Merge resources (for multi_state) "xmv * $1" ``` -------------------------------- ### Error Handling: Storage connection failed Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Example error message indicating a failure to connect to the history storage. ```text failed to read history: connection error ``` -------------------------------- ### Multi-State Migration to Merge States with Wildcards Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md This example demonstrates merging all resources from one directory to another using a wildcard ('*') in the 'xmv' action. The '$1' placeholder captures the wildcard match. ```hcl migration "multi_state" "merge_dir1_to_dir2" { from_dir = "dir1" to_dir = "dir2" actions = [ "xmv * $1", ] } ``` -------------------------------- ### Create New HistoryRunner Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Initializes a new HistoryRunner instance. Use this to start migrations with history tracking enabled. Ensure context and configuration are provided. ```go func NewHistoryRunner(ctx context.Context, filename string, config *config.TfmigrateConfig, option *tfmigrate.MigratorOption) (*HistoryRunner, error) ``` ```go config, _ := config.LoadConfigurationFile(".tfmigrate.hcl") runner, err := command.NewHistoryRunner(context.Background(), "", config, nil) ``` -------------------------------- ### NewStateRmAction Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Creates a StateRmAction to remove resources from state at the given addresses. Use this for resources that are no longer managed or have been deleted. ```go action := tfmigrate.NewStateRmAction([]string{"aws_sg.old", "aws_instance.dead"}) ``` -------------------------------- ### Setup Terraform Working Directory Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Use this function to set up the working directory for Terraform migrations. It handles version checks, initialization, workspace switching, remote state pulling, and backend overrides for safe testing. It's common for both single and multi-state migrations. ```go func setupWorkDir(ctx context.Context, tf tfexec.TerraformCLI, workspace string, isBackendTerraformCloud bool, backendConfig []string, ignoreLegacyStateInitErr bool) (*tfexec.State, func() error, error) ``` -------------------------------- ### Configuration Options Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Documentation for configuration options includes type, required status, default value, description, valid values, HCL examples, and environment variable mappings. ```APIDOC ## Configuration Options Every configuration option is documented with: - Type and required status - Default value - Description - Valid values (for enums) - Example HCL - Environment variable mapping Example from **configuration.md**: ```hcl tfmigrate { migration_dir = "./migrations" # string, optional, default "." is_backend_terraform_cloud = false # bool, optional, default false history { ... } # optional } ``` ``` -------------------------------- ### Display tfmigrate version Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Use the --version flag to display the current tfmigrate version. This is useful for verifying installation. ```bash tfmigrate --version ``` -------------------------------- ### CLI Commands Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Documentation for CLI commands includes syntax, arguments, flags, options, exit codes, example invocations, and error handling. ```APIDOC ## CLI Commands Every command is documented with: - Syntax and arguments - All flags and options - Exit codes - Example invocations - Error handling Example from **cli-reference.md**: ```bash tfmigrate plan [PATH] [--config PATH] [--backend-config VALUE] [--out PATH] ``` ``` -------------------------------- ### NewStateImportAction Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Creates a StateImportAction to import an existing resource into the Terraform state. Provide the resource address and its existing ID. ```go action := tfmigrate.NewStateImportAction("aws_sg.imported", "sg-12345") ``` -------------------------------- ### Simple State Migration Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Define a simple state migration to rename a resource within a specified directory. This is useful for straightforward resource refactoring. ```hcl migration "state" "rename_groups" { dir = "infrastructure" actions = [ "mv aws_security_group.old aws_security_group.new", ] } ``` -------------------------------- ### Multi-State Migration Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Perform a migration that involves moving resources between different directories, effectively splitting services or refactoring the Terraform state. ```hcl migration "multi_state" "split_services" { from_dir = "monorepo" to_dir = "microservice" actions = [ "mv aws_lambda_function.api aws_lambda_function.api", "mv aws_iam_role.api aws_iam_role.api", ] } ``` -------------------------------- ### State Import Action Examples Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Demonstrates the 'import' action for adding existing infrastructure resources into the Terraform state. Requires the resource address and its corresponding ID. ```hcl actions = [ "import aws_security_group.new sg-12345", "import aws_instance.prod i-98765", ] ``` -------------------------------- ### ApplyCommand.Help Method Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Returns the help text for the apply command, providing usage and option documentation. Call this to display help information to the user. ```go func (c *ApplyCommand) Help() string ``` -------------------------------- ### Plan with Backend Configuration Options Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Provide backend configuration settings directly on the command line for the plan command. This is useful for dynamically setting backend parameters like bucket names or regions. ```bash tfmigrate plan \ --backend-config='bucket=terraform-state' \ --backend-config='region=us-east-1' \ migration.hcl ``` -------------------------------- ### Create New Controller Instance Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/history-package.md Instantiates a new Controller. Loads migration file list and history from storage. Ensure the migration directory is accessible and the storage backend is available. ```go historyConfig := &history.Config{ Storage: &local.Config{Path: "history.json"}, } controller, err := history.NewController(context.Background(), "./migrations", historyConfig) ``` -------------------------------- ### State Replace-Provider Action Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Shows the 'replace-provider' action for updating the provider associated with resources in the state. Requires the old and new full provider registry paths. ```hcl actions = [ "replace-provider registry.terraform.io/-/null registry.terraform.io/hashicorp/null", ] ``` -------------------------------- ### CLI Entry Point Structure Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md Illustrates the command structure for tfmigrate's CLI, showing how commands like 'plan', 'apply', and 'list' are handled. ```go // main.go func main() └── cli.CLI.Run() ├── plan command → PlanCommand.Run() ├── apply command → ApplyCommand.Run() └── list command → ListCommand.Run() ``` -------------------------------- ### Get All Migration File Names Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/history-package.md Retrieves all migration file names, including applied and unapplied ones, sorted alphabetically. Useful for understanding the complete migration set. ```go all := controller.Migrations() // Returns: ["001_init.hcl", "002_add_resources.hcl", "003_rename.hcl"] ``` -------------------------------- ### Help for PlanCommand Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Retrieves the help text for the PlanCommand, providing usage and option documentation. ```go func (c *PlanCommand) Help() string ``` -------------------------------- ### Programmatic Usage of tfmigrate Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/INDEX.md Demonstrates how to load configuration, create a file runner, and execute plan and apply operations programmatically. Ensure necessary imports and error handling are in place. ```go config, _ := config.LoadConfigurationFile(".tfmigrate.hcl") runner, _ := command.NewFileRunner("migration.hcl", config, option) err := runner.Plan(context.Background()) err = runner.Apply(context.Background()) ``` -------------------------------- ### Prepare for Splitting State Across Directories Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Create a new directory 'dir2' and copy the configuration, modifying the backend to point to a new state file path for splitting the tfstate. ```bash # mkdir dir2 # cat config.tf | sed 's/test/dir2/' > dir2/config.tf ``` -------------------------------- ### ListCommand.Help Method Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Returns the help text for the list command, including usage and option documentation. ```go func (c *ListCommand) Help() string ``` -------------------------------- ### Error Handling: Invalid status filter Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Example error message for an unrecognized status filter value. ```text unknown filter for status: invalid_value ``` -------------------------------- ### ListCommand.Synopsis Method Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Returns a one-line help text summary for the list command. ```go func (c *ListCommand) Synopsis() string ``` -------------------------------- ### ListCommand.Run Method Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Executes the list command to display migrations. Requires history configuration to be present. Supports filtering by status. ```go func (c *ListCommand) Run(args []string) int ``` ```go ui := &cli.BasicUi{Writer: os.Stdout} cmd := &command.ListCommand{Meta: command.Meta{UI: ui}} exitCode := cmd.Run([]string{"--status", "unapplied"}) ``` -------------------------------- ### PlanCommand.Help Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Returns the help text for the plan command, including usage and option documentation. ```APIDOC ## PlanCommand.Help ### Description Returns the help text for the plan command. ### Method `Help` ### Return: String containing usage and option documentation ``` -------------------------------- ### Exported Functions and Types Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Documentation for all exported functions and types, including signatures, parameters, return types, and examples. ```APIDOC ## Exported API Reference This section documents all exported functions and types available in the tfmigrate library. ### Exported Functions - **Function Signature**: `FunctionName(param1 type, param2 type) returnType` - **Description**: A brief explanation of what the function does. - **Parameters**: Detailed description of each parameter, including its type and whether it's required or optional. - **Return Value**: Description of the return type and its meaning. - **Examples**: Code snippets demonstrating how to use the function. ### Exported Types - **Type Name**: `TypeName` - **Kind**: `struct` or `interface` or `type alias` - **Fields**: List of fields with their types and descriptions. - **Examples**: Usage examples for the type. ``` -------------------------------- ### Get FileRunner MigrationConfig Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Returns the parsed migration configuration, which includes the migration type, name, and migrator factory. ```go func (r *FileRunner) MigrationConfig() *tfmigrate.MigrationConfig ``` -------------------------------- ### Initialize Terraform and View State Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Initialize a Terraform working directory with a backend configuration and view the initial state of resources. ```bash # mkdir -p tmp && cp -pr test-fixtures/backend_s3 tmp/dir1 && cd tmp/dir1 # terraform init # cat main.tf ``` -------------------------------- ### Go Struct Definition Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Example of a Go struct definition, showcasing fields and their types. Used for documenting type definitions. ```go type MigratorOption struct { ExecPath string PlanOut string IsBackendTerraformCloud bool BackendConfig []string } ``` -------------------------------- ### Terraform CLI Commands Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md tfmigrate invokes the Terraform CLI for various operations. Ensure Terraform 0.12+ or OpenTofu 1.6+ is installed. ```bash terraform version terraform init terraform workspace show terraform state pull terraform state mv terraform state rm
terraform import
terraform state replace-provider terraform plan terraform state push ``` -------------------------------- ### Apply with Backend Configuration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Applies a migration and configures the backend for terraform init using multiple --backend-config options. ```bash tfmigrate apply \ --backend-config='bucket=state-bucket' \ --backend-config='key=prod.tfstate' migration.hcl ``` -------------------------------- ### ApplyCommand.Synopsis Method Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Returns a one-line synopsis for the apply command, summarizing its core function. This is typically used for brief command-line help. ```go func (c *ApplyCommand) Synopsis() string ``` -------------------------------- ### Go Function Signature Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Example of an exported function signature in Go, including parameter types. Used for documenting function definitions. ```go func NewFileRunner(filename string, config *config.TfmigrateConfig, option *tfmigrate.MigratorOption) (*FileRunner, error) ``` -------------------------------- ### WorkspaceShow Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/storage-and-tfexec.md Gets the name of the current Terraform workspace. It returns the workspace name (typically "default") and any error encountered. ```APIDOC ## WorkspaceShow ### Description Gets current workspace name. ### Method Go Function Signature ### Return - `string`: Workspace name (usually "default") - `error`: If command fails ``` -------------------------------- ### Migration with Workspace and Workspace Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Execute a state migration targeting a specific Terraform workspace. This allows for environment-specific resource renaming or modifications. ```hcl migration "state" "production_rename" { dir = "." workspace = "production" actions = [ "mv aws_db_instance.old aws_db_instance.new", ] } ``` -------------------------------- ### PlanCommand.Synopsis Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Returns a one-line help text summary for the plan command. ```APIDOC ## PlanCommand.Synopsis ### Description Returns one-line help text for the plan command. ### Method `Synopsis` ### Return: "Compute a new state" ``` -------------------------------- ### Get Number of Applied Migrations Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/history-package.md Returns the total count of migration records currently stored in the history. Useful for quick status checks. ```go count := controller.HistoryLength() ``` -------------------------------- ### Local History Storage Configuration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Configures tfmigrate to store migration history in a local JSON file. This is suitable for development and single-machine setups. ```hcl tfmigrate { history { storage "local" { path = "history.json" } } } ``` -------------------------------- ### Display general help information Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Use the --help flag to display general help information for tfmigrate. This provides an overview of available commands. ```bash tfmigrate --help ``` -------------------------------- ### State RM Action Examples Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Illustrates the 'rm' action for removing resources from the Terraform state. Can remove single or multiple resources by specifying their addresses. ```hcl actions = [ "rm aws_instance.old", "rm aws_security_group.deprecated aws_vpc.legacy", ] ``` -------------------------------- ### Initialize Terraform Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/storage-and-tfexec.md Initializes the Terraform working directory. Accepts additional flags for terraform init. ```go tf.Init(ctx, "-input=false", "-no-color") ``` -------------------------------- ### Configure GCS Storage Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Defines the configuration structure for GCS storage and provides an example of its usage in HCL. Uses Application Default Credentials for authentication. ```go type gcs.Config struct { Bucket string `hcl:"bucket"` Name string `hcl:"name"` } ``` ```hcl tfmigrate { history { storage "gcs" { bucket = "tfstate-test" name = "tfmigrate/history.json" } } } ``` -------------------------------- ### Error Handling: Migration File Not Found Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md This error occurs when the migration file specified for the plan or apply command cannot be found. Verify the file path and its existence. ```text failed to parse action: file not found ``` -------------------------------- ### Controller.NewController Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/history-package.md Creates a new Controller instance. Loads migration file list and history from storage. Returns a pointer to the Controller or an error if loading migrations or history fails. ```APIDOC ## Controller.NewController ### Description Creates a new Controller instance. Loads migration file list and history from storage. ### Method func ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for storage operations - **migrationDir** (string) - Required - Directory containing migration files - **config** (*Config) - Required - History configuration with storage backend ### Response #### Success Response - **Controller** (*Controller) - Pointer to Controller - **error** (error) - error if loading migrations or history fails ### Throws Error if directory is not accessible or storage read fails ### Example ```go historyConfig := &history.Config{ Storage: &local.Config{Path: "history.json"}, } controller, err := history.NewController(context.Background(), "./migrations", historyConfig) ``` ``` -------------------------------- ### S3 Storage KMS Encryption Configuration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/storage-and-tfexec.md Example of configuring S3 storage with KMS encryption for history files. Specify the KMS key ID for encryption. ```hcl storage "s3" { bucket = "terraform-state" key = "history.json" kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012" } ``` -------------------------------- ### Apply Terraform Configuration and List State Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Apply the Terraform configuration to create resources and then list the resources present in the Terraform state. ```bash # terraform apply -auto-approve # terraform state list ``` -------------------------------- ### ApplyCommand.Run Method Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Executes the apply command, processing arguments and delegating to file or history runners. Use this to run the apply process with specified arguments. ```go func (c *ApplyCommand) Run(args []string) int ``` -------------------------------- ### Exported Functions Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Documentation for exported functions includes their full signature, parameter descriptions, return types, error conditions, code examples, and source location. ```APIDOC ## Exported Functions Every exported function is documented with: - Full signature with parameter types - Parameter descriptions in table format - Return type documentation - Error/exception conditions - Working code example - Source file and line reference Example from **command-package.md**: ```go func NewFileRunner(filename string, config *config.TfmigrateConfig, option *tfmigrate.MigratorOption) (*FileRunner, error) ``` ``` -------------------------------- ### Get Unapplied Migration File Names Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/history-package.md Retrieves migration file names that have not yet been applied, sorted alphabetically. Use this to determine which migrations need to be run. ```go pending := controller.UnappliedMigrations() // Returns: ["003_rename.hcl"] ``` -------------------------------- ### Synopsis for PlanCommand Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Provides a one-line summary of the PlanCommand's functionality. ```go func (c *PlanCommand) Synopsis() string ``` -------------------------------- ### tfmigrate Configuration with Environment Variable Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md HCL2 configuration demonstrating how to use environment variables within the configuration file, such as for dynamic S3 key paths. ```hcl tfmigrate { migration_dir = "./tfmigrate" is_backend_terraform_cloud = true history { storage "s3" { bucket = "tfmigrate-test" key = "tfmigrate/${env.VAR_NAME}/history.json" } } } ``` -------------------------------- ### Create FileRunner Instance Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Creates a new FileRunner instance by loading and parsing a migration file. Ensure the migration file exists and is valid HCL. The migrator options can be nil. ```go func NewFileRunner(filename string, config *config.TfmigrateConfig, option *tfmigrate.MigratorOption) (*FileRunner, error) ``` ```go config, _ := config.LoadConfigurationFile(".tfmigrate.hcl") option := &tfmigrate.MigratorOption{ExecPath: "terraform"} runner, err := command.NewFileRunner("migration.hcl", config, option) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure S3 Storage Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Defines the configuration structure for S3 storage and provides an example of its usage in HCL. Supports authentication via environment variables or AWS profiles. ```go type s3.Config struct { Bucket string `hcl:"bucket"` Key string `hcl:"key"` Region string `hcl:"region,optional"` Endpoint string `hcl:"endpoint,optional"` AccessKey string `hcl:"access_key,optional"` SecretKey string `hcl:"secret_key,optional"` Profile string `hcl:"profile,optional"` RoleARN string `hcl:"role_arn,optional"` SkipCredentialsValidation bool `hcl:"skip_credentials_validation,optional"` SkipMetadataAPICheck bool `hcl:"skip_metadata_api_check,optional"` ForcePathStyle bool `hcl:"force_path_style,optional"` KmsKeyID string `hcl:"kms_key_id,optional"` } ``` ```hcl tfmigrate { history { storage "s3" { bucket = "tfmigrate-test" key = "tfmigrate/history.json" region = "ap-northeast-1" profile = "dev" } } } ``` -------------------------------- ### StateMigrator.Plan Method Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Plans the state migration by initializing the Terraform working directory, switching workspaces, pulling remote state, overriding the backend for testing, applying migration operations, and running 'terraform plan' to validate changes. It switches back to the remote backend afterwards. ```go func (m *StateMigrator) Plan(ctx context.Context) error ``` -------------------------------- ### Create MultiStateMigrator Instance Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Creates a new MultiStateMigrator instance from a MultiStateMigratorConfig. Ensure actions are provided and valid to avoid errors. ```go func (c *MultiStateMigratorConfig) NewMigrator(o *MigratorOption) (Migrator, error) ``` -------------------------------- ### State MV Action Examples Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Demonstrates the 'mv' action for moving resources within a Terraform state. Supports moving individual resources and resources with indexed or for-each syntax. ```hcl actions = [ "mv aws_security_group.old aws_security_group.new", "mv aws_instance.server[0] aws_instance.server[\"prod\"]", ] ``` -------------------------------- ### Apply with Custom Configuration File Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Applies a migration using a specified tfmigrate configuration file instead of the default. ```bash tfmigrate apply --config .tfmigrate.prod.hcl migration.hcl ``` -------------------------------- ### State Splitting for Monorepo Refactoring Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md Example of splitting resources into separate state files for monorepo refactoring. It defines a 'multi_state' migration to move resources from one directory to another. ```hcl migration "multi_state" "split_services" { from_dir = "monorepo" to_dir = "api-service" actions = [ "mv aws_lambda_function.api aws_lambda_function.api", "mv aws_iam_role.api aws_iam_role.api", ] } ``` -------------------------------- ### OverrideBackendToLocal Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/storage-and-tfexec.md Temporarily overrides the Terraform backend to a local configuration for safe migration testing. It returns a function to restore the original remote backend and any error encountered during the override setup. ```APIDOC ## OverrideBackendToLocal ### Description For safe migration testing, the TerraformCLI temporarily overrides the backend to local. ### Method Go Function Signature ### Parameters - `ctx` (context.Context): Context for the operation. - `filename` (string): Filename for the override configuration. - `workspace` (string): Workspace name. - `...`: Additional parameters. ### Return - `func() error`: Function to restore the remote backend. - `error`: If the override setup fails. ``` -------------------------------- ### tfmigrate Help Usage Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Displays the main usage information for the tfmigrate CLI, listing available commands. ```bash $ tfmigrate --help Usage: tfmigrate [--version] [--help] [] Available commands are: apply Compute a new state and push it to remote state list List migrations plan Compute a new state ``` -------------------------------- ### CLI Commands Reference Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/README.md Reference for all available tfmigrate CLI commands, including plan, apply, and list, with all their flags and options. ```APIDOC ## CLI Commands This section details the command-line interface for tfmigrate. ### `plan` Generates a migration plan without applying changes. ### `apply` Applies the generated migration plan. ### `list` Lists available migration states. ``` -------------------------------- ### Use Command-Line Flag for Configuration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Alternatively, use the --config flag directly on the command line to specify the configuration file. This provides an immediate override for the current command. ```bash # Using command-line flag tfmigrate plan --config config/tfmigrate.hcl migration.hcl ``` -------------------------------- ### Plan with Custom Configuration File Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Use the --config flag to specify a custom configuration file for the plan command. This allows for environment-specific settings without altering the default configuration. ```bash tfmigrate plan --config .tfmigrate.prod.hcl migration.hcl ``` -------------------------------- ### State Migration Type Example Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Illustrates the configuration for a 'state' migration type, operating on a single Terraform state. Includes options for working directory, workspace, actions, force, and skipping plan validation. ```hcl migration "state" "example" { dir = "." workspace = "default" actions = ["mv old new"] force = false skip_plan = false } ``` -------------------------------- ### Set Log Level and Filter Output Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Control the verbosity of tfmigrate output by setting the TFMIGRATE_LOG environment variable. This example sets the log level to DEBUG and filters the output to show lines containing 'migrator'. ```bash TFMIGRATE_LOG=DEBUG tfmigrate plan migration.hcl 2>&1 | grep "migrator" ``` -------------------------------- ### Run PlanCommand Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Executes the plan command, processing arguments and delegating to the appropriate runner. Use this to compute a new state without updating remote state. ```go func (c *PlanCommand) Run(args []string) int ``` ```go ui := &cli.BasicUi{Writer: os.Stdout} cmd := &command.PlanCommand{Meta: command.Meta{UI: ui}} exitCode := cmd.Run([]string{"migration.hcl"}) ``` -------------------------------- ### State Migration Using Environment Variables Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Shows how to access environment variables within a migration file for dynamic configuration. ```hcl migration "state" "test" { dir = "dir1" workspace = env.TFMIGRATE_WORKSPACE actions = [ "mv aws_security_group.foo aws_security_group.foo2" ] } ``` -------------------------------- ### Multi-Environment Configuration with S3 History Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/configuration.md Set up a dynamic configuration for multiple environments, using environment variables to specify S3 bucket names and regions for history storage. ```hcl tfmigrate { migration_dir = "./migrations" is_backend_terraform_cloud = env.USE_TERRAFORM_CLOUD == "true" history { storage "s3" { bucket = "terraform-state-${env.ENVIRONMENT}" key = "tfmigrate/history.json" region = env.AWS_REGION } } } ``` -------------------------------- ### Configure History Mode for Migrations Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md Set up history tracking by configuring the migration directory and history storage in a .tfmigrate.hcl file. ```hcl tfmigrate { migration_dir = "./migrations" history { storage "local" { path = "history.json" } } } ``` -------------------------------- ### Plan Migration with FileRunner Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Plans the migration using the underlying migrator. Pass a context for cancellation and timeouts. ```go func (r *FileRunner) Plan(ctx context.Context) error ``` ```go err := runner.Plan(context.Background()) ``` -------------------------------- ### Error Handling: Configuration File Not Found Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md This message indicates that the specified tfmigrate configuration file could not be loaded. Ensure the file path is correct and the file exists. ```text Failed to load config file: no such file ``` -------------------------------- ### List All Migrations Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md View all migrations, including applied and unapplied ones, using the 'tfmigrate list' command. ```bash tfmigrate list # Shows all migrations ``` -------------------------------- ### Init Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/storage-and-tfexec.md Initializes the Terraform working directory. This function can accept additional arguments to customize the initialization process, such as input and color flags. ```APIDOC ## Init ### Description Initializes terraform working directory. ### Method Go Function Signature ### Parameters - `args` ([]string): Additional terraform init flags (e.g., "-input=false", "-no-color") ### Example ```go tf.Init(ctx, "-input=false", "-no-color") ``` ``` -------------------------------- ### tfmigrate Plan Command Help Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Shows detailed usage for the 'tfmigrate plan' command, including its purpose, arguments, and options. This command computes a new state without applying changes. ```bash $ tfmigrate plan --help Usage: tfmigrate plan [PATH] Plan computes a new state by applying state migration operations to a temporary state. It will fail if terraform plan detects any diffs with the new state. Arguments: PATH A path of migration file Required in non-history mode. Optional in history-mode. Options: --config A path to tfmigrate config file --backend-config=path A backend configuration, a path to backend configuration file or key=value format backend configuraion. This option is passed to terraform init when switching backend to remote. --out=path Save a plan file after dry-run migration to the given path. Note that the saved plan file is not applicable in Terraform 1.1+. It's intended to use only for static analysis. ``` -------------------------------- ### NewStorage Method for Storage Configuration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/storage-and-tfexec.md This method is part of the storage configuration pattern, used to create a Storage instance. ```go func (c *Config) NewStorage() (storage.Storage, error) { return NewStorage(c) } ``` -------------------------------- ### Single Resource Rename Migration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md Demonstrates how to create, plan, and apply a migration to rename a single resource. This is typically done before merging configuration changes. ```bash # Create migration cat > rename.hcl <<'EOF' migration "state" "rename" { actions = ["mv old new"] } EOF # Validate tfmigrate plan rename.hcl # Apply tfmigrate apply rename.hcl # Merge config change git add rename.hcl git commit -m "Rename resource" git push ``` -------------------------------- ### Plan a Manual State Migration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Test a manually created state migration file to ensure the intended changes are correct before applying them. ```bash # Test tfmigrate plan migrations/20240115_fix_state.hcl ``` -------------------------------- ### Verify All Migrations Applied Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Confirm that all migrations have been successfully applied by listing their status. This is a verification step after applying changes. ```bash # Verify all are applied tfmigrate list ``` -------------------------------- ### View Applied Migrations Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/overview.md Lists all migrations that have been successfully applied. ```bash # View applied migrations tfmigrate list ``` -------------------------------- ### Plan Migrations with History Awareness Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Plans migrations while considering historical application status. Use this to preview changes before applying them. It can plan a single migration if a filename is specified. ```go func (r *HistoryRunner) Plan(ctx context.Context) error ``` ```go err := runner.Plan(context.Background()) ``` -------------------------------- ### tfmigrate List Command Help Source: https://github.com/minamijoyo/tfmigrate/blob/master/README.md Provides usage information for the 'tfmigrate list' command, used to list migrations. It includes options for filtering by status. ```bash $ tfmigrate list --help Usage: tfmigrate list List migrations. Options: --config A path to tfmigrate config file --status A filter for migration status Valid values are as follows: - all (default) - unapplied ``` -------------------------------- ### PlanCommand.Run Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/command-package.md Executes the plan command. Processes command-line arguments and delegates to either file runner or history runner based on configuration. Supports flags for config file, backend configuration, and output path. ```APIDOC ## PlanCommand.Run ### Description Executes the plan command. Processes command-line arguments and delegates to either file runner or history runner based on configuration. ### Method `Run` ### Parameters #### Path Parameters - **args** ([]string) - Required - Command-line arguments passed to the plan command ### Request Example ```go ui := &cli.BasicUi{Writer: os.Stdout} cmd := &command.PlanCommand{Meta: command.Meta{UI: ui}} exitCode := cmd.Run([]string{"migration.hcl"}) ``` ### Supported flags: - `--config`: Path to tfmigrate config file (default: `.tfmigrate.hcl`) - `--backend-config`: Backend configuration (path or key=value format) - `--out`: Path to save plan file ### Return: Exit status (0 for success, 1 for error) ### Throws: Error messages printed to UI on validation or execution failures ``` -------------------------------- ### Specify Terraform Backend Configuration Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/cli-reference.md Use the --backend-config flag to provide configuration settings for terraform init. This can be a file path or a key=value pair. Multiple --backend-config flags can be used to specify various settings, which is useful for overriding default configurations or providing runtime credentials. ```bash # File path format tfmigrate plan --backend-config=/path/to/backend.tf migration.hcl # Key=value format tfmigrate plan --backend-config='key=value' migration.hcl # Multiple values tfmigrate apply \ --backend-config='bucket=my-bucket' \ --backend-config='key=prod/terraform.tfstate' \ migration.hcl ``` -------------------------------- ### LoadConfigurationFile Function Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/config-package.md Reads and parses a tfmigrate configuration file from disk. Use this function when the configuration is stored in a file. ```go func LoadConfigurationFile(filename string) (*TfmigrateConfig, error) ``` ```go config, err := config.LoadConfigurationFile(".tfmigrate.hcl") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create StateAction from String Source: https://github.com/minamijoyo/tfmigrate/blob/master/_autodocs/tfmigrate-migrator.md Use this factory method to create StateAction instances from plain text command strings. It supports various state operations like move, remove, import, and replace-provider. Ensure the command string follows one of the valid formats. ```go func NewStateActionFromString(cmdStr string) (StateAction, error) ``` ```go action, err := tfmigrate.NewStateActionFromString("mv aws_sg.foo aws_sg.bar") ```