### Example Usage of Config Validation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Demonstrates how to unmarshal JSON into a Config object and then validate it. This is useful for ensuring configuration integrity after loading. ```go config := &tfjson.Config{} if err := json.Unmarshal(configJSON, config); err != nil { log.Fatal(err) } if err := config.Validate(); err != nil { log.Fatal("Invalid config:", err) } ``` -------------------------------- ### Unmarshal and Validate ProviderSchemas Example Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-schemas.md Demonstrates how to unmarshal JSON data into ProviderSchemas and then validate the resulting object. This is a common pattern for loading and verifying schema configurations. ```go schemas := &tfjson.ProviderSchemas{} if err := json.Unmarshal(schemasJSON, schemas); err != nil { log.Fatal(err) } if err := schemas.Validate(); err != nil { log.Fatal("Invalid schemas:", err) } ``` -------------------------------- ### Parse and Validate Terraform Function Signatures Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md This example shows how to unmarshal Terraform metadata functions JSON, validate it, and then iterate through function names, summaries, and parameter details. Ensure metadataData is populated correctly. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func main() { var metadataData []byte // ... read metadata from terraform metadata functions -json ... metadata := &tfjson.MetadataFunctions{} if err := json.Unmarshal(metadataData, metadata); err != nil { log.Fatal(err) } if err := metadata.Validate(); err != nil { log.Fatal(err) } for funcName, sig := range metadata.Signatures { log.Printf("Function %s: %s", funcName, sig.Summary) for _, param := range sig.Parameters { log.Printf(" Parameter %s: %v (nullable: %v)", param.Name, param.Type, param.IsNullable) } } } ``` -------------------------------- ### Range Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Represents a specific range of bytes within a configuration file, defined by start and end positions. Includes the filename for context. ```go type Range struct { Filename string Start Pos End Pos } ``` -------------------------------- ### Range Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Represents a specific range of bytes within a configuration file, defined by start and end positions. ```APIDOC ## Range ### Description Represents a range of bytes between two positions in a configuration file. ### Fields * **Filename** (`string`) - The name of the configuration file. * **Start** (`Pos`) - The starting position of the range. * **End** (`Pos`) - The ending position of the range. ``` -------------------------------- ### Unmarshal and Validate Terraform State JSON Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-state.md Example demonstrating how to unmarshal Terraform state JSON into a State object and validate it. This is useful for processing state files programmatically. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func main() { var stateData []byte // ... read state JSON from file or source ... state := &tfjson.State{} if err := json.Unmarshal(stateData, state); err != nil { log.Fatal(err) } if err := state.Validate(); err != nil { log.Fatal(err) } for address, output := range state.Values.Outputs { log.Printf("Output %s: %v (sensitive: %v)", address, output.Value, output.Sensitive) } } ``` -------------------------------- ### Handling NilPlanError Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md Demonstrates how to check for and handle the `NilPlanError` when sanitizing a plan. ```go sanitized, err := sanitize.SanitizePlan(plan) if err == sanitize.NilPlanError { log.Fatal("Cannot sanitize nil plan") } ``` -------------------------------- ### Iterate Through Resource Changes in a Plan Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/README.md Loop through plan.ResourceChanges to access individual resource modifications. Check change actions (Create, Update, Delete) and access Before/After state values. ```go for _, change := range plan.ResourceChanges { // Check change type if change.Change.Actions.Create() { // Handle creation } // Access before/after values if change.Change.Before != nil { // Process previous state } if change.Change.After != nil { // Process new state } } ``` -------------------------------- ### Basic Plan Initialization Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Initializes a Terraform plan from JSON data. Ensures the plan is unmarshaled and validated correctly. Requires importing encoding/json and log. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func main() { var planData []byte // ... read plan JSON ... plan := &tfjson.Plan{} if err := json.Unmarshal(planData, plan); err != nil { log.Fatal(err) } if err := plan.Validate(); err != nil { log.Fatal(err) } // Use plan } ``` -------------------------------- ### Parse Terraform Plan and Log Resource Changes Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Demonstrates how to parse Terraform plan JSON data and iterate through resource changes to log creation, update, deletion, or replacement actions. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func main() { var planData []byte // ... read plan JSON from terraform show -json ... plan := &tfjson.Plan{} if err := json.Unmarshal(planData, plan); err != nil { log.Fatal(err) } for _, resourceChange := range plan.ResourceChanges { switch { case resourceChange.Change.Actions.Create(): log.Printf("Create: %s", resourceChange.Address) case resourceChange.Change.Actions.Update(): log.Printf("Update: %s", resourceChange.Address) case resourceChange.Change.Actions.Delete(): log.Printf("Delete: %s", resourceChange.Address) case resourceChange.Change.Actions.Replace(): log.Printf("Replace: %s", resourceChange.Address) } } } ``` -------------------------------- ### Validate Method Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-plan.md Checks if the plan is present and its format version is supported by the library. Returns an error if validation fails. ```go func (p *Plan) Validate() error ``` ```go plan := &tfjson.Plan{} if err := json.Unmarshal(planJSON, plan); err != nil { log.Fatal(err) } if err := plan.Validate(); err != nil { log.Fatal("Invalid plan:", err) } ``` -------------------------------- ### Plan Initialization with Validation Checks Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Initializes a Terraform plan, performing JSON parsing, format validation, and checks for essential data like format version and resource changes. Returns an error if validation fails. ```go import ( "encoding/json" "fmt" "log" tfjson "github.com/hashicorp/terraform-json" ) func initializePlan(data []byte) (*tfjson.Plan, error) { plan := &tfjson.Plan{} // Parse JSON if err := json.Unmarshal(data, plan); err != nil { return nil, fmt.Errorf("JSON parse error: %w", err) } // Validate format if err := plan.Validate(); err != nil { return nil, fmt.Errorf("validation error: %w", err) } // Check for key data if plan.FormatVersion == "" { return nil, fmt.Errorf("plan missing format version") } if len(plan.ResourceChanges) == 0 { log.Println("Warning: plan contains no resource changes") } return plan, nil } ``` -------------------------------- ### Main Package Import Path Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/README.md Import the main terraform-json package to access core types and functions. ```go import tfjson "github.com/hashicorp/terraform-json" ``` -------------------------------- ### Handle 'unexpected provider schema data, format version is missing' Error Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This code demonstrates handling errors where the 'format_version' field is missing in the provider schema data. This indicates that the input JSON is incomplete or malformed. ```go // Trigger: ProviderSchemas.Validate() when FormatVersion field is empty // Location: schemas.go:42 ``` -------------------------------- ### Check for Destroy Before Create Operation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Returns true if the Actions indicate a destroy-before-create operation, which is the standard method for resource replacement. ```go func (a Actions) DestroyBeforeCreate() bool { return false } ``` -------------------------------- ### Check for Create Action Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Determines if the current set of Actions indicates a resource creation operation. ```go func (a Actions) Create() bool { return false } ``` -------------------------------- ### ValidateOutput.Validate Method Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Checks if the configuration data is present and the version matches the library's supported version. Returns nil if valid; otherwise, returns an error. ```go func (vo *ValidateOutput) Validate() error ``` -------------------------------- ### CheckDynamicAddress Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-checks.md Contains the instance key for resources that have multiple instances, providing a way to uniquely identify them. ```APIDOC ## Struct: CheckDynamicAddress ### Description Provides the instance key for resources that can have multiple instances, typically used in dynamic expansions. ### Fields - **ToDisplay** (string) - Required - Formatted, display-ready full address including instance info. - **Module** (string) - Required - Module part including instance keys from foreach/count. - **InstanceKey** (interface{}) - Required - Instance key for multi-instance resources. ``` -------------------------------- ### ProviderConfig Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Describes a single provider configuration instance, including its name, alias, and version constraints. ```go type ProviderConfig struct { Name string FullName string Alias string ModuleAddress string Expressions map[string]*Expression VersionConstraint string } ``` -------------------------------- ### Validate Config Method Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Checks if the configuration is present and not nil. Returns an error if the config is nil. ```go func (c *Config) Validate() error ``` -------------------------------- ### Custom Sensitive Value Replacement Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Demonstrates how to use a custom string to replace sensitive values during plan sanitization. Requires importing the sanitize package. ```go import ( tfjson "github.com/hashicorp/terraform-json" "github.com/hashicorp/terraform-json/sanitize" ) // Use a custom replacement sanitized, err := sanitize.SanitizePlanWithValue(plan, "[HIDDEN]") ``` -------------------------------- ### Parse and Validate Terraform Configuration Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Demonstrates how to unmarshal Terraform configuration data from JSON, validate it, and iterate through resources and provider configurations using the terraform-json library in Go. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func main() { var configData []byte // ... read configuration from plan JSON ... config := &tfjson.Config{} if err := json.Unmarshal(configData, config); err != nil { log.Fatal(err) } if err := config.Validate(); err != nil { log.Fatal(err) } for _, resource := range config.RootModule.Resources { log.Printf("Resource %s.%s (type: %s)", resource.Name, resource.Type, resource.Mode) } for providerKey, providerConfig := range config.ProviderConfigs { log.Printf("Provider: %s (alias: %s, version: %s)", providerConfig.Name, providerConfig.Alias, providerConfig.VersionConstraint) } } ``` -------------------------------- ### Define Plan Format Version Constraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Specifies the supported versions of the JSON plan format using semantic versioning. Plans within this constraint will pass validation. ```go var PlanFormatVersionConstraints = ">= 0.1, < 2.0" ``` -------------------------------- ### Sanitization Subpackage Import Path Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/README.md Import the sanitize subpackage for data sanitization functionalities. ```go import sanitize "github.com/hashicorp/terraform-json/sanitize" ``` -------------------------------- ### Define a Configuration Variable Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Represents a variable as it appears in Terraform configuration. Use this to define default values, descriptions, and sensitivity. ```Go type ConfigVariable struct { Default interface{} Description string Sensitive bool } ``` -------------------------------- ### ValidateOutput.Validate Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Checks if the configuration data is present and if the version matches the library's supported version. It returns an error if validation fails. ```APIDOC ## ValidateOutput.Validate ### Description Checks to ensure that data is present and the version matches the version supported by this library. Returns nil if valid. ### Method * Method Signature: `func (vo *ValidateOutput) Validate() error` ### Return Type * `error` — Returns nil if valid. Note: The format was not versioned in earlier releases, so missing format version returns nil. ``` -------------------------------- ### ConfigResource Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Represents a resource in its configuration form. This struct includes details about the resource's address, type, name, provisioners, and expressions. ```go type ConfigResource struct { Address string Mode ResourceMode Type string Name string ProviderConfigKey string Provisioners []*ConfigProvisioner Expressions map[string]*Expression SchemaVersion uint64 CountExpression *Expression ForEachExpression *Expression DependsOn []string } ``` -------------------------------- ### Load Plan with Chained Errors Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This Go function illustrates how to load a Terraform plan file, read its content, unmarshal it, and validate it, chaining errors with context at each step. ```go import ( "fmt" ) func loadPlan(path string) (*tfjson.Plan, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("cannot read plan file %s: %w", path, err) } plan := &tfjson.Plan{} if err := json.Unmarshal(data, plan); err != nil { return nil, fmt.Errorf("plan file %s has invalid JSON: %w", path, err) } if err := plan.Validate(); err != nil { return nil, fmt.Errorf("plan file %s failed validation: %w", path, err) } return plan, nil } ``` -------------------------------- ### ActionInvocation Structure Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Defines an action invocation in the plan, including its address, type, name, configuration values, provider, and trigger details. ```go type ActionInvocation struct { Address string Type string Name string ConfigValues interface{} ConfigSensitive interface{} ConfigUnknown interface{} ProviderName string LifecycleActionTrigger *LifecycleActionTrigger InvokeActionTrigger *InvokeActionTrigger } ``` -------------------------------- ### Recommended JSON Plan Parsing Pattern Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md A robust pattern for parsing and validating Terraform JSON plans, including specific handling for JSON syntax errors. ```go import ( "encoding/json" "log" "errors" tfjson "github.com/hashicorp/terraform-json" ) func parsePlan(data []byte) (*tfjson.Plan, error) { plan := &tfjson.Plan{} // Parse JSON if err := json.Unmarshal(data, plan); err != nil { var syntaxErr *json.SyntaxError if errors.As(err, &syntaxErr) { return nil, errors.New("plan JSON has syntax error at byte offset " + string(rune(syntaxErr.Offset))) } return nil, err } // Validate format if err := plan.Validate(); err != nil { return nil, err } return plan, nil } ``` -------------------------------- ### Importing Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Defines the structure for resource import metadata, including the original ID, whether it was unknown at plan time, and an alternative identity. ```go type Importing struct { ID string Unknown bool Identity interface{} } ``` -------------------------------- ### Process Single Log Line Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-logging.md Demonstrates how to unmarshal a single JSON log line and log its level, message, and timestamp. This is useful for basic log inspection. ```go import ( "log" tfjson "github.com/hashicorp/terraform-json" ) func processLogLine(line []byte) error { msg, err := tfjson.UnmarshalLogMessage(line) if err != nil { return err } log.Printf("[%s] %s @ %v", msg.Level(), msg.Message(), msg.Timestamp()) return nil } ``` -------------------------------- ### Define Provider Schemas Format Version Constraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Specifies the supported versions of the JSON provider schema format using semantic versioning. Plans within this constraint will pass validation. ```go var ProviderSchemasFormatVersionConstraints = ">= 0.1, < 2.0" ``` -------------------------------- ### Log Sanitized Plan Details Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-sanitize.md Unmarshals plan JSON, sanitizes it, and logs resource addresses and 'After' values. Useful for inspecting sanitized plan outputs without exposing sensitive data. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" "github.com/hashicorp/terraform-json/sanitize" ) func logPlan(planJSON []byte) error { plan := &tfjson.Plan{} if err := json.Unmarshal(planJSON, plan); err != nil { return err } sanitized, err := sanitize.SanitizePlan(plan) if err != nil { return err } // Safe to log for _, change := range sanitized.ResourceChanges { log.Printf("Resource: %s", change.Address) if change.Change.After != nil { log.Printf(" After: %v", change.Change.After) } } return nil } ``` -------------------------------- ### PlanFormatVersionConstraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Defines the versions of the JSON plan format that are supported by this package. Uses semantic version constraint syntax. ```APIDOC ## PlanFormatVersionConstraints ### Description Defines the versions of the JSON plan format that are supported by this package. Uses semantic version constraint syntax. ### Compatibility Plans with FormatVersion matching this constraint will pass validation. Terraform plans from versions 0.1.x and 1.x are supported; 2.0+ are not. ``` -------------------------------- ### Describe a Configuration Provisioner Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Defines a provisioner declared within a Terraform resource configuration. It includes the provisioner type and its configuration expressions. ```Go type ConfigProvisioner struct { Type string Expressions map[string]*Expression } ``` -------------------------------- ### Sanitize All Plans in a Directory Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-sanitize.md Reads all JSON files in a directory, unmarshals them as Terraform plans, sanitizes each plan, and writes the sanitized version to a new file prefixed with 'sanitized_'. Handles potential errors during file reading, unmarshalling, and sanitization by continuing to the next file. ```go import ( "encoding/json" "io/ioutil" "path/filepath" tfjson "github.com/hashicorp/terraform-json" "github.com/hashicorp/terraform-json/sanitize" ) func sanitizePlanDirectory(dir string) error { files, err := ioutil.ReadDir(dir) if err != nil { return err } for _, file := range files { if filepath.Ext(file.Name()) != ".json" { continue } planData, err := ioutil.ReadFile(filepath.Join(dir, file.Name())) if err != nil { continue } plan := &tfjson.Plan{} if err := json.Unmarshal(planData, plan); err != nil { continue } sanitized, err := sanitize.SanitizePlan(plan) if err != nil { continue } // Write sanitized plan outPath := filepath.Join(dir, "sanitized_"+file.Name()) sanitizedData, _ := json.MarshalIndent(sanitized, "", " ") ioutil.WriteFile(outPath, sanitizedData, 0644) } return nil } ``` -------------------------------- ### Plan Initialization with JSON Number Precision Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Initializes a Terraform plan, enabling JSON number precision before unmarshaling. Numbers are treated as json.Number, accessible via the .String() method. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func main() { var planData []byte // ... read plan JSON ... plan := &tfjson.Plan{} plan.UseJSONNumber(true) // Enable before unmarshaling if err := json.Unmarshal(planData, plan); err != nil { log.Fatal(err) } if err := plan.Validate(); err != nil { log.Fatal(err) } // Numbers are now json.Number, not float64 // Use .String() method to get string representation } ``` -------------------------------- ### CheckDynamicAddress Struct Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-checks.md Holds the instance key for resources that can have multiple instances. This is used to construct the relative address of a dynamic object. ```go type CheckDynamicAddress struct { ToDisplay string Module string InstanceKey interface{} } ``` -------------------------------- ### Handle 'unsupported provider schema format version' Error Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This code snippet addresses errors related to unsupported provider schema format versions, indicating incompatibility between the Terraform version and the library. It checks if the 'format_version' meets the defined constraints. ```go // Trigger: ProviderSchemas.Validate() when FormatVersion doesn't match ProviderSchemasFormatVersionConstraints (>= 0.1, < 2.0) // Location: schemas.go:56 ``` -------------------------------- ### ConfigOutput Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Represents an output value as defined in Terraform configuration. It includes details about sensitivity, the expression defining its value, a description, and any explicit dependencies. ```APIDOC ## ConfigOutput ### Description Defines an output as it appears in configuration. It includes details about sensitivity, the expression defining its value, a description, and any explicit dependencies. ### Fields - **Sensitive** (bool) - Whether output was marked as sensitive - **Expression** (*Expression) - Defined value of the output - **Description** (string) - Defined description of the output - **DependsOn** ([]string) - Defined dependencies for the output ``` -------------------------------- ### Check for Create Before Destroy Operation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Returns true if the Actions indicate a create-before-destroy operation, typically resulting from the 'create_before_destroy' lifecycle option. ```go func (a Actions) CreateBeforeDestroy() bool { return false } ``` -------------------------------- ### Describe a Module Call in Configuration Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Represents a declared 'module' within a Terraform configuration. Use this to specify the module source, expressions, version constraints, and dependencies. ```Go type ModuleCall struct { Source string Expressions map[string]*Expression CountExpression *Expression ForEachExpression *Expression Module *ConfigModule VersionConstraint string DependsOn []string } ``` -------------------------------- ### MetadataFunctionsFormatVersionConstraints Constant Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Defines the supported version constraints for the metadata functions format. This constant specifies the acceptable version range. ```go const MetadataFunctionsFormatVersionConstraints = "~> 1.0" ``` -------------------------------- ### Define Metadata Functions Format Version Constraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Specifies the supported versions of the JSON metadata functions format using compatible versioning (`~> 1.0`). Plans within this constraint will pass validation. ```go var MetadataFunctionsFormatVersionConstraints = "~> 1.0" ``` -------------------------------- ### Define State Format Version Constraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Specifies the supported versions of the JSON state format using semantic versioning. Plans within this constraint will pass validation. ```go var StateFormatVersionConstraints = ">= 0.1, < 2.0" ``` -------------------------------- ### Check for Valid Replacement Operation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Determines if the Actions represent a valid replacement operation, which can be either destroy-before-create or create-before-destroy. ```go func (a Actions) Replace() bool { return false } ``` -------------------------------- ### ConfigOutput Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Defines an output as it appears in configuration. Used to represent output variables within Terraform configuration files. ```go type ConfigOutput struct { Sensitive bool Expression *Expression Description string DependsOn []string } ``` -------------------------------- ### Process Terraform Plan Checks Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/README.md Iterate through plan.Checks to identify and log details of failed checks. Access check status, address, and specific problems within instances. ```go for _, check := range plan.Checks { if check.Status == tfjson.CheckStatusFail { log.Printf("Check failed: %s", check.Address.ToDisplay) for _, instance := range check.Instances { for _, problem := range instance.Problems { log.Printf(" Problem: %s", problem.Message) } } } } ``` -------------------------------- ### Change Structure Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Represents a proposed change for an object, detailing actions, before and after states, and sensitive values. It also includes information about imports and generated configuration. ```go type Change struct { Actions Actions Before interface{} After interface{} AfterUnknown interface{} BeforeSensitive interface{} AfterSensitive interface{} Importing *Importing GeneratedConfig string ReplacePaths []interface{} BeforeIdentity interface{} AfterIdentity interface{} } ``` -------------------------------- ### ConfigProvisioner Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Describes a provisioner declared in a resource configuration. It specifies the provisioner type and its associated configuration expressions. ```APIDOC ## ConfigProvisioner ### Description Describes a provisioner declared in a resource configuration. ### Fields - **Type** (string) - Provisioner type (e.g., "local-exec") - **Expressions** (map[string]*Expression) - Configuration values indexed by key ``` -------------------------------- ### Importing Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Represents metadata for resource import operations. It includes the original ID, a flag indicating if the ID was unknown at plan time, and an alternative identity if available. ```APIDOC ## Importing ### Description Represents metadata for resource import operations. It includes the original ID, a flag indicating if the ID was unknown at plan time, and an alternative identity if available. ### Fields - **ID** (string) - Original ID used to target resource in import - **Unknown** (bool) - Whether ID/identity was unknown at plan time - **Identity** (interface{}) - Identity that can be used instead of ID ``` -------------------------------- ### Handle 'unexpected state input, format version is missing' Error Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This code snippet addresses the error where the 'format_version' field is missing in the state input during validation. This indicates malformed or incomplete state JSON. ```go // Trigger: State.Validate() when FormatVersion field is empty // Location: state.go:60 ``` -------------------------------- ### Validate Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-plan.md Checks to ensure that the plan is present and the version matches the version supported by this library. ```APIDOC ## Validate ### Description Checks to ensure that the plan is present and the version matches the version supported by this library. ### Method func (p *Plan) Validate() error ### Return Type error — Returns nil if valid, or an error describing the validation failure. ### Throws/Rejects - If plan is nil: "plan is nil" - If format version is missing: "unexpected plan input, format version is missing" - If format version is invalid: "invalid format version..." - If version constraint is unsupported: "unsupported plan format version..." ### Request Example ```go plan := &tfjson.Plan{} if err := json.Unmarshal(planJSON, plan); err != nil { log.Fatal(err) } if err := plan.Validate(); err != nil { log.Fatal("Invalid plan:", err) } ``` ``` -------------------------------- ### ActionInvocation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Represents an action invocation in the plan. It includes details about the action's address, type, name, configuration, provider, and triggers. ```APIDOC ## ActionInvocation ### Description Represents an action invocation in the plan. It includes details about the action's address, type, name, configuration, provider, and triggers. ### Fields - **Address** (string) - Absolute action address - **Type** (string) - Type of the action - **Name** (string) - Name of the action - **ConfigValues** (interface{}) - JSON representation of action config values - **ConfigSensitive** (interface{}) - Sensitivity metadata for config values - **ConfigUnknown** (interface{}) - Unknown metadata for config values - **ProviderName** (string) - Provider name (allows disambiguation) - **LifecycleActionTrigger** (*LifecycleActionTrigger) - Lifecycle action trigger details - **InvokeActionTrigger** (*InvokeActionTrigger) - Invoke action trigger details ``` -------------------------------- ### Plan Type Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-plan.md Defines the structure for parsing Terraform plan JSON output. ```go type Plan struct { FormatVersion string TerraformVersion string Variables map[string]*PlanVariable PlannedValues *StateValues ResourceDrift []*ResourceChange ResourceChanges []*ResourceChange DeferredChanges []*DeferredResourceChange Complete *bool OutputChanges map[string]*Change PriorState *State Config *Config RelevantAttributes []ResourceAttribute Checks []CheckResultStatic Timestamp string ActionInvocations []*ActionInvocation } ``` -------------------------------- ### Process Output Changes in a Terraform Plan Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/README.md Iterate over plan.OutputChanges to access information about Terraform outputs. Log output names and identify sensitive outputs. ```go for name, output := range plan.OutputChanges { log.Printf("Output: %s", name) if output.AfterSensitive != nil { log.Printf(" (sensitive)") } } ``` -------------------------------- ### Pos Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Represents a position in a configuration file, including line, column, and byte offset. ```Go type Pos struct { Line int Column int Byte int } ``` -------------------------------- ### Actions Type and Constants Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Defines the Actions type as a slice of Action, along with constants for various action types like no-op, create, read, update, delete, and forget. ```go type Actions []Action type Action string const ( ActionNoop Action = "no-op" ActionCreate Action = "create" ActionRead Action = "read" ActionUpdate Action = "update" ActionDelete Action = "delete" ActionForget Action = "forget" ) ``` -------------------------------- ### Config.Validate Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Checks to ensure that the config is present. Currently only verifies the config is not nil. ```APIDOC ## Config.Validate ### Description Checks to ensure that the config is present. Currently only verifies the config is not nil. ### Method func (c *Config) Validate() error ### Return Type error — Returns nil if valid, or "config is nil" if the config is nil. ### Example ```go config := &tfjson.Config{} if err := json.Unmarshal(configJSON, config); err != nil { log.Fatal(err) } if err := config.Validate(); err != nil { log.Fatal("Invalid config:", err) } ``` ``` -------------------------------- ### ModuleCall Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Details a declared 'module' within a configuration, including its source, expressions, count, for_each, version constraint, and dependencies. ```APIDOC ## ModuleCall ### Description Describes a declared "module" within a configuration, including the module's data. ### Fields - **Source** (string) - Contents of the "source" field - **Expressions** (map[string]*Expression) - Configuration values indexed by key - **CountExpression** (*Expression) - Expression for "count" value - **ForEachExpression** (*Expression) - Expression for "for_each" value - **Module** (*ConfigModule) - Configuration data for the module itself - **VersionConstraint** (string) - Version constraint for registry modules - **DependsOn** ([]string) - Explicit resource dependencies ``` -------------------------------- ### DeferredResourceChange Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Represents a resource change that has been deferred, including the reason for deferral and details of the resource change itself. ```go type DeferredResourceChange struct { Reason string ResourceChange *ResourceChange } ``` -------------------------------- ### Inspect Terraform Resource Changes Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/README.md Iterate through resource changes in a parsed Terraform plan to identify actions like create, update, delete, or replace. ```go import ( tfjson "github.com/hashicorp/terraform-json" ) // From a parsed plan: for _, change := range plan.ResourceChanges { switch { case change.Change.Actions.Create(): log.Printf("Create: %s", change.Address) case change.Change.Actions.Update(): log.Printf("Update: %s", change.Address) case change.Change.Actions.Delete(): log.Printf("Delete: %s", change.Address) case change.Change.Actions.Replace(): log.Printf("Replace: %s", change.Address) } } ``` -------------------------------- ### Config Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-config.md Defines the structure for the complete Terraform configuration, including provider configurations and the root module. ```go type Config struct { ProviderConfigs map[string]*ProviderConfig RootModule *ConfigModule } ``` -------------------------------- ### Handle 'unsupported validation output format version' Error Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This code snippet shows how to handle errors for unsupported validation output format versions. This occurs when the 'format_version' does not meet the library's constraints, indicating potential incompatibility with the Terraform version. ```go // Trigger: ValidateOutput.Validate() when FormatVersion doesn't match ValidateFormatVersionConstraints (>= 0.1, < 2.0) // Location: validate.go:135 ``` -------------------------------- ### Collect Instance-Level Problems Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-checks.md Extracts and collects all problem messages from all instances within a given check result. Formats the output to include the instance's display address. Requires the tfjson package. ```go import ( tfjson "github.com/hashicorp/terraform-json" ) func collectAllProblems(checkResult *tfjson.CheckResultStatic) []string { var problems []string for _, instance := range checkResult.Instances { for _, problem := range instance.Problems { problems = append(problems, instance.Address.ToDisplay + ": " + problem.Message) } } return problems } ``` -------------------------------- ### Handle 'unsupported plan format version' Error in Terraform Plan Validation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This code demonstrates how to handle errors indicating an unsupported plan format version, typically due to incompatibility between Terraform and library versions. It checks for the 'unsupported plan format version' error message. ```go if err := plan.Validate(); err != nil { if strings.Contains(err.Error(), "unsupported plan format version") { log.Fatal("Plan from newer Terraform version is not supported") } } ``` -------------------------------- ### Check for Read Action Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Determines if the current set of Actions signifies a read-only operation. ```go func (a Actions) Read() bool { return false } ``` -------------------------------- ### ProviderSchemasFormatVersionConstraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Defines the versions of the JSON provider schema format that are supported by this package. ```APIDOC ## ProviderSchemasFormatVersionConstraints ### Description Defines the versions of the JSON provider schema format that are supported by this package. ``` -------------------------------- ### Actions Methods Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Provides methods to check the nature of a set of Actions, such as whether they represent a no-op, creation, read, update, delete, or replacement operation. ```APIDOC ## Actions Methods ### NoOp #### Description Returns true if this set of Actions denotes a no-op. #### Return Type bool ### Create #### Description Returns true if this set of Actions denotes creation of a new resource. #### Return Type bool ### Read #### Description Returns true if this set of Actions denotes a read operation only. #### Return Type bool ### Update #### Description Returns true if this set of Actions denotes an update operation. #### Return Type bool ### Delete #### Description Returns true if this set of Actions denotes resource removal. #### Return Type bool ### DestroyBeforeCreate #### Description Returns true if this set of Actions denotes a destroy-before-create operation (standard resource replacement method). #### Return Type bool ### CreateBeforeDestroy #### Description Returns true if this set of Actions denotes a create-before-destroy operation (usually from `create_before_destroy` lifecycle option). #### Return Type bool ### Replace #### Description Returns true if this set of Actions denotes a valid replacement operation (either destroy-before-create or create-before-destroy). #### Return Type bool ### Forget #### Description Returns true if this set of Actions denotes a forget operation. #### Return Type bool ``` -------------------------------- ### Define SchemaDescriptionKind Enum Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/types.md Describes the format of a description field within schema blocks and attributes. Supports plain text or markdown. ```go type SchemaDescriptionKind string const ( SchemaDescriptionKindPlain SchemaDescriptionKind = "plain" SchemaDescriptionKindMarkdown SchemaDescriptionKind = "markdown" ) ``` -------------------------------- ### Access Terraform Provider Schema Information Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/README.md Iterate through schemas.Schemas to access provider and resource schema details. Log provider names, resource types, and schema versions. ```go for providerName, providerSchema := range schemas.Schemas { for resourceType, resourceSchema := range providerSchema.ResourceSchemas { log.Printf("Resource: %s/%s (version %d)", providerName, resourceType, resourceSchema.Version) } } ``` -------------------------------- ### Define Validate Format Version Constraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Specifies the supported versions of the JSON validate format using semantic versioning. Plans within this constraint will pass validation. ```go var ValidateFormatVersionConstraints = ">= 0.1, < 2.0" ``` -------------------------------- ### StateFormatVersionConstraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Defines the versions of the JSON state format that are supported by this package. ```APIDOC ## StateFormatVersionConstraints ### Description Defines the versions of the JSON state format that are supported by this package. ``` -------------------------------- ### Define Diagnostic Severity Levels in Go Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/types.md Defines the `DiagnosticSeverity` string type and its constants for representing the severity of diagnostic messages. Includes an unknown state for future compatibility. ```go type DiagnosticSeverity string const ( DiagnosticSeverityUnknown DiagnosticSeverity = "unknown" DiagnosticSeverityError DiagnosticSeverity = "error" DiagnosticSeverityWarning DiagnosticSeverity = "warning" ) ``` -------------------------------- ### DeferredResourceChange Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Describes a resource change that has been deferred, including the reason for deferral and the details of the resource change itself. ```APIDOC ## DeferredResourceChange ### Description Describes a resource change that has been deferred, including the reason for deferral and the details of the resource change itself. ### Fields - **Reason** (string) - Reason why this change was deferred - **ResourceChange** (*ResourceChange) - Information about the deferred change ``` -------------------------------- ### LifecycleActionTrigger Structure Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Details a lifecycle action trigger, specifying the resource address, event, and indices related to the trigger. ```go type LifecycleActionTrigger struct { TriggeringResourceAddress string ActionTriggerEvent string ActionTriggerBlockIndex int ActionsListIndex int } ``` -------------------------------- ### Define ResourceAttribute Struct Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Describes a struct representing a full path to a resource attribute, including the resource address and attribute path. ```go type ResourceAttribute struct { Resource string Attribute []json.RawMessage } ``` -------------------------------- ### MetadataFunctionsFormatVersionConstraints Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/configuration.md Defines the versions of the JSON metadata functions format that are supported by this package. Uses compatible version constraint (~> 1.0 means >= 1.0.0, < 2.0.0). ```APIDOC ## MetadataFunctionsFormatVersionConstraints ### Description Defines the versions of the JSON metadata functions format that are supported by this package. Uses compatible version constraint (~> 1.0 means >= 1.0.0, < 2.0.0). ``` -------------------------------- ### ResourceChange Structure Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Defines an individual change action Terraform plans to execute. It includes details like address, mode, type, and the associated Change object. ```go type ResourceChange struct { Address string PreviousAddress string ModuleAddress string Mode ResourceMode Type string Name string Index interface{} ProviderName string DeposedKey string Change *Change } ``` -------------------------------- ### Diagnostic Struct Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Defines the structure for representing information about errors or anomalies during configuration parsing or evaluation. Includes severity, summary, detail, and location. ```go type Diagnostic struct { Severity DiagnosticSeverity Summary string Detail string Range *Range Snippet *DiagnosticSnippet } ``` -------------------------------- ### Analyze Check Results from Plan Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-checks.md Iterates through all checks and their instances within a Terraform plan, logging details about each check, instance, and any associated problems. Requires the tfjson package. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func analyzeChecks(plan *tfjson.Plan) { for _, checkResult := range plan.Checks { log.Printf("Check: %s (kind: %s, status: %s)", checkResult.Address.ToDisplay, checkResult.Address.Kind, checkResult.Status) for _, instance := range checkResult.Instances { log.Printf(" Instance: %s (status: %s)", instance.Address.ToDisplay, instance.Status) for _, problem := range instance.Problems { log.Printf(" Problem: %s", problem.Message) } } } } ``` -------------------------------- ### Validate Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-state.md Checks to ensure that the state is present and the version matches the version supported by this library. Returns nil if valid, or an error describing the validation failure. ```APIDOC ## Validate ### Description Validates the state to ensure it is present and its format version is supported by the library. ### Method `Validate` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go state := &tfjson.State{} if err := json.Unmarshal(stateJSON, state); err != nil { log.Fatal(err) } if err := state.Validate(); err != nil { log.Fatal("Invalid state:", err) } ``` ### Response #### Success Response `nil` if the state is valid. #### Response Example None ### Error Handling - If state is nil: "state is nil" - If format version is missing: "unexpected state input, format version is missing" - If format version is invalid: "invalid format version..." - If version constraint is unsupported: "unsupported state format version..." ``` -------------------------------- ### Define Action Type Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/types.md Defines the 'Action' string type and its constants representing various resource change operations like create, read, update, delete, and no-op. This type is fundamental for understanding resource change operations. ```Go type Action string const ( ActionNoop Action = "no-op" ActionCreate Action = "create" ActionRead Action = "read" ActionUpdate Action = "update" ActionDelete Action = "delete" ActionForget Action = "forget" ) ``` -------------------------------- ### Check for Update Action Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Determines if the current set of Actions indicates a resource update operation. ```go func (a Actions) Update() bool { return false } ``` -------------------------------- ### Handle 'provider schema data is nil' Error in Provider Schema Validation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This code snippet addresses the 'provider schema data is nil' error, which occurs when validating provider schemas and the schemas object itself is nil. ```go // Trigger: ProviderSchemas.Validate() when schemas is nil // Location: schemas.go:38 ``` -------------------------------- ### SanitizePlanWithValue Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-sanitize.md Sanitizes the entirety of a Plan to the best of its ability based on provided metadata on sensitive values. Sensitive values are replaced with the value supplied with `replaceWith`. ```APIDOC ## SanitizePlanWithValue ### Description Sanitizes the entirety of a Plan to the best of its ability based on provided metadata on sensitive values. Sensitive values are replaced with the value supplied with `replaceWith`. ### Method ```go func SanitizePlanWithValue(old *tfjson.Plan, replaceWith interface{}) (*tfjson.Plan, error) ``` ### Parameters #### Path Parameters - **old** (*tfjson.Plan) - Required - Plan to sanitize - **replaceWith** (interface{}) - Required - Value to replace sensitive data with ### Response #### Success Response - `(*tfjson.Plan, error)` - A copy of the plan with sensitive values redacted. ### Throws/Rejects - If plan is nil: `NilPlanError` - If copying fails - If component sanitization fails ### Example ```go import ( "log" "encoding/json" tfjson "github.com/hashicorp/terraform-json" "github.com/hashicorp/terraform-json/sanitize" ) func main() { var planData []byte // ... read plan JSON ... plan := &tfjson.Plan{} if err := json.Unmarshal(planData, plan); err != nil { log.Fatal(err) } customReplacement := map[string]interface{}{"redacted": true} sanitized, err := sanitize.SanitizePlanWithValue(plan, customReplacement) if err != nil { log.Fatal(err) } // Export sanitized plan data, _ := json.Marshal(sanitized) log.Print(string(data)) } ``` ``` -------------------------------- ### Check for Delete Action Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-changes.md Determines if the current set of Actions signifies a resource deletion operation. ```go func (a Actions) Delete() bool { return false } ``` -------------------------------- ### Analyze Terraform Expressions Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-expressions.md Use this function to inspect the properties of a Terraform expression, such as constant values, references, and nested blocks. It handles nil expressions gracefully. ```go import ( "encoding/json" "log" tfjson "github.com/hashicorp/terraform-json" ) func analyzeExpression(expr *tfjson.Expression) { if expr == nil { return } if expr.ConstantValue != nil && expr.ConstantValue != tfjson.UnknownConstantValue { log.Printf("Constant value: %v", expr.ConstantValue) } if expr.ConstantValue == tfjson.UnknownConstantValue { log.Printf("Unknown, references: %v", expr.References) } if len(expr.NestedBlocks) > 0 { log.Printf("Nested blocks: %d", len(expr.NestedBlocks)) } } ``` -------------------------------- ### Handle 'unsupported state format version' Error in Terraform State Validation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This snippet shows how to handle errors related to unsupported state format versions, which occur when the 'format_version' does not meet the library's constraints. This usually implies an incompatible Terraform version. ```go // Trigger: State.Validate() when FormatVersion doesn't match StateFormatVersionConstraints (>= 0.1, < 2.0) // Location: state.go:75 ``` -------------------------------- ### CheckStaticAddress Structure Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/api-reference-checks.md Details the static address of an object that performed a check, including its display representation, kind, module, mode, type, and name. ```Go type CheckStaticAddress struct { ToDisplay string Kind CheckKind Module string Mode ResourceMode Type string Name string } ``` -------------------------------- ### NilPlanError Definition Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This error is returned when `SanitizePlan` or `SanitizePlanWithValue` is called with a nil plan. ```go var NilPlanError = errors.New("nil plan supplied") ``` -------------------------------- ### Handle 'validation output is nil' Error in ValidateOutput Validation Source: https://github.com/hashicorp/terraform-json/blob/main/_autodocs/errors.md This snippet demonstrates handling the 'validation output is nil' error when validating a ValidateOutput object. This error occurs if the output object itself is nil. ```go // Trigger: ValidateOutput.Validate() when output is nil // Location: validate.go:114 ```