2014-09-26 18:03:39 -05:00
package command
import (
2020-03-24 16:51:55 -05:00
"context"
2014-09-26 18:03:39 -05:00
"fmt"
2020-05-13 07:48:11 -05:00
"log"
2022-07-20 07:28:04 -05:00
"reflect"
"sort"
2014-09-26 18:03:39 -05:00
"strings"
2019-09-09 17:58:44 -05:00
"github.com/hashicorp/hcl/v2"
2020-07-07 17:22:59 -05:00
svchost "github.com/hashicorp/terraform-svchost"
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 16:24:45 -05:00
"github.com/posener/complete"
"github.com/zclconf/go-cty/cty"
2021-05-17 14:00:50 -05:00
"github.com/hashicorp/terraform/internal/addrs"
2021-05-17 10:42:17 -05:00
"github.com/hashicorp/terraform/internal/backend"
backendInit "github.com/hashicorp/terraform/internal/backend/init"
2021-10-13 10:22:12 -05:00
"github.com/hashicorp/terraform/internal/cloud"
2021-11-19 11:54:06 -06:00
"github.com/hashicorp/terraform/internal/command/arguments"
2021-05-17 14:17:09 -05:00
"github.com/hashicorp/terraform/internal/configs"
"github.com/hashicorp/terraform/internal/configs/configschema"
2020-03-24 16:51:55 -05:00
"github.com/hashicorp/terraform/internal/getproviders"
"github.com/hashicorp/terraform/internal/providercache"
2021-05-17 14:43:35 -05:00
"github.com/hashicorp/terraform/internal/states"
2021-05-17 14:46:19 -05:00
"github.com/hashicorp/terraform/internal/terraform"
2021-05-17 12:11:06 -05:00
"github.com/hashicorp/terraform/internal/tfdiags"
2020-05-11 12:49:12 -05:00
tfversion "github.com/hashicorp/terraform/version"
2014-09-26 18:03:39 -05:00
)
// InitCommand is a Command implementation that takes a Terraform
// module and clones it to the working directory.
type InitCommand struct {
Meta
}
func ( c * InitCommand ) Run ( args [ ] string ) int {
2021-03-09 10:12:00 -06:00
var flagFromModule , flagLockfile string
2021-11-19 11:54:06 -06:00
var flagBackend , flagCloud , flagGet , flagUpgrade bool
2017-06-15 13:26:12 -05:00
var flagPluginPath FlagStringSlice
2018-03-27 17:31:05 -05:00
flagConfigExtra := newRawFlags ( "-backend-config" )
2017-03-21 14:05:51 -05:00
2020-04-01 14:01:08 -05:00
args = c . Meta . process ( args )
2018-11-21 08:35:27 -06:00
cmdFlags := c . Meta . extendedFlagSet ( "init" )
2017-01-18 22:50:45 -06:00
cmdFlags . BoolVar ( & flagBackend , "backend" , true , "" )
2021-11-19 11:54:06 -06:00
cmdFlags . BoolVar ( & flagCloud , "cloud" , true , "" )
2018-03-27 17:31:05 -05:00
cmdFlags . Var ( flagConfigExtra , "backend-config" , "" )
2017-07-28 17:23:29 -05:00
cmdFlags . StringVar ( & flagFromModule , "from-module" , "" , "copy the source of the given module into the directory before init" )
2017-01-18 22:50:45 -06:00
cmdFlags . BoolVar ( & flagGet , "get" , true , "" )
2017-03-21 14:05:51 -05:00
cmdFlags . BoolVar ( & c . forceInitCopy , "force-copy" , false , "suppress prompts about copying state data" )
2021-10-18 13:41:04 -05:00
cmdFlags . BoolVar ( & c . Meta . stateLock , "lock" , true , "lock state" )
cmdFlags . DurationVar ( & c . Meta . stateLockTimeout , "lock-timeout" , 0 , "lock timeout" )
2017-04-20 16:26:50 -05:00
cmdFlags . BoolVar ( & c . reconfigure , "reconfigure" , false , "reconfigure" )
2021-05-14 16:36:54 -05:00
cmdFlags . BoolVar ( & c . migrateState , "migrate-state" , false , "migrate state" )
2017-06-12 16:14:40 -05:00
cmdFlags . BoolVar ( & flagUpgrade , "upgrade" , false , "" )
2017-06-15 13:26:12 -05:00
cmdFlags . Var ( & flagPluginPath , "plugin-dir" , "plugin directory" )
2021-03-09 10:12:00 -06:00
cmdFlags . StringVar ( & flagLockfile , "lockfile" , "" , "Set a dependency lockfile mode" )
2021-06-02 14:30:05 -05:00
cmdFlags . BoolVar ( & c . Meta . ignoreRemoteVersion , "ignore-remote-version" , false , "continue even if remote and local Terraform versions are incompatible" )
2014-09-26 18:03:39 -05:00
cmdFlags . Usage = func ( ) { c . Ui . Error ( c . Help ( ) ) }
if err := cmdFlags . Parse ( args ) ; err != nil {
return 1
}
2021-11-19 11:54:06 -06:00
backendFlagSet := arguments . FlagIsSet ( cmdFlags , "backend" )
cloudFlagSet := arguments . FlagIsSet ( cmdFlags , "cloud" )
switch {
case backendFlagSet && cloudFlagSet :
c . Ui . Error ( "The -backend and -cloud options are aliases of one another and mutually-exclusive in their use" )
return 1
case backendFlagSet :
flagCloud = flagBackend
case cloudFlagSet :
flagBackend = flagCloud
}
2021-05-17 13:28:34 -05:00
if c . migrateState && c . reconfigure {
c . Ui . Error ( "The -migrate-state and -reconfigure options are mutually-exclusive" )
return 1
}
2021-05-14 16:36:54 -05:00
// Copying the state only happens during backend migration, so setting
// -force-copy implies -migrate-state
if c . forceInitCopy {
c . migrateState = true
}
2018-03-27 17:31:05 -05:00
var diags tfdiags . Diagnostics
2017-06-15 14:23:16 -05:00
if len ( flagPluginPath ) > 0 {
c . pluginPath = flagPluginPath
2020-12-07 10:10:21 -06:00
}
2021-02-02 09:35:45 -06:00
// Validate the arg count and get the working directory
2014-09-26 18:03:39 -05:00
args = cmdFlags . Args ( )
2021-02-02 09:35:45 -06:00
path , err := ModulePath ( args )
if err != nil {
c . Ui . Error ( err . Error ( ) )
2014-09-26 18:03:39 -05:00
return 1
2017-01-18 22:50:45 -06:00
}
2017-06-15 13:26:12 -05:00
if err := c . storePluginPath ( c . pluginPath ) ; err != nil {
c . Ui . Error ( fmt . Sprintf ( "Error saving -plugin-path values: %s" , err ) )
return 1
}
2017-01-18 22:50:45 -06:00
// This will track whether we outputted anything so that we know whether
// to output a newline before the success message
var header bool
2017-07-28 17:23:29 -05:00
if flagFromModule != "" {
src := flagFromModule
2019-07-18 12:07:10 -05:00
empty , err := configs . IsEmptyDir ( path )
2017-07-28 17:23:29 -05:00
if err != nil {
c . Ui . Error ( fmt . Sprintf ( "Error validating destination directory: %s" , err ) )
return 1
}
if ! empty {
c . Ui . Error ( strings . TrimSpace ( errInitCopyNotEmpty ) )
return 1
}
c . Ui . Output ( c . Colorize ( ) . Color ( fmt . Sprintf (
"[reset][bold]Copying configuration[reset] from %q..." , src ,
) ) )
header = true
2018-03-27 17:31:05 -05:00
hooks := uiModuleInstallHooks {
Ui : c . Ui ,
ShowLocalPaths : false , // since they are in a weird location for init
}
2021-11-01 15:09:16 -05:00
initDirFromModuleAbort , initDirFromModuleDiags := c . initDirFromModule ( path , src , hooks )
diags = diags . Append ( initDirFromModuleDiags )
if initDirFromModuleAbort || initDirFromModuleDiags . HasErrors ( ) {
2018-03-27 17:31:05 -05:00
c . showDiagnostics ( diags )
2017-07-28 17:23:29 -05:00
return 1
}
2018-03-27 19:22:51 -05:00
c . Ui . Output ( "" )
2017-07-28 17:23:29 -05:00
}
2021-01-26 13:39:11 -06:00
// If our directory is empty, then we're done. We can't get or set up
2017-01-18 22:50:45 -06:00
// the backend with an empty directory.
2019-07-18 12:07:10 -05:00
empty , err := configs . IsEmptyDir ( path )
2018-10-31 10:45:03 -05:00
if err != nil {
2018-03-27 17:31:05 -05:00
diags = diags . Append ( fmt . Errorf ( "Error checking configuration: %s" , err ) )
2020-06-18 16:56:05 -05:00
c . showDiagnostics ( diags )
2014-09-26 18:03:39 -05:00
return 1
2018-10-31 10:45:03 -05:00
}
if empty {
2017-01-18 22:50:45 -06:00
c . Ui . Output ( c . Colorize ( ) . Color ( strings . TrimSpace ( outputInitEmpty ) ) )
return 0
2014-09-26 18:03:39 -05:00
}
2023-01-24 14:33:47 -06:00
// Load just the root module to begin backend and module initialization
rootModEarly , earlyConfDiags := c . loadSingleModule ( path )
2021-09-28 11:38:40 -05:00
2023-01-24 14:33:47 -06:00
// There may be parsing errors in config loading but these will be shown later _after_
// checking for core version requirement errors. Not meeting the version requirement should
// be the first error displayed if that is an issue, but other operations are required
// before being able to check core version requirements.
if rootModEarly == nil {
c . Ui . Error ( c . Colorize ( ) . Color ( strings . TrimSpace ( errInitConfigError ) ) )
2021-09-28 11:38:40 -05:00
diags = diags . Append ( earlyConfDiags )
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
c . showDiagnostics ( diags )
2018-11-09 17:08:39 -06:00
2020-03-19 07:01:16 -05:00
return 1
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
}
var back backend . Backend
2020-03-19 07:01:16 -05:00
2023-01-24 14:33:47 -06:00
// There may be config errors or backend init errors but these will be shown later _after_
// checking for core version requirement errors.
var backDiags tfdiags . Diagnostics
var backendOutput bool
2021-08-24 14:28:12 -05:00
switch {
2023-01-24 14:33:47 -06:00
case flagCloud && rootModEarly . CloudConfig != nil :
back , backendOutput , backDiags = c . initCloud ( rootModEarly , flagConfigExtra )
2021-08-24 14:28:12 -05:00
case flagBackend :
2023-01-24 14:33:47 -06:00
back , backendOutput , backDiags = c . initBackend ( rootModEarly , flagConfigExtra )
2021-08-24 14:28:12 -05:00
default :
2020-01-07 14:07:06 -06:00
// load the previously-stored backend config
2023-01-24 14:33:47 -06:00
back , backDiags = c . Meta . backendFromState ( )
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
}
2023-01-24 14:33:47 -06:00
if backendOutput {
header = true
2017-06-15 14:23:16 -05:00
}
2017-05-03 10:02:47 -05:00
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 16:24:45 -05:00
var state * states . State
2017-06-21 12:32:13 -05:00
// If we have a functional backend (either just initialized or initialized
// on a previous run) we'll use the current state as a potential source
// of provider dependencies.
if back != nil {
2021-08-24 14:28:12 -05:00
c . ignoreRemoteVersionConflict ( back )
2020-06-16 11:23:15 -05:00
workspace , err := c . Workspace ( )
if err != nil {
c . Ui . Error ( fmt . Sprintf ( "Error selecting workspace: %s" , err ) )
return 1
}
sMgr , err := back . StateMgr ( workspace )
2017-06-21 12:32:13 -05:00
if err != nil {
2018-10-31 10:45:03 -05:00
c . Ui . Error ( fmt . Sprintf ( "Error loading state: %s" , err ) )
2017-06-21 12:32:13 -05:00
return 1
}
if err := sMgr . RefreshState ( ) ; err != nil {
2018-10-31 10:45:03 -05:00
c . Ui . Error ( fmt . Sprintf ( "Error refreshing state: %s" , err ) )
2017-06-21 12:32:13 -05:00
return 1
}
state = sMgr . State ( )
2017-06-15 14:23:16 -05:00
}
2017-05-03 10:02:47 -05:00
2023-01-24 14:33:47 -06:00
if flagGet {
modsOutput , modsAbort , modsDiags := c . getModules ( path , rootModEarly , flagUpgrade )
diags = diags . Append ( modsDiags )
if modsAbort || modsDiags . HasErrors ( ) {
c . showDiagnostics ( diags )
return 1
}
if modsOutput {
header = true
}
}
// With all of the modules (hopefully) installed, we can now try to load the
// whole configuration tree.
config , confDiags := c . loadConfig ( path )
// configDiags will be handled after the version constraint check, since an
// incorrect version of terraform may be producing errors for configuration
// constructs added in later versions.
// Before we go further, we'll check to make sure none of the modules in
// the configuration declare that they don't support this Terraform
// version, so we can produce a version-related error message rather than
// potentially-confusing downstream errors.
versionDiags := terraform . CheckCoreVersionRequirements ( config )
if versionDiags . HasErrors ( ) {
c . showDiagnostics ( versionDiags )
return 1
}
2023-02-15 22:56:38 -06:00
// If we pass the core version check, we want to show any errors from initializing the backend next,
// which will include syntax errors from loading the configuration. However, there's a special case
// where we are unable to load the backend from configuration or state _and_ the configuration has
// errors. In that case, we want to show a slightly friendlier error message for newcomers.
showBackendDiags := back != nil || rootModEarly . Backend != nil || rootModEarly . CloudConfig != nil
if showBackendDiags {
diags = diags . Append ( backDiags )
if backDiags . HasErrors ( ) {
c . showDiagnostics ( diags )
return 1
}
} else {
diags = diags . Append ( earlyConfDiags )
if earlyConfDiags . HasErrors ( ) {
c . Ui . Error ( strings . TrimSpace ( errInitConfigError ) )
c . showDiagnostics ( diags )
return 1
}
2023-01-24 14:33:47 -06:00
}
2023-02-15 22:56:38 -06:00
// If everything is ok with the core version check and backend initialization,
// show other errors from loading the full configuration tree.
2023-01-24 14:33:47 -06:00
diags = diags . Append ( confDiags )
if confDiags . HasErrors ( ) {
c . Ui . Error ( strings . TrimSpace ( errInitConfigError ) )
c . showDiagnostics ( diags )
return 1
}
2017-06-21 12:32:13 -05:00
// Now that we have loaded all modules, check the module tree for missing providers.
2021-03-09 10:12:00 -06:00
providersOutput , providersAbort , providerDiags := c . getProviders ( config , state , flagUpgrade , flagPluginPath , flagLockfile )
2018-03-27 19:22:51 -05:00
diags = diags . Append ( providerDiags )
2020-09-28 19:13:32 -05:00
if providersAbort || providerDiags . HasErrors ( ) {
2018-03-27 19:22:51 -05:00
c . showDiagnostics ( diags )
2017-06-15 14:23:16 -05:00
return 1
2017-05-03 10:02:47 -05:00
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
if providersOutput {
header = true
}
2017-05-03 10:02:47 -05:00
2017-01-18 22:50:45 -06:00
// If we outputted information, then we need to output a newline
// so that our success message is nicely spaced out from prior text.
if header {
c . Ui . Output ( "" )
2014-09-30 18:05:40 -05:00
}
2017-01-18 22:50:45 -06:00
2018-03-27 19:22:51 -05:00
// If we accumulated any warnings along the way that weren't accompanied
// by errors then we'll output them here so that the success message is
// still the final thing shown.
c . showDiagnostics ( diags )
2021-10-13 10:22:12 -05:00
_ , cloud := back . ( * cloud . Cloud )
2021-10-18 09:03:38 -05:00
output := outputInitSuccess
2021-10-13 10:22:12 -05:00
if cloud {
output = outputInitSuccessCloud
}
c . Ui . Output ( c . Colorize ( ) . Color ( strings . TrimSpace ( output ) ) )
2017-09-08 19:14:37 -05:00
if ! c . RunningInAutomation {
// If we're not running in an automation wrapper, give the user
// some more detailed next steps that are appropriate for interactive
// shell usage.
2021-10-13 10:22:12 -05:00
output = outputInitSuccessCLI
if cloud {
output = outputInitSuccessCLICloud
}
c . Ui . Output ( c . Colorize ( ) . Color ( strings . TrimSpace ( output ) ) )
2017-09-08 19:14:37 -05:00
}
2014-09-26 18:03:39 -05:00
return 0
}
2023-01-24 14:33:47 -06:00
func ( c * InitCommand ) getModules ( path string , earlyRoot * configs . Module , upgrade bool ) ( output bool , abort bool , diags tfdiags . Diagnostics ) {
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
if len ( earlyRoot . ModuleCalls ) == 0 {
// Nothing to do
2021-11-01 15:09:16 -05:00
return false , false , nil
2018-03-27 17:31:05 -05:00
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
if upgrade {
2020-12-01 11:34:50 -06:00
c . Ui . Output ( c . Colorize ( ) . Color ( "[reset][bold]Upgrading modules..." ) )
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
} else {
2020-12-01 11:34:50 -06:00
c . Ui . Output ( c . Colorize ( ) . Color ( "[reset][bold]Initializing modules..." ) )
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
}
hooks := uiModuleInstallHooks {
Ui : c . Ui ,
ShowLocalPaths : true ,
}
2021-11-01 15:09:16 -05:00
installAbort , installDiags := c . installModules ( path , upgrade , hooks )
diags = diags . Append ( installDiags )
2021-11-09 07:15:13 -06:00
// At this point, installModules may have generated error diags or been
// aborted by SIGINT. In any case we continue and the manifest as best
// we can.
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
// Since module installer has modified the module manifest on disk, we need
// to refresh the cache of it in the loader.
if c . configLoader != nil {
if err := c . configLoader . RefreshModules ( ) ; err != nil {
// Should never happen
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to read module manifest" ,
fmt . Sprintf ( "After installing modules, Terraform could not re-read the manifest of installed modules. This is a bug in Terraform. %s." , err ) ,
) )
2018-03-27 17:31:05 -05:00
}
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
2021-11-09 07:15:13 -06:00
return true , installAbort , diags
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
}
2021-11-12 19:07:10 -06:00
func ( c * InitCommand ) initCloud ( root * configs . Module , extraConfig rawFlags ) ( be backend . Backend , output bool , diags tfdiags . Diagnostics ) {
2021-08-24 14:28:12 -05:00
c . Ui . Output ( c . Colorize ( ) . Color ( "\n[reset][bold]Initializing Terraform Cloud..." ) )
2021-11-12 19:07:10 -06:00
if len ( extraConfig . AllItems ( ) ) != 0 {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid command-line option" ,
"The -backend-config=... command line option is only for state backends, and is not applicable to Terraform Cloud-based configurations.\n\nTo change the set of workspaces associated with this configuration, edit the Cloud configuration block in the root module." ,
) )
return nil , true , diags
}
2021-08-24 14:28:12 -05:00
backendConfig := root . CloudConfig . ToBackendConfig ( )
opts := & BackendOpts {
Config : & backendConfig ,
Init : true ,
}
back , backDiags := c . Backend ( opts )
diags = diags . Append ( backDiags )
return back , true , diags
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
func ( c * InitCommand ) initBackend ( root * configs . Module , extraConfig rawFlags ) ( be backend . Backend , output bool , diags tfdiags . Diagnostics ) {
2020-12-01 11:34:50 -06:00
c . Ui . Output ( c . Colorize ( ) . Color ( "\n[reset][bold]Initializing the backend..." ) )
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
var backendConfig * configs . Backend
var backendConfigOverride hcl . Body
if root . Backend != nil {
backendType := root . Backend . Type
2021-08-24 14:34:34 -05:00
if backendType == "cloud" {
diags = diags . Append ( & hcl . Diagnostic {
Severity : hcl . DiagError ,
Summary : "Unsupported backend type" ,
Detail : fmt . Sprintf ( "There is no explicit backend type named %q. To configure Terraform Cloud, declare a 'cloud' block instead." , backendType ) ,
Subject : & root . Backend . TypeRange ,
} )
return nil , true , diags
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
bf := backendInit . Backend ( backendType )
if bf == nil {
2022-06-28 12:13:20 -05:00
detail := fmt . Sprintf ( "There is no backend type named %q." , backendType )
if msg , removed := backendInit . RemovedBackends [ backendType ] ; removed {
detail = msg
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
diags = diags . Append ( & hcl . Diagnostic {
Severity : hcl . DiagError ,
Summary : "Unsupported backend type" ,
2022-06-28 12:13:20 -05:00
Detail : detail ,
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
Subject : & root . Backend . TypeRange ,
} )
return nil , true , diags
2018-03-27 17:31:05 -05:00
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
b := bf ( )
backendSchema := b . ConfigSchema ( )
backendConfig = root . Backend
2018-03-27 17:31:05 -05:00
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
var overrideDiags tfdiags . Diagnostics
backendConfigOverride , overrideDiags = c . backendConfigOverrideBody ( extraConfig , backendSchema )
diags = diags . Append ( overrideDiags )
if overrideDiags . HasErrors ( ) {
return nil , true , diags
2018-03-27 17:31:05 -05:00
}
2019-07-23 07:08:28 -05:00
} else {
// If the user supplied a -backend-config on the CLI but no backend
// block was found in the configuration, it's likely - but not
// necessarily - a mistake. Return a warning.
if ! extraConfig . Empty ( ) {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Warning ,
"Missing backend configuration" ,
` - backend - config was used without a "backend" block in the configuration .
If you intended to override the default local backend configuration ,
no action is required , but you may add an explicit backend block to your
configuration to clear this warning :
terraform {
backend "local" { }
}
However , if you intended to override a defined backend , please verify that
the backend configuration is present and valid .
` ,
) )
}
2018-03-27 17:31:05 -05:00
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
opts := & BackendOpts {
Config : backendConfig ,
ConfigOverride : backendConfigOverride ,
Init : true ,
}
2019-02-25 17:37:20 -06:00
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
back , backDiags := c . Backend ( opts )
diags = diags . Append ( backDiags )
return back , true , diags
2018-03-27 17:31:05 -05:00
}
2017-06-09 11:42:45 -05:00
// Load the complete module tree, and fetch any missing providers.
// This method outputs its own Ui.
2021-03-09 10:12:00 -06:00
func ( c * InitCommand ) getProviders ( config * configs . Config , state * states . State , upgrade bool , pluginDirs [ ] string , flagLockfile string ) ( output , abort bool , diags tfdiags . Diagnostics ) {
2021-02-01 09:50:08 -06:00
// Dev overrides cause the result of "terraform init" to be irrelevant for
// any overridden providers, so we'll warn about it to avoid later
// confusion when Terraform ends up using a different provider than the
// lock file called for.
diags = diags . Append ( c . providerDevOverrideInitWarnings ( ) )
2020-03-24 16:51:55 -05:00
// First we'll collect all the provider dependencies we can see in the
// configuration and the state.
2020-10-02 18:41:56 -05:00
reqs , hclDiags := config . ProviderRequirements ( )
diags = diags . Append ( hclDiags )
if hclDiags . HasErrors ( ) {
2020-09-28 19:13:32 -05:00
return false , true , diags
2020-03-24 16:51:55 -05:00
}
if state != nil {
2020-10-07 10:00:06 -05:00
stateReqs := state . ProviderRequirements ( )
2020-03-26 17:42:03 -05:00
reqs = reqs . Merge ( stateReqs )
2020-03-24 16:51:55 -05:00
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
2020-09-29 19:51:39 -05:00
for providerAddr := range reqs {
if providerAddr . IsLegacy ( ) {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid legacy provider address" ,
fmt . Sprintf (
"This configuration or its associated state refers to the unqualified provider %q.\n\nYou must complete the Terraform 0.13 upgrade process before upgrading to later versions." ,
providerAddr . Type ,
) ,
) )
}
}
2020-10-02 18:41:56 -05:00
previousLocks , moreDiags := c . lockedDependencies ( )
diags = diags . Append ( moreDiags )
2020-09-29 19:51:39 -05:00
if diags . HasErrors ( ) {
return false , true , diags
}
2020-03-31 18:03:07 -05:00
var inst * providercache . Installer
if len ( pluginDirs ) == 0 {
// By default we use a source that looks for providers in all of the
// standard locations, possibly customized by the user in CLI config.
inst = c . providerInstaller ( )
} else {
// If the user passes at least one -plugin-dir then that circumvents
// the usual sources and forces Terraform to consult only the given
// directories. Anything not available in one of those directories
// is not available for installation.
source := c . providerCustomLocalDirectorySource ( pluginDirs )
inst = c . providerInstallerCustomSource ( source )
2020-05-13 07:48:11 -05:00
// The default (or configured) search paths are logged earlier, in provider_source.go
// Log that those are being overridden by the `-plugin-dir` command line options
2020-05-14 13:04:13 -05:00
log . Println ( "[DEBUG] init: overriding provider plugin search paths" )
2020-05-13 07:48:11 -05:00
log . Printf ( "[DEBUG] will search for provider plugins in %s" , pluginDirs )
2020-03-31 18:03:07 -05:00
}
2017-06-19 09:23:58 -05:00
2020-12-09 18:55:40 -06:00
// Installation can be aborted by interruption signals
ctx , done := c . InterruptibleContext ( )
defer done ( )
2022-07-20 07:28:04 -05:00
// We want to print out a nice warning if we don't manage to pull
// checksums for all our providers. This is tracked via callbacks
// and incomplete providers are stored here for later analysis.
var incompleteProviders [ ] string
2020-03-13 19:04:14 -05:00
// Because we're currently just streaming a series of events sequentially
// into the terminal, we're showing only a subset of the events to keep
// things relatively concise. Later it'd be nice to have a progress UI
// where statuses update in-place, but we can't do that as long as we
// are shimming our vt100 output to the legacy console API on Windows.
evts := & providercache . InstallerEvents {
PendingProviders : func ( reqs map [ addrs . Provider ] getproviders . VersionConstraints ) {
c . Ui . Output ( c . Colorize ( ) . Color (
"\n[reset][bold]Initializing provider plugins..." ,
) )
} ,
ProviderAlreadyInstalled : func ( provider addrs . Provider , selectedVersion getproviders . Version ) {
2020-04-03 07:37:40 -05:00
c . Ui . Info ( fmt . Sprintf ( "- Using previously-installed %s v%s" , provider . ForDisplay ( ) , selectedVersion ) )
2020-03-13 19:04:14 -05:00
} ,
2020-04-01 18:44:50 -05:00
BuiltInProviderAvailable : func ( provider addrs . Provider ) {
2020-04-03 07:37:40 -05:00
c . Ui . Info ( fmt . Sprintf ( "- %s is built in to Terraform" , provider . ForDisplay ( ) ) )
2020-04-01 18:44:50 -05:00
} ,
BuiltInProviderFailure : func ( provider addrs . Provider , err error ) {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid dependency on built-in provider" ,
2020-04-03 07:37:40 -05:00
fmt . Sprintf ( "Cannot use %s: %s." , provider . ForDisplay ( ) , err ) ,
2020-04-01 18:44:50 -05:00
) )
} ,
2020-10-02 19:00:49 -05:00
QueryPackagesBegin : func ( provider addrs . Provider , versionConstraints getproviders . VersionConstraints , locked bool ) {
if locked {
c . Ui . Info ( fmt . Sprintf ( "- Reusing previous version of %s from the dependency lock file" , provider . ForDisplay ( ) ) )
2020-03-13 19:04:14 -05:00
} else {
2020-10-02 19:00:49 -05:00
if len ( versionConstraints ) > 0 {
c . Ui . Info ( fmt . Sprintf ( "- Finding %s versions matching %q..." , provider . ForDisplay ( ) , getproviders . VersionConstraintsString ( versionConstraints ) ) )
} else {
c . Ui . Info ( fmt . Sprintf ( "- Finding latest version of %s..." , provider . ForDisplay ( ) ) )
}
2020-03-13 19:04:14 -05:00
}
} ,
LinkFromCacheBegin : func ( provider addrs . Provider , version getproviders . Version , cacheRoot string ) {
2020-04-03 07:37:40 -05:00
c . Ui . Info ( fmt . Sprintf ( "- Using %s v%s from the shared cache directory" , provider . ForDisplay ( ) , version ) )
2020-03-13 19:04:14 -05:00
} ,
FetchPackageBegin : func ( provider addrs . Provider , version getproviders . Version , location getproviders . PackageLocation ) {
2020-04-03 07:37:40 -05:00
c . Ui . Info ( fmt . Sprintf ( "- Installing %s v%s..." , provider . ForDisplay ( ) , version ) )
2020-03-13 19:04:14 -05:00
} ,
QueryPackagesFailure : func ( provider addrs . Provider , err error ) {
2020-05-14 13:04:13 -05:00
switch errorTy := err . ( type ) {
case getproviders . ErrProviderNotFound :
sources := errorTy . Sources
displaySources := make ( [ ] string , len ( sources ) )
for i , source := range sources {
2020-09-30 03:30:02 -05:00
displaySources [ i ] = fmt . Sprintf ( " - %s" , source )
2020-05-14 13:04:13 -05:00
}
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to query available provider packages" ,
2020-05-20 09:20:13 -05:00
fmt . Sprintf ( "Could not retrieve the list of available versions for provider %s: %s\n\n%s" ,
2020-05-14 13:04:13 -05:00
provider . ForDisplay ( ) , err , strings . Join ( displaySources , "\n" ) ,
) ,
) )
2020-05-25 14:24:35 -05:00
case getproviders . ErrRegistryProviderNotKnown :
2020-12-09 18:55:40 -06:00
// We might be able to suggest an alternative provider to use
// instead of this one.
2021-03-11 07:54:18 -06:00
suggestion := fmt . Sprintf ( "\n\nAll modules should specify their required_providers so that external consumers will get the correct providers when using a module. To see which modules are currently depending on %s, run the following command:\n terraform providers" , provider . ForDisplay ( ) )
alternative := getproviders . MissingProviderSuggestion ( ctx , provider , inst . ProviderSource ( ) , reqs )
2020-12-09 18:55:40 -06:00
if alternative != provider {
suggestion = fmt . Sprintf (
"\n\nDid you intend to use %s? If so, you must specify that source address in each module which requires that provider. To see which modules are currently depending on %s, run the following command:\n terraform providers" ,
alternative . ForDisplay ( ) , provider . ForDisplay ( ) ,
)
}
2020-09-29 19:51:39 -05:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to query available provider packages" ,
2020-12-09 18:55:40 -06:00
fmt . Sprintf ( "Could not retrieve the list of available versions for provider %s: %s%s" ,
provider . ForDisplay ( ) , err , suggestion ,
2020-09-29 19:51:39 -05:00
) ,
) )
2020-07-07 17:22:59 -05:00
case getproviders . ErrHostNoProviders :
switch {
case errorTy . Hostname == svchost . Hostname ( "github.com" ) && ! errorTy . HasOtherVersion :
// If a user copies the URL of a GitHub repository into
// the source argument and removes the schema to make it
// provider-address-shaped then that's one way we can end up
// here. We'll use a specialized error message in anticipation
// of that mistake. We only do this if github.com isn't a
// provider registry, to allow for the (admittedly currently
// rather unlikely) possibility that github.com starts being
// a real Terraform provider registry in the future.
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid provider registry host" ,
fmt . Sprintf ( "The given source address %q specifies a GitHub repository rather than a Terraform provider. Refer to the documentation of the provider to find the correct source address to use." ,
provider . String ( ) ,
) ,
) )
case errorTy . HasOtherVersion :
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid provider registry host" ,
fmt . Sprintf ( "The host %q given in in provider source address %q does not offer a Terraform provider registry that is compatible with this Terraform version, but it may be compatible with a different Terraform version." ,
errorTy . Hostname , provider . String ( ) ,
) ,
) )
default :
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid provider registry host" ,
fmt . Sprintf ( "The host %q given in in provider source address %q does not offer a Terraform provider registry." ,
errorTy . Hostname , provider . String ( ) ,
) ,
) )
}
2020-09-28 19:13:32 -05:00
case getproviders . ErrRequestCanceled :
// We don't attribute cancellation to any particular operation,
// but rather just emit a single general message about it at
// the end, by checking ctx.Err().
2020-05-14 13:04:13 -05:00
default :
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to query available provider packages" ,
2020-05-20 09:20:13 -05:00
fmt . Sprintf ( "Could not retrieve the list of available versions for provider %s: %s" ,
2020-05-14 13:04:13 -05:00
provider . ForDisplay ( ) , err ,
) ,
) )
}
2020-03-13 19:04:14 -05:00
} ,
2020-06-25 09:49:48 -05:00
QueryPackagesWarning : func ( provider addrs . Provider , warnings [ ] string ) {
displayWarnings := make ( [ ] string , len ( warnings ) )
for i , warning := range warnings {
displayWarnings [ i ] = fmt . Sprintf ( "- %s" , warning )
}
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Warning ,
"Additional provider information from registry" ,
fmt . Sprintf ( "The remote registry returned warnings for %s:\n%s" ,
provider . String ( ) ,
strings . Join ( displayWarnings , "\n" ) ,
) ,
) )
} ,
2020-03-13 19:04:14 -05:00
LinkFromCacheFailure : func ( provider addrs . Provider , version getproviders . Version , err error ) {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to install provider from shared cache" ,
2020-04-03 07:37:40 -05:00
fmt . Sprintf ( "Error while importing %s v%s from the shared cache directory: %s." , provider . ForDisplay ( ) , version , err ) ,
2020-03-13 19:04:14 -05:00
) )
} ,
FetchPackageFailure : func ( provider addrs . Provider , version getproviders . Version , err error ) {
2020-09-28 16:25:08 -05:00
const summaryIncompatible = "Incompatible provider version"
2020-05-11 12:49:12 -05:00
switch err := err . ( type ) {
case getproviders . ErrProtocolNotSupported :
closestAvailable := err . Suggestion
switch {
case closestAvailable == getproviders . UnspecifiedVersion :
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
2020-09-28 16:25:08 -05:00
summaryIncompatible ,
2020-05-11 12:49:12 -05:00
fmt . Sprintf ( errProviderVersionIncompatible , provider . String ( ) ) ,
) )
case version . GreaterThan ( closestAvailable ) :
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
2020-09-28 16:25:08 -05:00
summaryIncompatible ,
2020-05-11 12:49:12 -05:00
fmt . Sprintf ( providerProtocolTooNew , provider . ForDisplay ( ) ,
version , tfversion . String ( ) , closestAvailable , closestAvailable ,
getproviders . VersionConstraintsString ( reqs [ provider ] ) ,
) ,
) )
default : // version is less than closestAvailable
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
2020-09-28 16:25:08 -05:00
summaryIncompatible ,
2020-05-11 12:49:12 -05:00
fmt . Sprintf ( providerProtocolTooOld , provider . ForDisplay ( ) ,
version , tfversion . String ( ) , closestAvailable , closestAvailable ,
getproviders . VersionConstraintsString ( reqs [ provider ] ) ,
) ,
) )
}
2020-09-28 16:25:08 -05:00
case getproviders . ErrPlatformNotSupported :
switch {
case err . MirrorURL != nil :
// If we're installing from a mirror then it may just be
// the mirror lacking the package, rather than it being
// unavailable from upstream.
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
summaryIncompatible ,
fmt . Sprintf (
"Your chosen provider mirror at %s does not have a %s v%s package available for your current platform, %s.\n\nProvider releases are separate from Terraform CLI releases, so this provider might not support your current platform. Alternatively, the mirror itself might have only a subset of the plugin packages available in the origin registry, at %s." ,
err . MirrorURL , err . Provider , err . Version , err . Platform ,
err . Provider . Hostname ,
) ,
) )
default :
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
summaryIncompatible ,
fmt . Sprintf (
"Provider %s v%s does not have a package available for your current platform, %s.\n\nProvider releases are separate from Terraform CLI releases, so not all providers are available for all platforms. Other versions of this provider may have different platforms supported." ,
err . Provider , err . Version , err . Platform ,
) ,
) )
}
2020-09-28 19:13:32 -05:00
case getproviders . ErrRequestCanceled :
// We don't attribute cancellation to any particular operation,
// but rather just emit a single general message about it at
// the end, by checking ctx.Err().
2020-09-28 16:25:08 -05:00
2020-05-11 12:49:12 -05:00
default :
2020-09-28 16:25:08 -05:00
// We can potentially end up in here under cancellation too,
// in spite of our getproviders.ErrRequestCanceled case above,
// because not all of the outgoing requests we do under the
// "fetch package" banner are source metadata requests.
// In that case we will emit a redundant error here about
// the request being cancelled, but we'll still detect it
// as a cancellation after the installer returns and do the
// normal cancellation handling.
2020-05-11 12:49:12 -05:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to install provider" ,
fmt . Sprintf ( "Error while installing %s v%s: %s" , provider . ForDisplay ( ) , version , err ) ,
) )
}
2020-03-13 19:04:14 -05:00
} ,
internal: Verify provider signatures on install
Providers installed from the registry are accompanied by a list of
checksums (the "SHA256SUMS" file), which is cryptographically signed to
allow package authentication. The process of verifying this has multiple
steps:
- First we must verify that the SHA256 hash of the package archive
matches the expected hash. This could be done for local installations
too, in the future.
- Next we ensure that the expected hash returned as part of the registry
API response matches an entry in the checksum list.
- Finally we verify the cryptographic signature of the checksum list,
using the public keys provided by the registry.
Each of these steps is implemented as a separate PackageAuthentication
type. The local archive installation mechanism uses only the archive
checksum authenticator, and the HTTP installation uses all three in the
order given.
The package authentication system now also returns a result value, which
is used by command/init to display the result of the authentication
process.
There are three tiers of signature, each of which is presented
differently to the user:
- Signatures from the embedded HashiCorp public key indicate that the
provider is officially supported by HashiCorp;
- If the signing key is not from HashiCorp, it may have an associated
trust signature, which indicates that the provider is from one of
HashiCorp's trusted partners;
- Otherwise, if the signature is valid, this is a community provider.
2020-04-08 15:22:07 -05:00
FetchPackageSuccess : func ( provider addrs . Provider , version getproviders . Version , localDir string , authResult * getproviders . PackageAuthenticationResult ) {
2020-05-12 12:58:12 -05:00
var keyID string
if authResult != nil && authResult . ThirdPartySigned ( ) {
keyID = authResult . KeyID
internal: Verify provider signatures on install
Providers installed from the registry are accompanied by a list of
checksums (the "SHA256SUMS" file), which is cryptographically signed to
allow package authentication. The process of verifying this has multiple
steps:
- First we must verify that the SHA256 hash of the package archive
matches the expected hash. This could be done for local installations
too, in the future.
- Next we ensure that the expected hash returned as part of the registry
API response matches an entry in the checksum list.
- Finally we verify the cryptographic signature of the checksum list,
using the public keys provided by the registry.
Each of these steps is implemented as a separate PackageAuthentication
type. The local archive installation mechanism uses only the archive
checksum authenticator, and the HTTP installation uses all three in the
order given.
The package authentication system now also returns a result value, which
is used by command/init to display the result of the authentication
process.
There are three tiers of signature, each of which is presented
differently to the user:
- Signatures from the embedded HashiCorp public key indicate that the
provider is officially supported by HashiCorp;
- If the signing key is not from HashiCorp, it may have an associated
trust signature, which indicates that the provider is from one of
HashiCorp's trusted partners;
- Otherwise, if the signature is valid, this is a community provider.
2020-04-08 15:22:07 -05:00
}
2020-05-12 12:58:12 -05:00
if keyID != "" {
keyID = c . Colorize ( ) . Color ( fmt . Sprintf ( ", key ID [reset][bold]%s[reset]" , keyID ) )
internal: Verify provider signatures on install
Providers installed from the registry are accompanied by a list of
checksums (the "SHA256SUMS" file), which is cryptographically signed to
allow package authentication. The process of verifying this has multiple
steps:
- First we must verify that the SHA256 hash of the package archive
matches the expected hash. This could be done for local installations
too, in the future.
- Next we ensure that the expected hash returned as part of the registry
API response matches an entry in the checksum list.
- Finally we verify the cryptographic signature of the checksum list,
using the public keys provided by the registry.
Each of these steps is implemented as a separate PackageAuthentication
type. The local archive installation mechanism uses only the archive
checksum authenticator, and the HTTP installation uses all three in the
order given.
The package authentication system now also returns a result value, which
is used by command/init to display the result of the authentication
process.
There are three tiers of signature, each of which is presented
differently to the user:
- Signatures from the embedded HashiCorp public key indicate that the
provider is officially supported by HashiCorp;
- If the signing key is not from HashiCorp, it may have an associated
trust signature, which indicates that the provider is from one of
HashiCorp's trusted partners;
- Otherwise, if the signature is valid, this is a community provider.
2020-04-08 15:22:07 -05:00
}
2020-05-12 12:58:12 -05:00
c . Ui . Info ( fmt . Sprintf ( "- Installed %s v%s (%s%s)" , provider . ForDisplay ( ) , version , authResult , keyID ) )
} ,
2022-07-20 07:28:04 -05:00
ProvidersLockUpdated : func ( provider addrs . Provider , version getproviders . Version , localHashes [ ] getproviders . Hash , signedHashes [ ] getproviders . Hash , priorHashes [ ] getproviders . Hash ) {
// We're going to use this opportunity to track if we have any
// "incomplete" installs of providers. An incomplete install is
// when we are only going to write the local hashes into our lock
// file which means a `terraform init` command will fail in future
// when used on machines of a different architecture.
//
// We want to print a warning about this.
if len ( signedHashes ) > 0 {
// If we have any signedHashes hashes then we don't worry - as
// we know we retrieved all available hashes for this version
// anyway.
return
}
// If local hashes and prior hashes are exactly the same then
// it means we didn't record any signed hashes previously, and
// we know we're not adding any extra in now (because we already
// checked the signedHashes), so that's a problem.
//
// In the actual check here, if we have any priorHashes and those
// hashes are not the same as the local hashes then we're going to
// accept that this provider has been configured correctly.
if len ( priorHashes ) > 0 && ! reflect . DeepEqual ( localHashes , priorHashes ) {
return
}
// Now, either signedHashes is empty, or priorHashes is exactly the
// same as our localHashes which means we never retrieved the
// signedHashes previously.
//
// Either way, this is bad. Let's complain/warn.
incompleteProviders = append ( incompleteProviders , provider . ForDisplay ( ) )
} ,
2020-05-12 12:58:12 -05:00
ProvidersFetched : func ( authResults map [ addrs . Provider ] * getproviders . PackageAuthenticationResult ) {
thirdPartySigned := false
for _ , authResult := range authResults {
if authResult . ThirdPartySigned ( ) {
thirdPartySigned = true
break
}
}
if thirdPartySigned {
c . Ui . Info ( fmt . Sprintf ( "\nPartner and community providers are signed by their developers.\n" +
"If you'd like to know more about provider signing, you can read about it here:\n" +
2021-01-19 15:53:40 -06:00
"https://www.terraform.io/docs/cli/plugins/signing.html" ) )
2020-05-12 12:58:12 -05:00
}
internal: Verify provider signatures on install
Providers installed from the registry are accompanied by a list of
checksums (the "SHA256SUMS" file), which is cryptographically signed to
allow package authentication. The process of verifying this has multiple
steps:
- First we must verify that the SHA256 hash of the package archive
matches the expected hash. This could be done for local installations
too, in the future.
- Next we ensure that the expected hash returned as part of the registry
API response matches an entry in the checksum list.
- Finally we verify the cryptographic signature of the checksum list,
using the public keys provided by the registry.
Each of these steps is implemented as a separate PackageAuthentication
type. The local archive installation mechanism uses only the archive
checksum authenticator, and the HTTP installation uses all three in the
order given.
The package authentication system now also returns a result value, which
is used by command/init to display the result of the authentication
process.
There are three tiers of signature, each of which is presented
differently to the user:
- Signatures from the embedded HashiCorp public key indicate that the
provider is officially supported by HashiCorp;
- If the signing key is not from HashiCorp, it may have an associated
trust signature, which indicates that the provider is from one of
HashiCorp's trusted partners;
- Otherwise, if the signature is valid, this is a community provider.
2020-04-08 15:22:07 -05:00
} ,
2020-03-13 19:04:14 -05:00
}
2020-12-09 18:55:40 -06:00
ctx = evts . OnContext ( ctx )
2020-03-13 19:04:14 -05:00
2020-03-24 16:51:55 -05:00
mode := providercache . InstallNewProvidersOnly
if upgrade {
2021-03-09 10:12:00 -06:00
if flagLockfile == "readonly" {
c . Ui . Error ( "The -upgrade flag conflicts with -lockfile=readonly." )
return true , true , diags
}
2020-03-24 16:51:55 -05:00
mode = providercache . InstallUpgrades
}
2020-10-02 18:41:56 -05:00
newLocks , err := inst . EnsureProviderVersions ( ctx , previousLocks , reqs , mode )
2020-09-28 19:13:32 -05:00
if ctx . Err ( ) == context . Canceled {
c . showDiagnostics ( diags )
c . Ui . Error ( "Provider installation was canceled by an interrupt signal." )
return true , true , diags
}
2020-03-24 16:51:55 -05:00
if err != nil {
2020-03-13 19:04:14 -05:00
// The errors captured in "err" should be redundant with what we
// received via the InstallerEvents callbacks above, so we'll
// just return those as long as we have some.
if ! diags . HasErrors ( ) {
diags = diags . Append ( err )
}
2020-05-25 14:24:35 -05:00
2020-09-28 19:13:32 -05:00
return true , true , diags
2020-03-24 16:51:55 -05:00
}
2017-06-19 09:23:58 -05:00
2020-10-02 18:41:56 -05:00
// If the provider dependencies have changed since the last run then we'll
// say a little about that in case the reader wasn't expecting a change.
// (When we later integrate module dependencies into the lock file we'll
// probably want to refactor this so that we produce one lock-file related
// message for all changes together, but this is here for now just because
// it's the smallest change relative to what came before it, which was
// a hidden JSON file specifically for tracking providers.)
if ! newLocks . Equal ( previousLocks ) {
2021-03-09 10:12:00 -06:00
// if readonly mode
if flagLockfile == "readonly" {
// check if required provider dependences change
if ! newLocks . EqualProviderAddress ( previousLocks ) {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
` Provider dependency changes detected ` ,
` Changes to the required provider dependencies were detected, but the lock file is read-only. To use and record these requirements, run "terraform init" without the "-lockfile=readonly" flag. ` ,
) )
return true , true , diags
}
// suppress updating the file to record any new information it learned,
// such as a hash using a new scheme.
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Warning ,
` Provider lock file not updated ` ,
` Changes to the provider selections were detected, but not saved in the .terraform.lock.hcl file. To record these selections, run "terraform init" without the "-lockfile=readonly" flag. ` ,
) )
return true , false , diags
}
2022-07-20 07:28:04 -05:00
// Jump in here and add a warning if any of the providers are incomplete.
if len ( incompleteProviders ) > 0 {
// We don't really care about the order here, we just want the
// output to be deterministic.
sort . Slice ( incompleteProviders , func ( i , j int ) bool {
return incompleteProviders [ i ] < incompleteProviders [ j ]
} )
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Warning ,
incompleteLockFileInformationHeader ,
fmt . Sprintf (
incompleteLockFileInformationBody ,
strings . Join ( incompleteProviders , "\n - " ) ,
getproviders . CurrentPlatform . String ( ) ) ) )
}
2020-10-02 18:41:56 -05:00
if previousLocks . Empty ( ) {
// A change from empty to non-empty is special because it suggests
// we're running "terraform init" for the first time against a
// new configuration. In that case we'll take the opportunity to
// say a little about what the dependency lock file is, for new
// users or those who are upgrading from a previous Terraform
// version that didn't have dependency lock files.
c . Ui . Output ( c . Colorize ( ) . Color ( `
Terraform has created a lock file [ bold ] . terraform . lock . hcl [ reset ] to record the provider
selections it made above . Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future . ` ) )
} else {
c . Ui . Output ( c . Colorize ( ) . Color ( `
Terraform has made some changes to the provider dependency selections recorded
in the . terraform . lock . hcl file . Review those changes and commit them to your
version control system if they represent changes you intended to make . ` ) )
2017-06-12 20:32:42 -05:00
}
2020-10-02 18:41:56 -05:00
2021-03-29 15:03:29 -05:00
moreDiags = c . replaceLockedDependencies ( newLocks )
diags = diags . Append ( moreDiags )
}
2017-06-01 19:57:43 -05:00
2020-09-28 19:13:32 -05:00
return true , false , diags
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
}
// backendConfigOverrideBody interprets the raw values of -backend-config
// arguments into a hcl Body that should override the backend settings given
// in the configuration.
//
// If the result is nil then no override needs to be provided.
//
// If the returned diagnostics contains errors then the returned body may be
// incomplete or invalid.
func ( c * InitCommand ) backendConfigOverrideBody ( flags rawFlags , schema * configschema . Block ) ( hcl . Body , tfdiags . Diagnostics ) {
items := flags . AllItems ( )
if len ( items ) == 0 {
return nil , nil
}
var ret hcl . Body
var diags tfdiags . Diagnostics
synthVals := make ( map [ string ] cty . Value )
mergeBody := func ( newBody hcl . Body ) {
if ret == nil {
ret = newBody
} else {
ret = configs . MergeBodies ( ret , newBody )
}
}
flushVals := func ( ) {
if len ( synthVals ) == 0 {
return
}
newBody := configs . SynthBody ( "-backend-config=..." , synthVals )
mergeBody ( newBody )
synthVals = make ( map [ string ] cty . Value )
}
2019-05-29 12:58:04 -05:00
if len ( items ) == 1 && items [ 0 ] . Value == "" {
// Explicitly remove all -backend-config options.
// We do this by setting an empty but non-nil ConfigOverrides.
return configs . SynthBody ( "-backend-config=''" , synthVals ) , diags
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
for _ , item := range items {
eq := strings . Index ( item . Value , "=" )
if eq == - 1 {
// The value is interpreted as a filename.
newBody , fileDiags := c . loadHCLFile ( item . Value )
diags = diags . Append ( fileDiags )
command: Fix backend config override validation
When loading a backend config override file, init was doing two things
wrong:
- First, if the file failed to parse, we accidentally didn't return,
which caused a panic due to the parsed body being nil;
- Secondly, we were overzealous with the validation of the file,
allowing only attributes. While most backend configs are attributes
only, the enhanced remote backend body also contains a `workspaces`
block, which we need to support here.
This commit fixes the first bug with an early return and adds test cases
for missing file and intentionally-blank filename (to clear the config).
We also add a schema validation for the backend block, based on the
backend schema itself. This requires constructing an HCL body schema so
that we can call `Content` and check for diagnostic errors.
The result is more useful errors when an invalid backend config override
file is used, while also supporting the enhanced remote backend config
fully.
Does not include tests specific to the remote backend, because the
mocking involved to allow the backend to fully initialize is too
involved to be worth it.
2020-08-21 15:10:06 -05:00
if fileDiags . HasErrors ( ) {
continue
}
// Generate an HCL body schema for the backend block.
var bodySchema hcl . BodySchema
2020-08-26 09:50:47 -05:00
for name := range schema . Attributes {
// We intentionally ignore the `Required` attribute here
// because backend config override files can be partial. The
// goal is to make sure we're not loading a file with
// extraneous attributes or blocks.
command: Fix backend config override validation
When loading a backend config override file, init was doing two things
wrong:
- First, if the file failed to parse, we accidentally didn't return,
which caused a panic due to the parsed body being nil;
- Secondly, we were overzealous with the validation of the file,
allowing only attributes. While most backend configs are attributes
only, the enhanced remote backend body also contains a `workspaces`
block, which we need to support here.
This commit fixes the first bug with an early return and adds test cases
for missing file and intentionally-blank filename (to clear the config).
We also add a schema validation for the backend block, based on the
backend schema itself. This requires constructing an HCL body schema so
that we can call `Content` and check for diagnostic errors.
The result is more useful errors when an invalid backend config override
file is used, while also supporting the enhanced remote backend config
fully.
Does not include tests specific to the remote backend, because the
mocking involved to allow the backend to fully initialize is too
involved to be worth it.
2020-08-21 15:10:06 -05:00
bodySchema . Attributes = append ( bodySchema . Attributes , hcl . AttributeSchema {
2020-08-26 09:50:47 -05:00
Name : name ,
command: Fix backend config override validation
When loading a backend config override file, init was doing two things
wrong:
- First, if the file failed to parse, we accidentally didn't return,
which caused a panic due to the parsed body being nil;
- Secondly, we were overzealous with the validation of the file,
allowing only attributes. While most backend configs are attributes
only, the enhanced remote backend body also contains a `workspaces`
block, which we need to support here.
This commit fixes the first bug with an early return and adds test cases
for missing file and intentionally-blank filename (to clear the config).
We also add a schema validation for the backend block, based on the
backend schema itself. This requires constructing an HCL body schema so
that we can call `Content` and check for diagnostic errors.
The result is more useful errors when an invalid backend config override
file is used, while also supporting the enhanced remote backend config
fully.
Does not include tests specific to the remote backend, because the
mocking involved to allow the backend to fully initialize is too
involved to be worth it.
2020-08-21 15:10:06 -05:00
} )
}
for name , block := range schema . BlockTypes {
var labelNames [ ] string
if block . Nesting == configschema . NestingMap {
labelNames = append ( labelNames , "key" )
}
bodySchema . Blocks = append ( bodySchema . Blocks , hcl . BlockHeaderSchema {
Type : name ,
LabelNames : labelNames ,
} )
}
// Verify that the file body matches the expected backend schema.
_ , schemaDiags := newBody . Content ( & bodySchema )
diags = diags . Append ( schemaDiags )
if schemaDiags . HasErrors ( ) {
2020-06-26 11:49:31 -05:00
continue
}
command: "terraform init" can partially initialize for 0.12upgrade
There are a few constructs from 0.11 and prior that cause 0.12 parsing to
fail altogether, which previously created a chicken/egg problem because
we need to install the providers in order to run "terraform 0.12upgrade"
and thus fix the problem.
This changes "terraform init" to use the new "early configuration" loader
for module and provider installation. This is built on the more permissive
parser in the terraform-config-inspect package, and so it allows us to
read out the top-level blocks from the configuration while accepting
legacy HCL syntax.
In the long run this will let us do version compatibility detection before
attempting a "real" config load, giving us better error messages for any
future syntax additions, but in the short term the key thing is that it
allows us to install the dependencies even if the configuration isn't
fully valid.
Because backend init still requires full configuration, this introduces a
new mode of terraform init where it detects heuristically if it seems like
we need to do a configuration upgrade and does a partial init if so,
before finally directing the user to run "terraform 0.12upgrade" before
running any other commands.
The heuristic here is based on two assumptions:
- If the "early" loader finds no errors but the normal loader does, the
configuration is likely to be valid for Terraform 0.11 but not 0.12.
- If there's already a version constraint in the configuration that
excludes Terraform versions prior to v0.12 then the configuration is
probably _already_ upgraded and so it's just a normal syntax error,
even if the early loader didn't detect it.
Once the upgrade process is removed in 0.13.0 (users will be required to
go stepwise 0.11 -> 0.12 -> 0.13 to upgrade after that), some of this can
be simplified to remove that special mode, but the idea of doing the
dependency version checks against the liberal parser will remain valuable
to increase our chances of reporting version-based incompatibilities
rather than syntax errors as we add new features in future.
2019-01-14 13:11:00 -06:00
flushVals ( ) // deal with any accumulated individual values first
mergeBody ( newBody )
} else {
name := item . Value [ : eq ]
rawValue := item . Value [ eq + 1 : ]
attrS := schema . Attributes [ name ]
if attrS == nil {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid backend configuration argument" ,
fmt . Sprintf ( "The backend configuration argument %q given on the command line is not expected for the selected backend type." , name ) ,
) )
continue
}
value , valueDiags := configValueFromCLI ( item . String ( ) , rawValue , attrS . Type )
diags = diags . Append ( valueDiags )
if valueDiags . HasErrors ( ) {
continue
}
synthVals [ name ] = value
}
}
flushVals ( )
return ret , diags
2017-05-03 10:02:47 -05:00
}
2017-09-25 20:09:43 -05:00
func ( c * InitCommand ) AutocompleteArgs ( ) complete . Predictor {
return complete . PredictDirs ( "" )
}
func ( c * InitCommand ) AutocompleteFlags ( ) complete . Flags {
return complete . Flags {
"-backend" : completePredictBoolean ,
2021-11-19 11:54:06 -06:00
"-cloud" : completePredictBoolean ,
2017-09-25 20:09:43 -05:00
"-backend-config" : complete . PredictFiles ( "*.tfvars" ) , // can also be key=value, but we can't "predict" that
"-force-copy" : complete . PredictNothing ,
"-from-module" : completePredictModuleSource ,
"-get" : completePredictBoolean ,
"-input" : completePredictBoolean ,
2021-10-18 13:41:04 -05:00
"-lock" : completePredictBoolean ,
"-lock-timeout" : complete . PredictAnything ,
2017-09-25 20:09:43 -05:00
"-no-color" : complete . PredictNothing ,
"-plugin-dir" : complete . PredictDirs ( "" ) ,
"-reconfigure" : complete . PredictNothing ,
2021-05-17 11:19:36 -05:00
"-migrate-state" : complete . PredictNothing ,
2017-09-25 20:09:43 -05:00
"-upgrade" : completePredictBoolean ,
}
}
2014-09-26 18:03:39 -05:00
func ( c * InitCommand ) Help ( ) string {
helpText := `
2021-02-22 08:25:56 -06:00
Usage : terraform [ global options ] init [ options ]
2017-01-18 22:50:45 -06:00
2017-06-02 18:59:52 -05:00
Initialize a new or existing Terraform working directory by creating
2017-01-18 22:50:45 -06:00
initial files , loading any remote state , downloading modules , etc .
This is the first command that should be run for any new or existing
Terraform configuration per machine . This sets up all the local data
2017-04-26 09:10:04 -05:00
necessary to run Terraform that is typically not committed to version
2017-01-18 22:50:45 -06:00
control .
This command is always safe to run multiple times . Though subsequent runs
2017-06-02 18:59:52 -05:00
may give errors , this command will never delete your configuration or
state . Even so , if you have important information , please back it up prior
to running this command , just in case .
2014-09-26 18:03:39 -05:00
2014-09-30 18:05:40 -05:00
Options :
2022-03-25 09:31:52 -05:00
- backend = false Disable backend or Terraform Cloud initialization
for this configuration and use what was previously
2021-11-19 11:54:06 -06:00
initialized instead .
aliases : - cloud = false
2014-12-04 21:06:47 -06:00
2021-11-19 13:53:09 -06:00
- backend - config = path Configuration to be merged with what is in the
configuration file ' s ' backend ' block . This can be
either a path to an HCL file with key / value
2021-06-02 14:30:05 -05:00
assignments ( same format as terraform . tfvars ) or a
2021-11-19 13:53:09 -06:00
' key = value ' format , and can be specified multiple
2021-06-02 14:30:05 -05:00
times . The backend type must be in the configuration
itself .
2014-09-30 18:05:40 -05:00
2021-11-19 13:53:09 -06:00
- force - copy Suppress prompts about copying state data when
initializating a new state backend . This is
2021-06-02 14:30:05 -05:00
equivalent to providing a "yes" to all confirmation
prompts .
2017-04-20 16:26:50 -05:00
2021-06-02 14:30:05 -05:00
- from - module = SOURCE Copy the contents of the given module into the target
directory before initialization .
2017-07-28 17:23:29 -05:00
2021-10-18 13:41:04 -05:00
- get = false Disable downloading modules for this configuration .
2017-01-18 22:50:45 -06:00
2021-11-19 13:53:09 -06:00
- input = false Disable interactive prompts . Note that some actions may
require interactive prompts and will error if input is
disabled .
2021-10-18 13:41:04 -05:00
- lock = false Don ' t hold a state lock during backend migration .
This is dangerous if others might concurrently run
commands against the same workspace .
- lock - timeout = 0 s Duration to retry a state lock .
2017-01-18 22:50:45 -06:00
2021-06-02 14:30:05 -05:00
- no - color If specified , output won ' t contain any color .
2015-06-22 07:14:01 -05:00
2021-06-02 14:30:05 -05:00
- plugin - dir Directory containing plugin binaries . This overrides all
default search paths for plugins , and prevents the
automatic installation of plugins . This flag can be used
multiple times .
2017-06-15 14:23:16 -05:00
2021-11-19 13:53:09 -06:00
- reconfigure Reconfigure a backend , ignoring any saved
2021-06-02 14:30:05 -05:00
configuration .
2017-06-12 16:14:40 -05:00
2021-11-19 13:53:09 -06:00
- migrate - state Reconfigure a backend , and attempt to migrate any
2021-06-02 14:30:05 -05:00
existing state .
2021-05-17 11:19:36 -05:00
2021-10-18 13:41:04 -05:00
- upgrade Install the latest module and provider versions
allowed within configured constraints , overriding the
default behavior of selecting exactly the version
recorded in the dependency lockfile .
2021-03-09 10:12:00 -06:00
2021-06-02 14:30:05 -05:00
- lockfile = MODE Set a dependency lockfile mode .
Currently only "readonly" is valid .
2021-11-19 13:53:09 -06:00
- ignore - remote - version A rare option used for Terraform Cloud and the remote backend
only . Set this to ignore checking that the local and remote
Terraform versions use compatible state representations , making
an operation proceed even when there is a potential mismatch .
See the documentation on configuring Terraform with
Terraform Cloud for more information .
2021-03-09 10:12:00 -06:00
2014-09-26 18:03:39 -05:00
`
return strings . TrimSpace ( helpText )
}
func ( c * InitCommand ) Synopsis ( ) string {
2020-10-23 18:55:32 -05:00
return "Prepare your working directory for other commands"
2014-09-26 18:03:39 -05:00
}
2017-01-18 22:50:45 -06:00
2017-10-05 14:00:45 -05:00
const errInitConfigError = `
2020-07-07 17:19:41 -05:00
[ reset ] There are some problems with the configuration , described below .
2017-10-05 14:00:45 -05:00
The Terraform configuration must be valid before initialization so that
Terraform can determine which modules and providers need to be installed .
`
2017-01-18 22:50:45 -06:00
const errInitCopyNotEmpty = `
2017-07-28 17:23:29 -05:00
The working directory already contains files . The - from - module option requires
an empty directory into which a copy of the referenced module will be placed .
2017-01-18 22:50:45 -06:00
2017-07-28 17:23:29 -05:00
To initialize the configuration already in this working directory , omit the
- from - module option .
2017-01-18 22:50:45 -06:00
`
const outputInitEmpty = `
[ reset ] [ bold ] Terraform initialized in an empty directory ! [ reset ]
The directory has no Terraform configuration files . You may begin working
with Terraform immediately by creating Terraform configuration files .
`
const outputInitSuccess = `
[ reset ] [ bold ] [ green ] Terraform has been successfully initialized ! [ reset ] [ green ]
2017-09-08 19:14:37 -05:00
`
2017-01-18 22:50:45 -06:00
2021-10-13 10:22:12 -05:00
const outputInitSuccessCloud = `
[ reset ] [ bold ] [ green ] Terraform Cloud has been successfully initialized ! [ reset ] [ green ]
`
2017-09-08 19:14:37 -05:00
const outputInitSuccessCLI = ` [ reset ] [ green ]
2017-01-18 22:50:45 -06:00
You may now begin working with Terraform . Try running "terraform plan" to see
any changes that are required for your infrastructure . All Terraform commands
should now work .
If you ever set or change modules or backend configuration for Terraform ,
2017-06-02 18:59:52 -05:00
rerun this command to reinitialize your working directory . If you forget , other
2017-01-18 22:50:45 -06:00
commands will detect it and remind you to do so if necessary .
`
2017-06-01 19:57:43 -05:00
2021-10-13 10:22:12 -05:00
const outputInitSuccessCLICloud = ` [ reset ] [ green ]
You may now begin working with Terraform Cloud . Try running "terraform plan" to
see any changes that are required for your infrastructure .
2021-10-21 08:40:09 -05:00
If you ever set or change modules or Terraform Settings , run "terraform init"
again to reinitialize your working directory .
2021-10-13 10:22:12 -05:00
`
2020-05-11 12:49:12 -05:00
// providerProtocolTooOld is a message sent to the CLI UI if the provider's
// supported protocol versions are too old for the user's version of terraform,
// but a newer version of the provider is compatible.
const providerProtocolTooOld = ` Provider % q v % s is not compatible with Terraform % s .
Provider version % s is the latest compatible version . Select it with the following version constraint :
version = % q
Terraform checked all of the plugin versions matching the given constraint :
% s
Consult the documentation for this provider for more information on compatibility between provider and Terraform versions .
`
// providerProtocolTooNew is a message sent to the CLI UI if the provider's
// supported protocol versions are too new for the user's version of terraform,
// and the user could either upgrade terraform or choose an older version of the
// provider.
const providerProtocolTooNew = ` Provider % q v % s is not compatible with Terraform % s .
You need to downgrade to v % s or earlier . Select it with the following constraint :
version = % q
Terraform checked all of the plugin versions matching the given constraint :
% s
Consult the documentation for this provider for more information on compatibility between provider and Terraform versions .
Alternatively , upgrade to the latest version of Terraform for compatibility with newer provider releases .
`
// No version of the provider is compatible.
const errProviderVersionIncompatible = ` No compatible versions of provider %s were found. `
2022-07-20 07:28:04 -05:00
// incompleteLockFileInformationHeader is the summary displayed to users when
// the lock file has only recorded local hashes.
const incompleteLockFileInformationHeader = ` Incomplete lock file information for providers `
// incompleteLockFileInformationBody is the body of text displayed to users when
// the lock file has only recorded local hashes.
const incompleteLockFileInformationBody = ` Due to your customized provider installation methods , Terraform was forced to calculate lock file checksums locally for the following providers :
- % s
The current . terraform . lock . hcl file only includes checksums for % s , so Terraform running on another platform will fail to install these providers .
To calculate additional checksums for another platform , run :
terraform providers lock - platform = linux_amd64
( where linux_amd64 is the platform to generate ) `