### Install tf-manage2 using Go Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Installs tf-manage2 using the Go toolchain. This method requires Go to be installed and configured. It places the binary in the Go bin directory and symlinks it to /usr/local/bin/tf. ```bash export PATH=$PATH:$(go env GOPATH)/bin go install github.com/sorinlg/tf-manage2@latest sudo ln -s $(go env GOPATH)/bin/tf-manage2 /usr/local/bin/tf ``` -------------------------------- ### tf-manage2 CLI Usage Example Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Demonstrates the basic command structure for tf-manage2, showing how to specify project, module, environment, instance, and action, along with an example of overriding the workspace. ```bash tf [workspace] # Examples: tf project1 sample_module dev instance_x init tf project1 sample_module dev instance_x plan tf project1 sample_module dev instance_x apply tf project1 sample_module staging instance_y destroy workspace=custom ``` -------------------------------- ### Install tf-manage2 via Homebrew (Development/Prerelease) Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Installs a development or prerelease version of tf-manage2 using a separate Homebrew tap. Use this for testing new features or providing early feedback. ```bash brew install sorinlg/dev-tap/tf-manage2-dev ``` -------------------------------- ### Install tf-manage2 via Homebrew (Stable) Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Installs the stable version of tf-manage2 using the Homebrew package manager. This is the recommended method for most users seeking a reliable installation. ```bash brew install sorinlg/tap/tf-manage2 ``` -------------------------------- ### YAML Configuration Format Source: https://context7.com/sorinlg/tf-manage2/llms.txt An example of the recommended YAML configuration file format for tf-manage2. It specifies the configuration version, repository name, and relative paths for environments and modules. ```yaml # .tfm.yaml config_version: "2.0" repo_name: "your-project-name" env_rel_path: "terraform/environments" module_rel_path: "terraform/modules" ``` -------------------------------- ### Download and Install tf-manage2 Binary (Linux AMD64) Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Downloads the latest tf-manage2 binary for Linux AMD64 architecture directly from GitHub releases. The script makes the binary executable and moves it to /usr/local/bin/tf. ```bash curl -L https://github.com/sorinlg/tf-manage2/releases/latest/download/tf-manage2-linux-amd64 -o tf-manage2 chmod +x tf-manage2 sudo mv tf-manage2 /usr/local/bin/tf ``` -------------------------------- ### tf-manage2 Modern YAML Configuration Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md An example of the recommended .tfm.yaml configuration file for tf-manage2. It defines repository name and relative paths for environments and modules. ```yaml # tf-manage2 configuration file config_version: "2.0" repo_name: "your-project-name" env_rel_path: "terraform/environments" module_rel_path: "terraform/modules" ``` -------------------------------- ### GitHub Actions Workflow for Terraform Deployment Source: https://context7.com/sorinlg/tf-manage2/llms.txt This GitHub Actions workflow automates Terraform deployments. It checks out the code, sets up Terraform, installs the tf-manage2 tool, and then performs validation, initialization, planning, and applying of Terraform configurations. It specifically targets the 'main' branch for deployments. ```yaml name: Terraform Deployment on: push: branches: [main] pull_request: branches: [main] jobs: terraform: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Terraform uses: hashicorp/setup-terraform@v2 with: terraform_version: 1.5.0 - name: Install tf-manage2 run: | curl -L https://github.com/sorinlg/tf-manage2/releases/latest/download/tf-manage2-linux-amd64 -o tf chmod +x tf sudo mv tf /usr/local/bin/ - name: Validate Configuration run: tf config validate - name: Terraform Init run: tf project1 vpc dev main init - name: Terraform Plan run: tf project1 vpc dev main plan - name: Terraform Apply if: github.ref == 'refs/heads/main' run: tf project1 vpc dev main apply # Auto-approves because GITHUB_ACTIONS=true is detected - name: Terraform Output run: tf project1 vpc dev main "output -json" ``` -------------------------------- ### Enable Bash Shell Completion for tf-manage2 Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Configures bash shell completion for the 'tf' command. This requires adding a script sourced from Homebrew's installation directory to your ~/.bashrc file. ```bash # Add to ~/.bashrc if command -v tf &> /dev/null; then . $(brew --prefix)/etc/bash_completion.d/tf fi ``` -------------------------------- ### Legacy Bash Configuration Format Source: https://context7.com/sorinlg/tf-manage2/llms.txt An example of the deprecated legacy bash configuration format for tf-manage2. It uses exported environment variables to define repository name and relative paths. ```bash #!/bin/bash # .tfm.conf export __tfm_repo_name='your-project-name' export __tfm_env_rel_path='terraform/environments' export __tfm_module_rel_path='terraform/modules' ``` -------------------------------- ### tf-manage2 Legacy Bash Configuration (Deprecated) Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md An example of the legacy .tfm.conf configuration file for tf-manage2. This format is deprecated and will be removed in v2.0. It uses bash exports to set configuration variables. ```bash #!/bin/bash export __tfm_repo_name='your-project-name' export __tfm_env_rel_path='terraform/environments' export __tfm_module_rel_path='terraform/modules' ``` -------------------------------- ### Main Entry Point - Go Source: https://context7.com/sorinlg/tf-manage2/llms.txt Sets up version information and executes the main CLI command for tf-manage2. It handles command parsing and error reporting, exiting with a non-zero status on failure. ```go package main import ( "fmt" "os" "github.com/sorinlg/tf-manage2/internal/cli" ) var ( version = "dev" commit = "none" date = "unknown" builtBy = "unknown" ) func main() { cli.SetVersionInfo(version, commit, date, builtBy) if err := cli.Execute(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } } ``` -------------------------------- ### Execute Terraform Operations with Manager Interface (Go) Source: https://context7.com/sorinlg/tf-manage2/llms.txt Demonstrates how to use the Manager interface to execute various Terraform commands like init, plan, apply, destroy, and output. It requires loading configuration and creating a new Manager instance. The commands can target specific products, modules, and environments, with options for action flags. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/config" "github.com/sorinlg/tf-manage2/internal/terraform" "os" ) cfg, _ := config.LoadConfig() mgr := terraform.NewManager(cfg) // Initialize Terraform initCmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "dev", ModuleInstance: "main", Action: "init", } err := mgr.Execute(initCmd) // Plan changes planCmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "dev", ModuleInstance: "main", Action: "plan", ActionFlags: "-target=aws_vpc.main", } err = mgr.Execute(planCmd) // Apply changes (interactive with confirmation) applyCmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "dev", ModuleInstance: "main", Action: "apply", } err = mgr.Execute(applyCmd) // Apply from plan file (no confirmation) applyPlanCmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "dev", ModuleInstance: "main", Action: "apply_plan", } err = mgr.Execute(applyPlanCmd) // Destroy resources destroyCmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "dev", ModuleInstance: "main", Action: "destroy", } err = mgr.Execute(destroyCmd) // Get outputs outputCmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "dev", ModuleInstance: "main", Action: "output", ActionFlags: "-json", } err = mgr.Execute(outputCmd) ``` -------------------------------- ### Configuration Management - Go Source: https://context7.com/sorinlg/tf-manage2/llms.txt Shows how to load, access, and validate tf-manage2 configuration, which can be in YAML or bash format. It also demonstrates creating and writing a new YAML configuration file. ```go package main import ( "fmt" "github.com/sorinlg/tf-manage2/internal/config" ) // Load configuration (auto-detects .tfm.yaml or .tfm.conf) cfg, err := config.LoadConfig() if err != nil { panic(err) } // Access configuration values fmt.Printf("Repository: %s\n", cfg.RepoName) fmt.Printf("Environments: %s\n", cfg.GetEnvPath()) fmt.Printf("Modules: %s\n", cfg.GetModulePath()) // Validate configuration if err := cfg.Validate(); err != nil { panic(err) } // Create new YAML configuration newCfg := &config.Config{ ConfigVersion: "2.0", RepoName: "my-project", EnvRelPath: "terraform/environments", ModuleRelPath: "terraform/modules", ProjectDir: "/path/to/project", } configPath := "/path/to/project/.tfm.yaml" if err := config.WriteYAMLConfig(configPath, newCfg); err != nil { panic(err) } ``` -------------------------------- ### Complete Terraform Workflow in Bash Source: https://context7.com/sorinlg/tf-manage2/llms.txt Provides a comprehensive bash script demonstrating the full Terraform workflow using tf-manage2. This includes initialization, validation, planning, applying, managing state, importing resources, tainting, destroying, and formatting. ```bash #!/bin/bash # 1. Initialize project with YAML config cd /path/to/terraform/project tf config init yaml # 2. Verify configuration tf config validate # 3. Project structure # terraform/ # environments/ # project1/ # dev/ # vpc/ # main.tfvars # staging/ # vpc/ # main.tfvars # modules/ # vpc/ # main.tf # variables.tf # outputs.tf # 4. Initialize Terraform tf project1 vpc dev main init # 5. Plan changes tf project1 vpc dev main plan # 6. Review plan and apply tf project1 vpc dev main apply # 7. Apply from plan file (skip confirmation) tf project1 vpc dev main apply_plan # 8. View outputs tf project1 vpc dev main output tf project1 vpc dev main "output -json vpc_id" # 9. Manage state tf project1 vpc dev main "state list" tf project1 vpc dev main "state show aws_vpc.main" # 10. Import existing resources tf project1 vpc dev main "import aws_vpc.main vpc-12345" # 11. Taint resource for recreation tf project1 vpc dev main "taint aws_vpc.main" # 12. Destroy infrastructure tf project1 vpc dev main destroy # 13. Use custom workspace tf project1 vpc dev main plan workspace=custom-workspace # 14. Format Terraform files tf project1 vpc dev main fmt # 15. Validate configuration tf project1 vpc dev main validate ``` -------------------------------- ### CLI Execution - Go Source: https://context7.com/sorinlg/tf-manage2/llms.txt Demonstrates how to programmatically execute Terraform commands using tf-manage2. It involves loading configuration, defining a command structure, and using the Terraform manager to execute the command, handling potential errors. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/cli" "github.com/sorinlg/tf-manage2/internal/config" "github.com/sorinlg/tf-manage2/internal/terraform" ) // Load configuration cfg, err := config.LoadConfig() if err != nil { panic(err) } // Parse command from arguments cmd := &terraform.Command{ Product: "project1", Module: "sample_module", Env: "dev", ModuleInstance: "instance_x", Action: "plan", ActionFlags: "", Workspace: "", // Optional override } // Create manager and execute tfm := terraform.NewManager(cfg) err = tfm.Execute(cmd) if exitCodeErr, ok := err.(*terraform.ExitCodeError); ok { os.Exit(exitCodeErr.ExitCode) } ``` -------------------------------- ### tf-manage2 Configuration Management CLI Commands Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Provides command-line interface commands for managing tf-manage2 configuration, including initializing new configurations in YAML or legacy format, converting legacy to YAML, and validating the current configuration. ```bash # Create new YAML configuration tf config init yaml # Create new legacy configuration (deprecated) tf config init legacy # Convert legacy to YAML format tf config convert # Validate current configuration tf config validate ``` -------------------------------- ### Shell Completion in Go Source: https://context7.com/sorinlg/tf-manage2/llms.txt Provides context-aware shell completion suggestions for various Terraform operations. It supports suggesting products, modules, environments, configuration files, actions, and workspace overrides. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/cli" "github.com/sorinlg/tf-manage2/internal/config" ) cfg, _ := config.LoadConfig() completion := cli.NewCompletion(cfg) // Suggest available products completion.SuggestProducts() // Output: project1\nproject2\nproject3 // Suggest available modules completion.SuggestModules() // Output: vpc\necs\nrds\ns3 // Suggest environments for product and module completion.SuggestEnvironments("project1", "vpc") // Output: dev\nstaging\nprod // Suggest config files completion.SuggestConfigs("project1", "dev", "vpc") // Output: main\nbackup // Suggest available actions completion.SuggestActions() // Output: init\nplan\napply\ndestroy\noutput // Suggest workspace override completion.SuggestWorkspace() // Output: workspace=default ``` -------------------------------- ### Execute System Commands with Framework (Go) Source: https://context7.com/sorinlg/tf-manage2/llms.txt Illustrates executing system commands using the framework.RunCmd function, allowing for custom output and error handling. It supports different execution modes like silent, strict, and interactive, and provides a result struct to check command success, output, and errors. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/framework" ) // Basic command execution result := framework.RunCmd( "terraform --version", "Checking Terraform version", framework.DefaultCmdFlags(), "Terraform not found", ) // Custom flags for command execution flags := framework.DefaultCmdFlags() flags.PrintOutput = false flags.PrintMessage = true flags.PrintStatus = true result = framework.RunCmd( "terraform init", "Initializing Terraform", flags, "Init failed", ) // Silent execution result = framework.RunCmdSilent( "terraform workspace list", "Checking workspaces", "Workspace check failed", ) // Strict mode (exits on failure) result = framework.RunCmdStrict( "terraform validate", "Validating configuration", "Validation failed", ) // Interactive mode (preserves stdin) result = framework.RunCmdInteractive( "terraform apply", "Applying changes", "Apply failed", ) // Check result if result.Success { println("Command succeeded") println("Output:", result.Output) } else { println("Command failed with exit code:", result.ExitCode) println("Error:", result.Error) } ``` -------------------------------- ### Go: Advanced Terraform Deployment with Error Handling Source: https://context7.com/sorinlg/tf-manage2/llms.txt This Go program demonstrates advanced Terraform deployment management using tf-manage2. It includes comprehensive error handling for configuration loading and execution of Terraform stages (init, validate, plan, apply). The program also retrieves Terraform outputs in JSON format. ```go package main import ( "fmt" "os" "github.com/sorinlg/tf-manage2/internal/config" "github.com/sorinlg/tf-manage2/internal/terraform" "github.com/sorinlg/tf-manage2/internal/framework" ) func deployInfrastructure() error { // Load configuration cfg, err := config.LoadConfig() if err != nil { return fmt.Errorf("config load failed: %w", err) } // Create manager mgr := terraform.NewManager(cfg) // Define deployment stages stages := []struct { name string action string flags string }{ {"Initialize", "init", ""}, {"Validate", "validate", ""}, {"Plan", "plan", ""}, {"Apply", "apply", ""}, } // Execute each stage for _, stage := range stages { framework.Info(fmt.Sprintf("Stage: %s", stage.name)) cmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "production", ModuleInstance: "main", Action: stage.action, ActionFlags: stage.flags, } err := mgr.Execute(cmd) if exitCodeErr, ok := err.(*terraform.ExitCodeError); ok { if exitCodeErr.ExitCode != 0 { return fmt.Errorf("stage %s failed with exit code %d", stage.name, exitCodeErr.ExitCode) } } } // Get outputs outputCmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "production", ModuleInstance: "main", Action: "output", ActionFlags: "-json", } err = mgr.Execute(outputCmd) if err != nil { return fmt.Errorf("failed to get outputs: %w", err) } return nil } func main() { if err := deployInfrastructure(); err != nil { framework.Error(fmt.Sprintf("Deployment failed: %v", err)) os.Exit(1) } framework.Info("Deployment completed successfully") } ``` -------------------------------- ### Enable Zsh Shell Completion for tf-manage2 Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Configures zsh shell completion for the 'tf' command. This involves adding the completion directory to your fpath and initializing compinit in your ~/.zshrc file. ```zsh # Add to ~/.zshrc if command -v tf &> /dev/null; then fpath=( $(brew --prefix)/share/tf-completion $fpath ) autoload -U compinit && compinit fi ``` -------------------------------- ### Configuration Conversion - Go Source: https://context7.com/sorinlg/tf-manage2/llms.txt Provides a Go function to convert legacy bash configuration files (.tfm.conf) to the modern YAML format (.tfm.yaml). It handles the conversion process and provides feedback on success or failure. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/config" ) // Convert .tfm.conf to .tfm.yaml projectDir := "/path/to/project" err := config.ConvertLegacyToYAML(projectDir) if err != nil { panic(err) } // Output: // ✅ Created YAML configuration at /path/to/project/.tfm.yaml // 📝 Backed up legacy config to /path/to/project/.tfm.conf.backup ``` -------------------------------- ### Native Go Functions for Validation (Go) Source: https://context7.com/sorinlg/tf-manage2/llms.txt Provides native Go functions for performing validation checks, replacing slower shell commands. It includes functions to test directory existence, file existence, and string non-emptiness, offering a more performant alternative for common validation tasks. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/framework" ) flags := framework.DefaultCmdFlags() flags.PrintOutput = false // Check if directory exists result := framework.RunNative( framework.NativeTestDir("/path/to/terraform/modules"), "Checking modules directory exists", flags, "Modules directory not found", ) // Check if file exists result = framework.RunNative( framework.NativeTestFile("/path/to/config.tfvars"), "Checking config file exists", flags, "Config file not found", ) // Check if string is not empty result = framework.RunNative( framework.NativeTestNotEmpty("my-repo-name"), "Validating repository name", flags, "Repository name is empty", ) // Direct native function calls dirResult := framework.TestDir("/path/to/directory") fileResult := framework.TestFile("/path/to/file.txt") stringResult := framework.TestNotEmpty("value") if dirResult.Success { println("Directory exists") } ``` -------------------------------- ### Go: Custom Command Flags for Fine-Grained Control Source: https://context7.com/sorinlg/tf-manage2/llms.txt This Go code snippet demonstrates how to use custom command flags provided by tf-manage2's framework for precise control over command execution. It illustrates setting options like strict error checking, command printing, output decoration, and defining valid exit codes. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/framework" ) // Create custom flags flags := &framework.CmdFlags{ Strict: true, // Exit on failure PrintCmd: true, // Show command DecorateOutput: true, // Add [cmd] prefix PrintOutput: true, // Show output PrintMessage: true, // Show message PrintStatus: true, // Show ✓/✗ PrintOutcome: true, // Show done/continuing StrictMessage: "aborting deployment", // Failure message NoStrictMessage: "continuing with errors", ValidExitCodes: []int{0, 2}, // Accept 0 or 2 } result := framework.RunCmd( "terraform plan -detailed-exitcode", "Planning with detailed exit code", flags, "Plan failed", ) // Exit codes: // 0 = no changes // 1 = error // 2 = changes detected if result.ExitCode == 2 { println("Changes detected, proceeding to apply") } ``` -------------------------------- ### Reload Shell after enabling completion Source: https://github.com/sorinlg/tf-manage2/blob/develop/README.md Reloads the current shell environment to apply changes made to shell configuration files like ~/.bashrc or ~/.zshrc, making shell completion active. ```bash source ~/.bashrc # or ~/.zshrc for zsh users ``` -------------------------------- ### CI/CD Detection in Go Source: https://context7.com/sorinlg/tf-manage2/llms.txt Automatically detects CI/CD environments for unattended Terraform execution. It identifies common CI systems and can force unattended mode or auto-approve commands in CI environments. Overrides can be set using environment variables. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/terraform" "github.com/sorinlg/tf-manage2/internal/config" "os" ) cfg, _ := config.LoadConfig() mgr := terraform.NewManager(cfg) // Detect execution mode (returns "operator" or "unattended") mode := mgr.detectExecMode() // Detected CI systems: // - GITHUB_ACTIONS=true (GitHub Actions) // - GITLAB_CI=true (GitLab CI) // - CIRCLECI=true (CircleCI) // - TRAVIS=true (Travis CI) // - TF_BUILD=True (Azure DevOps) // - JENKINS_URL or BUILD_NUMBER (Jenkins) // - bamboo_buildKey (Bamboo) // - TEAMCITY_VERSION (TeamCity) // - BUILDKITE=true (Buildkite) // - DRONE=true (Drone CI) // - CODEBUILD_BUILD_ID (AWS CodeBuild) // - CI=true or CI=1 (Generic CI) // Force unattended mode os.Setenv("TF_EXEC_MODE_OVERRIDE", "1") // In CI mode, apply/destroy commands auto-approve cmd := &terraform.Command{ Product: "project1", Module: "vpc", Env: "dev", ModuleInstance: "main", Action: "apply", } mgr.Execute(cmd) // Runs with -auto-approve ``` -------------------------------- ### Output Formatting and Colors in Go Source: https://context7.com/sorinlg/tf-manage2/llms.txt Formats output messages using ANSI color codes for enhanced readability. Supports info, error, debug, and emphasis styling. Debug output can be enabled by setting the TFM_DEBUG environment variable. ```go package main import ( "github.com/sorinlg/tf-manage2/internal/framework" "fmt" "os" ) // Print info messages framework.Info("Starting Terraform operations") // Print error messages framework.Error("Failed to initialize Terraform") // Enable debug output os.Setenv("TFM_DEBUG", "1") framework.Debug("Debug information") // Color formatting blueText := framework.AddEmphasisBlue("project1") redText := framework.AddEmphasisRed("failed") greenText := framework.AddEmphasisGreen("success") magentaText := framework.AddEmphasisMagenta("warning") grayText := framework.AddEmphasisGray("[tf]") fmt.Printf("Status: %s\n", greenText) fmt.Printf("Project: %s Environment: %s\n", framework.AddEmphasisBlue("project1"), framework.AddEmphasisGreen("production")) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.