|
1 | 1 | package terraform |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "slices" |
| 5 | + "strings" |
| 6 | + |
4 | 7 | "github.com/spf13/cobra" |
| 8 | + "github.com/spf13/viper" |
5 | 9 |
|
6 | 10 | "github.com/cloudposse/atmos/cmd/internal" |
| 11 | + errUtils "github.com/cloudposse/atmos/errors" |
| 12 | + exec "github.com/cloudposse/atmos/internal/exec" |
| 13 | + cfg "github.com/cloudposse/atmos/pkg/config" |
| 14 | + "github.com/cloudposse/atmos/pkg/data" |
| 15 | + "github.com/cloudposse/atmos/pkg/flags" |
| 16 | + "github.com/cloudposse/atmos/pkg/flags/compat" |
| 17 | + "github.com/cloudposse/atmos/pkg/perf" |
| 18 | + "github.com/cloudposse/atmos/pkg/schema" |
| 19 | + tfoutput "github.com/cloudposse/atmos/pkg/terraform/output" |
7 | 20 | ) |
8 | 21 |
|
| 22 | +// outputParser handles flag parsing for output command. |
| 23 | +var outputParser *flags.StandardParser |
| 24 | + |
9 | 25 | // outputCmd represents the terraform output command. |
10 | 26 | var outputCmd = &cobra.Command{ |
11 | 27 | Use: "output", |
12 | 28 | Short: "Show output values from your root module", |
13 | | - Long: `Read an output variable from the state file. |
| 29 | + Long: `Read output variables from the state file. |
| 30 | +
|
| 31 | +When --format is specified, retrieves all outputs and formats them in the specified format. |
| 32 | +Without --format, passes through to native terraform/tofu output command. |
14 | 33 |
|
15 | 34 | For complete Terraform/OpenTofu documentation, see: |
16 | 35 | https://developer.hashicorp.com/terraform/cli/commands/output |
17 | 36 | https://opentofu.org/docs/cli/commands/output`, |
18 | 37 | RunE: func(cmd *cobra.Command, args []string) error { |
19 | | - return terraformRun(terraformCmd, cmd, args) |
| 38 | + v := viper.GetViper() |
| 39 | + if err := terraformParser.BindFlagsToViper(cmd, v); err != nil { |
| 40 | + return err |
| 41 | + } |
| 42 | + if err := outputParser.BindFlagsToViper(cmd, v); err != nil { |
| 43 | + return err |
| 44 | + } |
| 45 | + format := v.GetString("format") |
| 46 | + if format == "" { |
| 47 | + return terraformRun(terraformCmd, cmd, args) |
| 48 | + } |
| 49 | + return outputRunWithFormat(cmd, args, format) |
20 | 50 | }, |
21 | 51 | } |
22 | 52 |
|
| 53 | +// outputRunWithFormat executes terraform output with atmos formatting. |
| 54 | +func outputRunWithFormat(cmd *cobra.Command, args []string, format string) error { |
| 55 | + defer perf.Track(nil, "terraform.outputRunWithFormat")() |
| 56 | + |
| 57 | + if err := validateOutputFormat(format); err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + info, atmosConfig, err := prepareOutputContext(cmd, args) |
| 61 | + if err != nil { |
| 62 | + return err |
| 63 | + } |
| 64 | + return executeOutputWithFormat(atmosConfig, info, format) |
| 65 | +} |
| 66 | + |
| 67 | +// validateOutputFormat checks if the format is supported. |
| 68 | +func validateOutputFormat(format string) error { |
| 69 | + if !slices.Contains(tfoutput.SupportedFormats, format) { |
| 70 | + return errUtils.Build(errUtils.ErrInvalidArgumentError). |
| 71 | + WithExplanationf("Invalid --format value %q.", format). |
| 72 | + WithHintf("Supported formats: %s.", strings.Join(tfoutput.SupportedFormats, ", ")). |
| 73 | + Err() |
| 74 | + } |
| 75 | + return nil |
| 76 | +} |
| 77 | + |
| 78 | +// prepareOutputContext validates config and prepares component info. |
| 79 | +func prepareOutputContext(cmd *cobra.Command, args []string) (*schema.ConfigAndStacksInfo, *schema.AtmosConfiguration, error) { |
| 80 | + if err := internal.ValidateAtmosConfig(); err != nil { |
| 81 | + return nil, nil, err |
| 82 | + } |
| 83 | + separatedArgs := compat.GetSeparated() |
| 84 | + argsWithSubCommand := append([]string{"output"}, args...) |
| 85 | + info, err := exec.ProcessCommandLineArgs(cfg.TerraformComponentType, terraformCmd, argsWithSubCommand, separatedArgs) |
| 86 | + if err != nil { |
| 87 | + return nil, nil, err |
| 88 | + } |
| 89 | + if err := resolveAndPromptForArgs(&info, cmd); err != nil { |
| 90 | + return nil, nil, err |
| 91 | + } |
| 92 | + v := viper.GetViper() |
| 93 | + globalFlags := flags.ParseGlobalFlags(cmd, v) |
| 94 | + configAndStacksInfo := schema.ConfigAndStacksInfo{ |
| 95 | + AtmosBasePath: globalFlags.BasePath, |
| 96 | + AtmosConfigFilesFromArg: globalFlags.Config, |
| 97 | + AtmosConfigDirsFromArg: globalFlags.ConfigPath, |
| 98 | + ProfilesFromArg: globalFlags.Profile, |
| 99 | + ComponentFromArg: info.ComponentFromArg, |
| 100 | + Stack: info.Stack, |
| 101 | + } |
| 102 | + atmosConfig, err := cfg.InitCliConfig(configAndStacksInfo, true) |
| 103 | + if err != nil { |
| 104 | + return nil, nil, errUtils.Build(errUtils.ErrInitializeCLIConfig).WithCause(err).Err() |
| 105 | + } |
| 106 | + return &info, &atmosConfig, nil |
| 107 | +} |
| 108 | + |
| 109 | +// executeOutputWithFormat retrieves and formats terraform outputs. |
| 110 | +func executeOutputWithFormat(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo, format string) error { |
| 111 | + v := viper.GetViper() |
| 112 | + skipInit := v.GetBool("skip-init") |
| 113 | + outputFile := v.GetString("output-file") |
| 114 | + uppercase := v.GetBool("uppercase") |
| 115 | + flatten := v.GetBool("flatten") |
| 116 | + |
| 117 | + outputs, err := tfoutput.GetComponentOutputs(atmosConfig, info.ComponentFromArg, info.Stack, skipInit) |
| 118 | + if err != nil { |
| 119 | + return errUtils.Build(errUtils.ErrTerraformOutputFailed). |
| 120 | + WithCause(err). |
| 121 | + WithExplanationf("Failed to get terraform outputs for component %q in stack %q.", info.ComponentFromArg, info.Stack). |
| 122 | + Err() |
| 123 | + } |
| 124 | + |
| 125 | + // Build format options. |
| 126 | + opts := tfoutput.FormatOptions{ |
| 127 | + Uppercase: uppercase, |
| 128 | + Flatten: flatten, |
| 129 | + } |
| 130 | + |
| 131 | + // Check if a specific output name was requested (in AdditionalArgsAndFlags). |
| 132 | + outputName := extractOutputName(info.AdditionalArgsAndFlags) |
| 133 | + var formatted string |
| 134 | + if outputName != "" { |
| 135 | + formatted, err = formatSingleOutput(outputs, outputName, format, opts) |
| 136 | + } else { |
| 137 | + formatted, err = tfoutput.FormatOutputsWithOptions(outputs, tfoutput.Format(format), opts) |
| 138 | + } |
| 139 | + if err != nil { |
| 140 | + return err |
| 141 | + } |
| 142 | + |
| 143 | + if outputFile != "" { |
| 144 | + return tfoutput.WriteToFile(outputFile, formatted) |
| 145 | + } |
| 146 | + return data.Write(formatted) |
| 147 | +} |
| 148 | + |
| 149 | +// extractOutputName extracts the output name from additional args. |
| 150 | +// Output name is a positional arg that doesn't start with "-". |
| 151 | +func extractOutputName(args []string) string { |
| 152 | + for _, arg := range args { |
| 153 | + if !strings.HasPrefix(arg, "-") { |
| 154 | + return arg |
| 155 | + } |
| 156 | + } |
| 157 | + return "" |
| 158 | +} |
| 159 | + |
| 160 | +// formatSingleOutput formats a single output value. |
| 161 | +func formatSingleOutput(outputs map[string]any, outputName, format string, opts tfoutput.FormatOptions) (string, error) { |
| 162 | + value, exists := outputs[outputName] |
| 163 | + if !exists { |
| 164 | + return "", errUtils.Build(errUtils.ErrTerraformOutputFailed). |
| 165 | + WithExplanationf("Output %q not found.", outputName). |
| 166 | + WithHint("Use 'atmos terraform output <component> -s <stack>' without an output name to see all available outputs."). |
| 167 | + Err() |
| 168 | + } |
| 169 | + return tfoutput.FormatSingleValueWithOptions(outputName, value, tfoutput.Format(format), opts) |
| 170 | +} |
| 171 | + |
23 | 172 | func init() { |
24 | | - // Register completions for outputCmd. |
| 173 | + outputParser = flags.NewStandardParser( |
| 174 | + flags.WithStringFlag("format", "f", "", "Output format: json, yaml, hcl, env, dotenv, bash, csv, tsv"), |
| 175 | + flags.WithStringFlag("output-file", "o", "", "Write output to file instead of stdout"), |
| 176 | + flags.WithBoolFlag("uppercase", "u", false, "Convert keys to uppercase (useful for env vars)"), |
| 177 | + flags.WithBoolFlag("flatten", "", false, "Flatten nested maps into key_subkey format"), |
| 178 | + flags.WithEnvVars("format", "ATMOS_TERRAFORM_OUTPUT_FORMAT"), |
| 179 | + flags.WithEnvVars("output-file", "ATMOS_TERRAFORM_OUTPUT_FILE"), |
| 180 | + flags.WithEnvVars("uppercase", "ATMOS_TERRAFORM_OUTPUT_UPPERCASE"), |
| 181 | + flags.WithEnvVars("flatten", "ATMOS_TERRAFORM_OUTPUT_FLATTEN"), |
| 182 | + ) |
| 183 | + outputParser.RegisterFlags(outputCmd) |
| 184 | + if err := outputParser.BindToViper(viper.GetViper()); err != nil { |
| 185 | + panic(err) |
| 186 | + } |
| 187 | + if err := outputCmd.RegisterFlagCompletionFunc("format", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 188 | + return tfoutput.SupportedFormats, cobra.ShellCompDirectiveNoFileComp |
| 189 | + }); err != nil { |
| 190 | + _ = err |
| 191 | + } |
25 | 192 | RegisterTerraformCompletions(outputCmd) |
26 | | - |
27 | | - // Register compat flags for this subcommand. |
28 | 193 | internal.RegisterCommandCompatFlags("terraform", "output", OutputCompatFlags()) |
29 | | - |
30 | | - // Attach to parent terraform command. |
31 | 194 | terraformCmd.AddCommand(outputCmd) |
32 | 195 | } |
0 commit comments