2015-11-05 15:47:08 +01:00
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"path/filepath"
|
2016-10-27 19:42:49 +02:00
|
|
|
"strings"
|
2016-02-08 23:04:24 +01:00
|
|
|
|
2021-05-17 21:07:38 +02:00
|
|
|
"github.com/hashicorp/terraform/internal/command/arguments"
|
|
|
|
"github.com/hashicorp/terraform/internal/command/views"
|
2021-05-17 21:46:19 +02:00
|
|
|
"github.com/hashicorp/terraform/internal/terraform"
|
2021-05-17 19:11:06 +02:00
|
|
|
"github.com/hashicorp/terraform/internal/tfdiags"
|
2015-11-05 15:47:08 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// ValidateCommand is a Command implementation that validates the terraform files
|
|
|
|
type ValidateCommand struct {
|
|
|
|
Meta
|
|
|
|
}
|
|
|
|
|
2021-03-18 16:14:58 +01: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-10 01:18:30 +01:00
|
|
|
|
2021-03-18 16:14:58 +01:00
|
|
|
// Parse and validate flags
|
|
|
|
args, diags := arguments.ParseValidate(rawArgs)
|
|
|
|
if diags.HasErrors() {
|
|
|
|
c.View.Diagnostics(diags)
|
|
|
|
c.View.HelpPrompt("validate")
|
2016-10-27 19:42:49 +02:00
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
2021-03-18 16:14:58 +01:00
|
|
|
view := views.NewValidate(args.ViewType, c.View)
|
2019-10-14 21:35:33 +02:00
|
|
|
|
2018-03-10 01:18:30 +01: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 16:14:58 +01:00
|
|
|
// view.Results in order to produce the expected output.
|
|
|
|
|
|
|
|
dir, err := filepath.Abs(args.Path)
|
2015-11-05 15:47:08 +01:00
|
|
|
if err != nil {
|
2018-03-10 01:18:30 +01:00
|
|
|
diags = diags.Append(fmt.Errorf("unable to locate module: %s", err))
|
2021-03-18 16:14:58 +01:00
|
|
|
return view.Results(diags)
|
2015-11-05 15:47:08 +01:00
|
|
|
}
|
|
|
|
|
2017-10-21 00:42:51 +02:00
|
|
|
// Check for user-supplied plugin path
|
|
|
|
if c.pluginPath, err = c.loadPluginPath(); err != nil {
|
2018-03-10 01:18:30 +01:00
|
|
|
diags = diags.Append(fmt.Errorf("error loading plugin path: %s", err))
|
2021-03-18 16:14:58 +01:00
|
|
|
return view.Results(diags)
|
2017-10-21 00:42:51 +02:00
|
|
|
}
|
|
|
|
|
2018-03-10 01:18:30 +01:00
|
|
|
validateDiags := c.validate(dir)
|
|
|
|
diags = diags.Append(validateDiags)
|
2015-11-05 15:47:08 +01:00
|
|
|
|
2020-10-15 03:00:23 +02: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 16:50:08 +01:00
|
|
|
diags = diags.Append(c.providerDevOverrideRuntimeWarnings())
|
2020-10-15 03:00:23 +02:00
|
|
|
|
2021-03-18 16:14:58 +01:00
|
|
|
return view.Results(diags)
|
2015-11-05 15:47:08 +01:00
|
|
|
}
|
|
|
|
|
2018-03-10 01:18:30 +01: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-07 01:41:48 +01:00
|
|
|
var diags tfdiags.Diagnostics
|
|
|
|
|
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 19:33:53 +02:00
|
|
|
cfg, cfgDiags := c.loadConfig(dir)
|
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-03-01 02:14:05 +01:00
|
|
|
diags = diags.Append(cfgDiags)
|
|
|
|
|
|
|
|
if diags.HasErrors() {
|
2018-03-10 01:18:30 +01:00
|
|
|
return diags
|
2015-11-05 15:47:08 +01: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-07 01:41:48 +01:00
|
|
|
|
2020-06-16 18:23:15 +02:00
|
|
|
opts, err := c.contextOpts()
|
|
|
|
if err != nil {
|
|
|
|
diags = diags.Append(err)
|
|
|
|
return diags
|
|
|
|
}
|
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-03-01 02:14:05 +01:00
|
|
|
|
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 19:33:53 +02:00
|
|
|
tfCtx, ctxDiags := terraform.NewContext(opts)
|
|
|
|
diags = diags.Append(ctxDiags)
|
|
|
|
if ctxDiags.HasErrors() {
|
|
|
|
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-07 01:41:48 +01:00
|
|
|
}
|
|
|
|
|
core: Functional-style API for terraform.Context
Previously terraform.Context was built in an unfortunate way where all of
the data was provided up front in terraform.NewContext and then mutated
directly by subsequent operations. That made the data flow hard to follow,
commonly leading to bugs, and also meant that we were forced to take
various actions too early in terraform.NewContext, rather than waiting
until a more appropriate time during an operation.
This (enormous) commit changes terraform.Context so that its fields are
broadly just unchanging data about the execution context (current
workspace name, available plugins, etc) whereas the main data Terraform
works with arrives via individual method arguments and is returned in
return values.
Specifically, this means that terraform.Context no longer "has-a" config,
state, and "planned changes", instead holding on to those only temporarily
during an operation. The caller is responsible for propagating the outcome
of one step into the next step so that the data flow between operations is
actually visible.
However, since that's a change to the main entry points in the "terraform"
package, this commit also touches every file in the codebase which
interacted with those APIs. Most of the noise here is in updating tests
to take the same actions using the new API style, but this also affects
the main-code callers in the backends and in the command package.
My goal here was to refactor without changing observable behavior, but in
practice there are a couple externally-visible behavior variations here
that seemed okay in service of the broader goal:
- The "terraform graph" command is no longer hooked directly into the
core graph builders, because that's no longer part of the public API.
However, I did include a couple new Context functions whose contract
is to produce a UI-oriented graph, and _for now_ those continue to
return the physical graph we use for those operations. There's no
exported API for generating the "validate" and "eval" graphs, because
neither is particularly interesting in its own right, and so
"terraform graph" no longer supports those graph types.
- terraform.NewContext no longer has the responsibility for collecting
all of the provider schemas up front. Instead, we wait until we need
them. However, that means that some of our error messages now have a
slightly different shape due to unwinding through a differently-shaped
call stack. As of this commit we also end up reloading the schemas
multiple times in some cases, which is functionally acceptable but
likely represents a performance regression. I intend to rework this to
use caching, but I'm saving that for a later commit because this one is
big enough already.
The proximal reason for this change is to resolve the chicken/egg problem
whereby there was previously no single point where we could apply "moved"
statements to the previous run state before creating a plan. With this
change in place, we can now do that as part of Context.Plan, prior to
forking the input state into the three separate state artifacts we use
during planning.
However, this is at least the third project in a row where the previous
API design led to piling more functionality into terraform.NewContext and
then working around the incorrect order of operations that produces, so
I intend that by paying the cost/risk of this large diff now we can in
turn reduce the cost/risk of future projects that relate to our main
workflow actions.
2021-08-24 21:06:38 +02:00
|
|
|
validateDiags := tfCtx.Validate(cfg)
|
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 19:33:53 +02:00
|
|
|
diags = diags.Append(validateDiags)
|
2018-03-10 01:18:30 +01:00
|
|
|
return diags
|
|
|
|
}
|
|
|
|
|
2018-11-21 15:35:27 +01:00
|
|
|
func (c *ValidateCommand) Synopsis() string {
|
2020-10-24 01:55:32 +02:00
|
|
|
return "Check whether the configuration is valid"
|
2018-11-21 15:35:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ValidateCommand) Help() string {
|
|
|
|
helpText := `
|
2021-03-18 16:14:58 +01:00
|
|
|
Usage: terraform [global options] validate [options]
|
2018-11-21 15:35:27 +01: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-28 01:39:20 +02: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 15:35:27 +01: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 23:02:47 +01:00
|
|
|
To verify configuration in the context of a particular run (a particular
|
2019-09-28 01:39:20 +02:00
|
|
|
target workspace, input variable values, etc), use the 'terraform plan'
|
|
|
|
command instead, which includes an implied validation check.
|
2019-02-25 23:02:47 +01:00
|
|
|
|
2018-11-21 15:35:27 +01:00
|
|
|
Options:
|
|
|
|
|
|
|
|
-json Produce output in a machine-readable JSON format, suitable for
|
2019-09-28 01:39:20 +02:00
|
|
|
use in text editor integrations and other automated systems.
|
|
|
|
Always disables color.
|
2018-11-21 15:35:27 +01:00
|
|
|
|
2019-09-28 01:39:20 +02:00
|
|
|
-no-color If specified, output won't contain any color.
|
2018-11-21 15:35:27 +01:00
|
|
|
`
|
|
|
|
return strings.TrimSpace(helpText)
|
|
|
|
}
|