2023-05-02 11:33:06 -04:00
// Copyright IBM Corp. 2014, 2026
2023-08-10 18:43:27 -04:00
// SPDX-License-Identifier: BUSL-1.1
2023-05-02 11:33:06 -04:00
2015-11-05 09:47:08 -05:00
package command
import (
"fmt"
2026-02-16 05:09:26 -05:00
"maps"
2015-11-05 09:47:08 -05:00
"path/filepath"
2026-02-16 05:09:26 -05:00
"slices"
2016-10-27 13:42:49 -04:00
"strings"
2016-02-08 17:04:24 -05:00
2026-02-13 10:31:57 -05:00
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hcldec"
2023-07-26 04:56:44 -04:00
"github.com/hashicorp/terraform/internal/addrs"
2026-02-13 10:31:57 -05:00
backendInit "github.com/hashicorp/terraform/internal/backend/init"
2026-02-16 05:09:26 -05:00
backendPluggable "github.com/hashicorp/terraform/internal/backend/pluggable"
2021-05-17 15:07:38 -04:00
"github.com/hashicorp/terraform/internal/command/arguments"
"github.com/hashicorp/terraform/internal/command/views"
2023-07-26 04:56:44 -04:00
"github.com/hashicorp/terraform/internal/configs"
2026-02-16 05:09:26 -05:00
"github.com/hashicorp/terraform/internal/didyoumean"
"github.com/hashicorp/terraform/internal/providers"
2021-05-17 15:46:19 -04:00
"github.com/hashicorp/terraform/internal/terraform"
2021-05-17 13:11:06 -04:00
"github.com/hashicorp/terraform/internal/tfdiags"
2015-11-05 09:47:08 -05:00
)
// ValidateCommand is a Command implementation that validates the terraform files
type ValidateCommand struct {
Meta
2025-10-01 05:33:52 -04:00
ParsedArgs * arguments . Validate
2015-11-05 09:47:08 -05:00
}
2021-03-18 11:14:58 -04:00
func ( c * ValidateCommand ) Run ( rawArgs [ ] string ) int {
// Parse and apply global view arguments
common , rawArgs := arguments . ParseView ( rawArgs )
c . View . Configure ( common )
2018-03-09 19:18:30 -05:00
2021-03-18 11:14:58 -04:00
// Parse and validate flags
args , diags := arguments . ParseValidate ( rawArgs )
if diags . HasErrors ( ) {
c . View . Diagnostics ( diags )
c . View . HelpPrompt ( "validate" )
2016-10-27 13:42:49 -04:00
return 1
}
2025-10-01 05:33:52 -04:00
c . ParsedArgs = args
2021-03-18 11:14:58 -04:00
view := views . NewValidate ( args . ViewType , c . View )
2019-10-14 15:35:33 -04:00
2018-03-09 19:18:30 -05:00
// After this point, we must only produce JSON output if JSON mode is
// enabled, so all errors should be accumulated into diags and we'll
// print out a suitable result at the end, depending on the format
// selection. All returns from this point on must be tail-calls into
2021-03-18 11:14:58 -04:00
// view.Results in order to produce the expected output.
dir , err := filepath . Abs ( args . Path )
2015-11-05 09:47:08 -05:00
if err != nil {
2018-03-09 19:18:30 -05:00
diags = diags . Append ( fmt . Errorf ( "unable to locate module: %s" , err ) )
2021-03-18 11:14:58 -04:00
return view . Results ( diags )
2015-11-05 09:47:08 -05:00
}
2017-10-20 18:42:51 -04:00
// Check for user-supplied plugin path
if c . pluginPath , err = c . loadPluginPath ( ) ; err != nil {
2018-03-09 19:18:30 -05:00
diags = diags . Append ( fmt . Errorf ( "error loading plugin path: %s" , err ) )
2021-03-18 11:14:58 -04:00
return view . Results ( diags )
2017-10-20 18:42:51 -04:00
}
2025-10-01 05:33:52 -04:00
validateDiags := c . validate ( dir )
2018-03-09 19:18:30 -05:00
diags = diags . Append ( validateDiags )
2015-11-05 09:47:08 -05:00
2020-10-14 21:00:23 -04:00
// Validating with dev overrides in effect means that the result might
// not be valid for a stable release, so we'll warn about that in case
// the user is trying to use "terraform validate" as a sort of pre-flight
// check before submitting a change.
2021-02-01 10:50:08 -05:00
diags = diags . Append ( c . providerDevOverrideRuntimeWarnings ( ) )
2020-10-14 21:00:23 -04:00
2021-03-18 11:14:58 -04:00
return view . Results ( diags )
2015-11-05 09:47:08 -05:00
}
2025-10-01 05:33:52 -04:00
func ( c * ValidateCommand ) validate ( dir string ) tfdiags . Diagnostics {
command: validate config as part of loading it
Previously we required callers to separately call .Validate on the root
module to determine if there were any value errors, but we did that
inconsistently and would thus see crashes in some cases where later code
would try to use invalid configuration as if it were valid.
Now we run .Validate automatically after config loading, returning the
resulting diagnostics. Since we return a diagnostics here, it's possible
to return both warnings and errors.
We return the loaded module even if it's invalid, so callers are free to
ignore returned errors and try to work with the config anyway, though they
will need to be defensive against invalid configuration themselves in
that case.
As a result of this, all of the commands that load configuration now need
to use diagnostic printing to signal errors. For the moment this just
allows us to return potentially-multiple config errors/warnings in full
fidelity, but also sets us up for later when more subsystems are able
to produce rich diagnostics so we can show them all together.
Finally, this commit also removes some stale, commented-out code for the
"legacy" (pre-0.8) graph implementation, which has not been available
for some time.
2017-12-06 19:41:48 -05:00
var diags tfdiags . Diagnostics
2023-07-26 04:56:44 -04:00
var cfg * configs . Config
command: validate config as part of loading it
Previously we required callers to separately call .Validate on the root
module to determine if there were any value errors, but we did that
inconsistently and would thus see crashes in some cases where later code
would try to use invalid configuration as if it were valid.
Now we run .Validate automatically after config loading, returning the
resulting diagnostics. Since we return a diagnostics here, it's possible
to return both warnings and errors.
We return the loaded module even if it's invalid, so callers are free to
ignore returned errors and try to work with the config anyway, though they
will need to be defensive against invalid configuration themselves in
that case.
As a result of this, all of the commands that load configuration now need
to use diagnostic printing to signal errors. For the moment this just
allows us to return potentially-multiple config errors/warnings in full
fidelity, but also sets us up for later when more subsystems are able
to produce rich diagnostics so we can show them all together.
Finally, this commit also removes some stale, commented-out code for the
"legacy" (pre-0.8) graph implementation, which has not been available
for some time.
2017-12-06 19:41:48 -05:00
2025-10-01 05:33:52 -04:00
// If the query flag is set, include query files in the validation.
c . includeQueryFiles = c . ParsedArgs . Query
if c . ParsedArgs . NoTests {
2023-07-26 04:56:44 -04:00
cfg , diags = c . loadConfig ( dir )
} else {
2025-10-01 05:33:52 -04:00
cfg , diags = c . loadConfigWithTests ( dir , c . ParsedArgs . TestDirectory )
2023-07-26 04:56:44 -04:00
}
command: beginnings of new config loader in "terraform validate"
As part of some light reorganization of our commands, this new
implementation no longer does validation of variables and will thus avoid
the need to spin up a fully-valid context. Instead, its focus is on
validating the configuration itself, regardless of any variables, state,
etc.
This change anticipates us later adding a -validate-only flag to
"terraform plan" which will then take over the related use-case of
checking if a particular execution of Terraform is valid, _including_ the
state, variables, etc.
Although leaving variables out of validate feels pretty arbitrary today
while all of the variable sources are local anyway, we have plans to
allow per-workspace variables to be stored in the backend in future and
at that point it will no longer be possible to fully validate variables
without accessing the backend. The "terraform plan" command explicitly
requires access to the backend, while "terraform validate" is now
explicitly for local-only validation of a single module.
In a future commit this will be extended to do basic type checking of
the configuration based on provider schemas, etc.
2018-02-28 20:14:05 -05:00
if diags . HasErrors ( ) {
2018-03-09 19:18:30 -05:00
return diags
2015-11-05 09:47:08 -05:00
}
command: validate config as part of loading it
Previously we required callers to separately call .Validate on the root
module to determine if there were any value errors, but we did that
inconsistently and would thus see crashes in some cases where later code
would try to use invalid configuration as if it were valid.
Now we run .Validate automatically after config loading, returning the
resulting diagnostics. Since we return a diagnostics here, it's possible
to return both warnings and errors.
We return the loaded module even if it's invalid, so callers are free to
ignore returned errors and try to work with the config anyway, though they
will need to be defensive against invalid configuration themselves in
that case.
As a result of this, all of the commands that load configuration now need
to use diagnostic printing to signal errors. For the moment this just
allows us to return potentially-multiple config errors/warnings in full
fidelity, but also sets us up for later when more subsystems are able
to produce rich diagnostics so we can show them all together.
Finally, this commit also removes some stale, commented-out code for the
"legacy" (pre-0.8) graph implementation, which has not been available
for some time.
2017-12-06 19:41:48 -05:00
2025-10-01 05:33:52 -04:00
diags = diags . Append ( c . validateConfig ( cfg ) )
2023-07-26 04:56:44 -04:00
2026-02-13 10:31:57 -05:00
// Validation of backend block, if present
// Backend blocks live outside the Terraform graph so we have to do this separately.
2026-02-16 05:09:26 -05:00
switch {
case cfg . Module . Backend != nil :
diags = diags . Append ( c . validateBackend ( cfg . Module . Backend ) )
case cfg . Module . StateStore != nil :
diags = diags . Append ( c . validateStateStore ( cfg . Module . StateStore ) )
2026-02-13 10:31:57 -05:00
}
2025-10-01 05:33:52 -04:00
// Unless excluded, we'll also do a quick validation of the Terraform test files. These live
// outside the Terraform graph so we have to do this separately.
if ! c . ParsedArgs . NoTests {
diags = diags . Append ( c . validateTestFiles ( cfg ) )
}
2023-07-26 04:56:44 -04:00
2025-10-01 05:33:52 -04:00
return diags
}
2023-07-26 04:56:44 -04:00
2025-10-01 05:33:52 -04:00
func ( c * ValidateCommand ) validateConfig ( cfg * configs . Config ) tfdiags . Diagnostics {
var diags tfdiags . Diagnostics
command: beginnings of new config loader in "terraform validate"
As part of some light reorganization of our commands, this new
implementation no longer does validation of variables and will thus avoid
the need to spin up a fully-valid context. Instead, its focus is on
validating the configuration itself, regardless of any variables, state,
etc.
This change anticipates us later adding a -validate-only flag to
"terraform plan" which will then take over the related use-case of
checking if a particular execution of Terraform is valid, _including_ the
state, variables, etc.
Although leaving variables out of validate feels pretty arbitrary today
while all of the variable sources are local anyway, we have plans to
allow per-workspace variables to be stored in the backend in future and
at that point it will no longer be possible to fully validate variables
without accessing the backend. The "terraform plan" command explicitly
requires access to the backend, while "terraform validate" is now
explicitly for local-only validation of a single module.
In a future commit this will be extended to do basic type checking of
the configuration based on provider schemas, etc.
2018-02-28 20:14:05 -05:00
2025-10-01 05:33:52 -04:00
opts , err := c . contextOpts ( )
if err != nil {
diags = diags . Append ( err )
return diags
}
2023-07-26 04:56:44 -04:00
2025-10-01 05:33:52 -04:00
tfCtx , ctxDiags := terraform . NewContext ( opts )
diags = diags . Append ( ctxDiags )
if ctxDiags . HasErrors ( ) {
terraform: ugly huge change to weave in new HCL2-oriented types
Due to how deeply the configuration types go into Terraform Core, there
isn't a great way to switch out to HCL2 gradually. As a consequence, this
huge commit gets us from the old state to a _compilable_ new state, but
does not yet attempt to fix any tests and has a number of known missing
parts and bugs. We will continue to iterate on this in forthcoming
commits, heading back towards passing tests and making Terraform
fully-functional again.
The three main goals here are:
- Use the configuration models from the "configs" package instead of the
older models in the "config" package, which is now deprecated and
preserved only to help us write our migration tool.
- Do expression inspection and evaluation using the functionality of the
new "lang" package, instead of the Interpolator type and related
functionality in the main "terraform" package.
- Represent addresses of various objects using types in the addrs package,
rather than hand-constructed strings. This is not critical to support
the above, but was a big help during the implementation of these other
points since it made it much more explicit what kind of address is
expected in each context.
Since our new packages are built to accommodate some future planned
features that are not yet implemented (e.g. the "for_each" argument on
resources, "count"/"for_each" on modules), and since there's still a fair
amount of functionality still using old-style APIs, there is a moderate
amount of shimming here to connect new assumptions with old, hopefully in
a way that makes it easier to find and eliminate these shims later.
I apologize in advance to the person who inevitably just found this huge
commit while spelunking through the commit history.
2018-04-30 13:33:53 -04:00
return diags
command: validate config as part of loading it
Previously we required callers to separately call .Validate on the root
module to determine if there were any value errors, but we did that
inconsistently and would thus see crashes in some cases where later code
would try to use invalid configuration as if it were valid.
Now we run .Validate automatically after config loading, returning the
resulting diagnostics. Since we return a diagnostics here, it's possible
to return both warnings and errors.
We return the loaded module even if it's invalid, so callers are free to
ignore returned errors and try to work with the config anyway, though they
will need to be defensive against invalid configuration themselves in
that case.
As a result of this, all of the commands that load configuration now need
to use diagnostic printing to signal errors. For the moment this just
allows us to return potentially-multiple config errors/warnings in full
fidelity, but also sets us up for later when more subsystems are able
to produce rich diagnostics so we can show them all together.
Finally, this commit also removes some stale, commented-out code for the
"legacy" (pre-0.8) graph implementation, which has not been available
for some time.
2017-12-06 19:41:48 -05:00
}
2025-10-01 05:33:52 -04:00
return diags . Append ( tfCtx . Validate ( cfg , nil ) )
}
2023-07-26 04:56:44 -04:00
2025-10-01 05:33:52 -04:00
func ( c * ValidateCommand ) validateTestFiles ( cfg * configs . Config ) tfdiags . Diagnostics {
diags := tfdiags . Diagnostics { }
validatedModules := make ( map [ string ] bool )
2023-07-26 04:56:44 -04:00
for _ , file := range cfg . Module . Tests {
2023-11-13 04:36:06 -05:00
// The file validation only returns warnings so we'll just add them
// without checking anything about them.
diags = diags . Append ( file . Validate ( cfg ) )
2023-07-26 04:56:44 -04:00
for _ , run := range file . Runs {
if run . Module != nil {
// Then we can also validate the referenced modules, but we are
// only going to do this is if they are local modules.
//
// Basically, local testing modules are something the user can
// reasonably go and fix. If it's a module being downloaded from
// the registry, the expectation is that the author of the
// module should have ran `terraform validate` themselves.
if _ , ok := run . Module . Source . ( addrs . ModuleSourceLocal ) ; ok {
if validated := validatedModules [ run . Module . Source . String ( ) ] ; ! validated {
// Since we can reference the same module twice, let's
// not validate the same thing multiple times.
validatedModules [ run . Module . Source . String ( ) ] = true
2025-10-01 05:33:52 -04:00
diags = diags . Append ( c . validateConfig ( run . ConfigUnderTest ) )
2023-07-26 04:56:44 -04:00
}
}
2023-11-13 04:36:06 -05:00
diags = diags . Append ( run . Validate ( run . ConfigUnderTest ) )
} else {
diags = diags . Append ( run . Validate ( cfg ) )
2023-07-26 04:56:44 -04:00
}
}
}
2018-03-09 19:18:30 -05:00
return diags
}
2026-02-13 10:31:57 -05:00
// We validate the backend in an offline manner, so we use PrepareConfig to validate the configuration (and ENVs present),
// but we never use the Configure method, as that will interact with third-party systems.
//
// The code in this method is very similar to the `backendInitFromConfig` method, expect it doesn't configure the backend.
func ( c * ValidateCommand ) validateBackend ( cfg * configs . Backend ) tfdiags . Diagnostics {
var diags tfdiags . Diagnostics
bf := backendInit . Backend ( cfg . Type )
if bf == nil {
detail := fmt . Sprintf ( "There is no backend type named %q." , cfg . Type )
if msg , removed := backendInit . RemovedBackends [ cfg . Type ] ; removed {
detail = msg
}
diags = diags . Append ( & hcl . Diagnostic {
Severity : hcl . DiagError ,
Summary : "Unsupported backend type" ,
Detail : detail ,
Subject : & cfg . TypeRange ,
} )
return diags
}
b := bf ( )
backendSchema := b . ConfigSchema ( )
decSpec := backendSchema . DecoderSpec ( )
configVal , hclDiags := hcldec . Decode ( cfg . Config , decSpec , nil )
diags = diags . Append ( hclDiags )
if hclDiags . HasErrors ( ) {
return diags
}
_ , validateDiags := b . PrepareConfig ( configVal )
diags = diags . Append ( validateDiags )
if validateDiags . HasErrors ( ) {
return diags
}
return diags
}
2026-02-16 05:09:26 -05:00
// We validate the state store in an offline manner, so we use:
// - State store's PrepareConfig method to validate the state_store block.
// - Provider's ValidateProviderConfig to validate the nested provider block.
// We don't use the Configure method, as that will interact with third-party systems.
//
// The code in this method is very similar to the `stateStoreInitFromConfig` method,
// expect it doesn't configure the provider or the state store.
func ( c * ValidateCommand ) validateStateStore ( cfg * configs . StateStore ) tfdiags . Diagnostics {
var diags tfdiags . Diagnostics
locks , depsDiags := c . Meta . lockedDependencies ( )
if depsDiags . HasErrors ( ) {
// Add some context to the error so it's obvious that it's related to the state store.
newDiag := & hcl . Diagnostic {
Severity : hcl . DiagError ,
Summary : "Unable to validate state store configuration" ,
Detail : fmt . Sprintf ( "An unexpected error was encountered when loading the dependency locks file. Make sure the working directory has been initialized and try again. Error: %s" , diags . Err ( ) ) ,
Subject : & cfg . DeclRange ,
}
return diags . Append ( newDiag )
}
diags = diags . Append ( depsDiags ) // Preserve any warnings
factory , pDiags := c . Meta . StateStoreProviderFactoryFromConfig ( cfg , locks )
diags = diags . Append ( pDiags )
if pDiags . HasErrors ( ) {
return diags
}
provider , err := factory ( )
if err != nil {
diags = diags . Append ( fmt . Errorf ( "Unable to validate state store configuration. Terraform was unable to obtain a provider instance during state store initialization: %w" , err ) )
return diags
}
defer provider . Close ( )
resp := provider . GetProviderSchema ( )
if len ( resp . StateStores ) == 0 {
diags = diags . Append ( & hcl . Diagnostic {
Severity : hcl . DiagError ,
Summary : "Provider does not support pluggable state storage" ,
Detail : fmt . Sprintf ( "There are no state stores implemented by provider %s (%q)" ,
cfg . Provider . Name ,
cfg . ProviderAddr ) ,
Subject : & cfg . DeclRange ,
} )
return diags
}
schema , exists := resp . StateStores [ cfg . Type ]
if ! exists {
suggestions := slices . Sorted ( maps . Keys ( resp . StateStores ) )
suggestion := didyoumean . NameSuggestion ( cfg . Type , suggestions )
if suggestion != "" {
suggestion = fmt . Sprintf ( " Did you mean %q?" , suggestion )
}
diags = diags . Append ( & hcl . Diagnostic {
Severity : hcl . DiagError ,
Summary : "State store not implemented by the provider" ,
Detail : fmt . Sprintf ( "State store %q is not implemented by provider %s (%q)%s" ,
cfg . Type , cfg . Provider . Name ,
cfg . ProviderAddr , suggestion ) ,
Subject : & cfg . DeclRange ,
} )
return diags
}
// Handle the nested provider block.
pDecSpec := resp . Provider . Body . DecoderSpec ( )
pConfig := cfg . Provider . Config
providerConfigVal , pDecDiags := hcldec . Decode ( pConfig , pDecSpec , nil )
diags = diags . Append ( pDecDiags )
if pDecDiags . HasErrors ( ) {
return diags
}
// Handle the schema for the state store itself, excluding the provider block.
ssdecSpec := schema . Body . DecoderSpec ( )
stateStoreConfigVal , ssDecDiags := hcldec . Decode ( cfg . Config , ssdecSpec , nil )
diags = diags . Append ( ssDecDiags )
if ssDecDiags . HasErrors ( ) {
return diags
}
// Validate the provider config
//
// NOTE: We don't configure the provider because the validate command is offline-only.
validateResp := provider . ValidateProviderConfig ( providers . ValidateProviderConfigRequest {
Config : providerConfigVal ,
} )
diags = diags . Append ( validateResp . Diagnostics )
if validateResp . Diagnostics . HasErrors ( ) {
return diags
}
// Validate the state store config
//
// NOTE: We don't configure the state store because the validate command is offline-only.
p , err := backendPluggable . NewPluggable ( provider , cfg . Type )
if err != nil {
diags = diags . Append ( err )
}
_ , validateDiags := p . PrepareConfig ( stateStoreConfigVal )
diags = diags . Append ( validateDiags )
return diags
}
2018-11-21 09:35:27 -05:00
func ( c * ValidateCommand ) Synopsis ( ) string {
2020-10-23 19:55:32 -04:00
return "Check whether the configuration is valid"
2018-11-21 09:35:27 -05:00
}
func ( c * ValidateCommand ) Help ( ) string {
helpText := `
2021-03-18 11:14:58 -04:00
Usage : terraform [ global options ] validate [ options ]
2018-11-21 09:35:27 -05:00
Validate the configuration files in a directory , referring only to the
configuration and not accessing any remote services such as remote state ,
provider APIs , etc .
2019-09-27 19:39:20 -04:00
Validate runs checks that verify whether a configuration is syntactically
valid and internally consistent , regardless of any provided variables or
existing state . It is thus primarily useful for general verification of
reusable modules , including correctness of attribute names and value types .
2018-11-21 09:35:27 -05:00
It is safe to run this command automatically , for example as a post - save
check in a text editor or as a test step for a re - usable module in a CI
system .
Validation requires an initialized working directory with any referenced
plugins and modules installed . To initialize a working directory for
validation without accessing any configured remote backend , use :
terraform init - backend = false
2019-02-25 17:02:47 -05:00
To verify configuration in the context of a particular run ( a particular
2019-09-27 19:39:20 -04:00
target workspace , input variable values , etc ) , use the ' terraform plan '
command instead , which includes an implied validation check .
2019-02-25 17:02:47 -05:00
2018-11-21 09:35:27 -05:00
Options :
2023-07-26 04:56:44 -04:00
- json Produce output in a machine - readable JSON format ,
suitable for use in text editor integrations and other
automated systems . Always disables color .
- no - color If specified , output won ' t contain any color .
- no - tests If specified , Terraform will not validate test files .
2018-11-21 09:35:27 -05:00
2023-07-26 04:56:44 -04:00
- test - directory = path Set the Terraform test directory , defaults to "tests" .
2025-10-01 05:33:52 -04:00
- query If specified , the command will also validate . tfquery . hcl files .
2018-11-21 09:35:27 -05:00
`
return strings . TrimSpace ( helpText )
}