* Update `internal/command` to use OpenTF
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix e2e tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix e2e tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Rewrite message.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
---------
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Update `internal/command/views`
Signed-off-by: Marcin Białoń <mbialon@spacelift.io>
* fix tests
Signed-off-by: Marcin Białoń <mbialon@spacelift.io>
* Fix some tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix some tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* update tests golden files
Signed-off-by: Marcin Białoń <mbialon@spacelift.io>
* Fix tests
Signed-off-by: Marcin Białoń <mbialon@spacelift.io>
* Fix tests
Signed-off-by: Marcin Białoń <mbialon@spacelift.io>
* Fix tests
Signed-off-by: Marcin Białoń <mbialon@spacelift.io>
---------
Signed-off-by: Marcin Białoń <mbialon@spacelift.io>
Signed-off-by: Jakub Martin <kubam@spacelift.io>
Co-authored-by: Jakub Martin <kubam@spacelift.io>
* Use ~/.opentf.d instead of ~/.terraform.d
Stay backwards-compatible, though.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix imports.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Add tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Use util function.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix windows directories.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Add a comment to the tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
---------
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Change PKG_NAME
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix rpm and deb packaging.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix e2e test step.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix e2e test step.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix e2e test step.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix docker build.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix exec tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix e2e tests.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix docker build.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
---------
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Rename module name from "github.com/hashicorp/terraform" to "github.com/placeholderplaceholderplaceholder/opentf".
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Gofmt.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Regenerate protobuf.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix comments.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Undo issue and pull request link changes.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Undo comment changes.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Fix comment.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* Undo some link changes.
Signed-off-by: Jakub Martin <kubam@spacelift.io>
* make generate && make protobuf
Signed-off-by: Jakub Martin <kubam@spacelift.io>
---------
Signed-off-by: Jakub Martin <kubam@spacelift.io>
The import block id field can now reference variables, attributes, and module outputs, as long as the result is a known non-empty string at plan time. A null or unknown value will result in an error.
This commit slightly modifies the legacy CLI terraform import code path to construct a synthetic hcl.Expression from the import id passed in from the command line, with no intended change of functionality.
Since terraform show can accept three different kinds of file to act on, its
error messages were starting to become untidy and unhelpful. The main issue was
that if we successfully identified the file type but then ran into some problem
while reading or processing it, the "real" error would be obscured by some other
useless errors (since a file of one type is necessarily invalid as the other
types).
This commit tries to winnow it down to just one best error message, in the
"happy path" case where we know what we're dealing with but hit a snag. (If we
still have no idea, then we fall back to dumping everything.)
One funny bit: We need to know the ViewType at the point where we ask the Cloud
backend for the plan JSON, because we need to switch between two distinctly
different formats for human show vs. `show -json`. I chose to pass that by
stashing it on the command struct; passing it as an argument would also work,
but one, the argument lists in these nested method calls were getting a little
unwieldy, and two, many of these functions had to be receiver methods anyway in
order to call methods on Meta.
This commit replaces the existing jsonformat.PlanRendererOpt type with a new
type with identical semantics, located in the plans package.
We needed to be able to exchange the facts represented by
`jsonformat.PlanRendererOpt` across some package boundaries, but the jsonformat
package is implicated in too many dependency chains to be safe for that purpose!
So, we had to make a new one. The plans package seems safe to import from all
the places that must emit or accept this info, and already contains plans.Mode,
which is effectively a sibling of this type.
It displays a run header with link to web UI, like starting a new plan does, then confirms the run
and streams the apply logs. If you can't apply the run (it's from a different workspace, is in an
unconfirmable state, etc. etc.), it displays an error instead.
Notable points along the way:
* Implement `WrappedPlanFile` sum type, and update planfile consumers to use it instead of a plain `planfile.Reader`.
* Enable applying a saved cloud plan
* Update TFC mocks — add org name to workspace, and minimal support for includes on MockRuns.ReadWithOptions.
Previously, remote and cloud backends would automatically alias localterraform.com as the configured hostname during configuration. This turned out to be an issue with how backends could potentially be used within the builtin terraform_remote_state data source. Those data sources each configure the same service discovery with different targets for localterraform.com, and do so simultaneously, creating an occasional concurrent map read & write panic when multiple data sources are defined.
localterraform.com is obviously not useful for every backend configuration. Therefore, I relocated the alias configuration to the callers, so they may specify when to use it. The modified design adds a new method to backend.Enhanced to allow configurators to ask which aliases should be defined.
* Implement word wrapping in the terraform test view functions
* Update internal/command/views/test.go
Co-authored-by: CJ Horton <17039873+radditude@users.noreply.github.com>
---------
Co-authored-by: CJ Horton <17039873+radditude@users.noreply.github.com>
Several times over the years we've considered adding tracing
instrumentation to Terraform, since even when running in isolation as a
CLI program it has a "distributed system-like" structure, with lots of
concurrent internal work and also some work delegated to provider plugins
that are essentially temporarily-running microservices.
However, it's always felt a bit overwhelming to do it because much of
Terraform predates the Go context.Context idiom and so it's tough to get
a clean chain of context.Context values all the way down the stack without
disturbing a lot of existing APIs.
This commit aims to just get that process started by establishing how a
context can propagate from "package main" into the command package,
focusing initially on "terraform init" and some other commands that share
some underlying functions with that command.
OpenTelemetry has emerged as a de-facto industry standard and so this uses
its API directly, without any attempt to hide it behind an abstraction.
The OpenTelemetry API is itself already an adapter layer, so we should be
able to swap in any backend that uses comparable concepts. For now we just
discard the tracing reports by default, and allow users to opt in to
delivering traces over OTLP by setting an environment variable when
running Terraform (the environment variable was established in an earlier
commit, so this commit builds on that.)
When tracing collection is enabled, every Terraform CLI run will generate
at least one overall span representing the command that was run. Some
commands might also create child spans, but most currently do not.
* [testing framework] prepare for beta phase of development
* [Testing Framework] Add module block to test run blocks
* [testing framework] allow tests to define and override providers
* testing framework: introduce interrupts for stopping tests
* remove panic handling, will do it properly later
* [testing framework] prepare for beta phase of development
* [Testing Framework] Add module block to test run blocks
* [testing framework] allow tests to define and override providers
* main: disambiguate arg ordering test
Make it extra clear what order of args we are asserting.
* command: fix plan -refresh=false test
The test for plan -refresh=false was not functioning, since ReadResource will not be called if the resource is not in prior state.
Add a new fixture directory with state, and also test the converse, to prevent regression.
* command: add test for refresh flag precedence
A consumer relies on the fact that running terraform plan -refresh=false -refresh true gives the same result as terraform plan -refresh=true.
Add a single global schema cache for providers. This allows multiple
provider instances to share a single copy of the schema, and prevents
loading the schema multiple times for a given provider type during a
single command.
This does not currently work with some provider releases, which are
using GetProviderSchema to trigger certain initializations. A new server
capability will be introduced to trigger reloading their schemas, but
not store duplicate results.
* Add test structure to views package for rendering test output
* Add test file HCL configuration and parser functionality
* Adds a TestContext structure for evaluating assertions against the state and plan
* Add test command to Terraform CLI
* cloud: assert import block compatibility
* check for import <> TFC compatibility during init
* imports are not in alphabetical order 🙃
---------
Co-authored-by: CJ Horton <cjhorton@hashicorp.com>
* genconfig: fix nil nested block panic
* genconfig: null NestingSingle blocks should be absent
A NestingSingle block that is null in state should be completely absent from config.
* configschema: make FilterOr variadic
* configschema: apply filters to nested types
* configschema: filter helper/schema id attribute
The legacy SDK adds an Optional+Computed "id" attribute to the
resource schema even if not defined in provider code.
During validation, however, the presence of an extraneous "id"
attribute in config will cause an error.
Remove this attribute so we do not generate an "id" attribute
where there is a risk that it is not in the real resource schema.
* configschema: filter test
* terraform: do not pre-validate generated config
Config generated from a resource's import state may fail validation in
the case of schema behaviours such as ExactlyOneOf and ConflictsWith.
We don't want to fail the plan now, because that would give the user no
way to proceed and fix the config to make it valid. We allow the plan to
complete and output the generated config.
* generate config alongside import process
Rather than waiting until we call `plan()`, generate the configuration
at the point of the import call, so we have the necessary data to return
in case planning fails later.
The `plan` and `state` predeclared variables in the plan() method were
obfuscating the actual return of nil throughout, so those identifiers
were removed for clarity.
* move generateHCLStringAttributes closer to caller
* store generated config in plan on error
* test for config gen with error
* add simple warning when generating config
---------
Co-authored-by: James Bardin <j.bardin@gmail.com>
* command: keep our promises
* remove some nil config checks
Remove some of the safety checks that ensure plan nodes have config attached at the appropriate time.
* add GeneratedConfig to plan changes objects
Add a new GeneratedConfig field alongside Importing in plan changes.
* add config generation package
The genconfig package implements HCL config generation from provider state values.
Thanks to @mildwonkey whose implementation of terraform add is the basis for this package.
* generate config during plan
If a resource is being imported and does not already have config, attempt to generate that config during planning. The config is generated from the state as an HCL string, and then parsed back into an hcl.Body to attach to the plan graph node.
The generated config string is attached to the change emitted by the plan.
* complete config generation prototype, and add tests
* Plannable import: Add generated config to json and human-readable plan output
---------
Co-authored-by: Katy Moe <katy@katy.moe>
* command: keep our promises
* remove some nil config checks
Remove some of the safety checks that ensure plan nodes have config attached at the appropriate time.
* add GeneratedConfig to plan changes objects
Add a new GeneratedConfig field alongside Importing in plan changes.
* add config generation package
The genconfig package implements HCL config generation from provider state values.
Thanks to @mildwonkey whose implementation of terraform add is the basis for this package.
* generate config during plan
If a resource is being imported and does not already have config, attempt to generate that config during planning. The config is generated from the state as an HCL string, and then parsed back into an hcl.Body to attach to the plan graph node.
The generated config string is attached to the change emitted by the plan.
* complete config generation prototype, and add tests
---------
Co-authored-by: Katy Moe <katy@katy.moe>
* [plannable import] embed the resource id within the changes
* [Plannable Import] Implement streamed logs for -json plan
* use latest structs
* remove implementation plans from TODO
* Add support for scoped resources
* refactor existing checks addrs and add check block addr
* Add configuration for check blocks
* introduce check blocks into the terraform node and transform graph
* address comments
* address comments
* don't execute checks during destroy operations
* don't even include check nodes for destroy operations
This is a mostly mechanical refactor with a handful of changes which
are necessary due to the semantic difference between earlyconfig and
configs.
When parsing root and descendant modules in the module installer, we now
check the core version requirements inline. If the Terraform version is
incompatible, we drop any other module loader diagnostics. This ensures
that future language additions don't clutter the output and confuse the
user.
We also add two new checks during the module load process:
* Don't try to load a module with a `nil` source address. This is a
necessary change due to the move away from earlyconfig.
* Don't try to load a module with a blank name (i.e. `module ""`).
Because our module loading manifest uses the stringified module path
as its map key, this causes a collision with the root module, and a
later panic. This is the bug which triggered this refactor in the
first place.
Since it's already possible to activate the dependency lock file using an
environment variable, we should allow opting in to it having broken
behavior using the environment too.
It's kinda odd in retrospect that TF_PLUGIN_CACHE_DIR is the only setting
we allow to be configured both in the environment and the CLI
configuration. That means that the infrastructure for dealing with that
situation was relatively immature here and so I did some light refactoring
to make it unit-testable without actually modifying the test program's
environment.
With the demise of the early config loader, we want to show core
version errors first, followed by backend errors, and only then
show other errors with the configuration.
* Add metadata functions command skeleton
* Export functions as JSON via cli command
* Add metadata command
* Add tests to jsonfunction package
* WIP: Add metadata functions test
* Change return_type & type in JSON to json.RawMessage
This enables easier deserialisation of types when parsing the JSON.
* Skip is_nullable when false
* Update cli docs with metadata command
* Use tfdiags to report function marshal errors
* Ignore map, list and type functions
* Test Marshal function with diags
* Test metadata functions command output
* Simplify type marshaling by using cty.Type
* Add static function signatures for can and try
* Update internal/command/jsonfunction/function_test.go
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
---------
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
* Implementation of structured logging.
These are the changes that enable the cloud backend to consume
structured logs and make use of the new plan renderer. This will enable
CLI-driven runs to view the structured output in the Terraform Cloud UI.
* Cloud structured logging unit tests
* Remove deferred logs logic, fix minor issues
Color formatting fixes, log type stop lists, default behavior for logs
that are unknown
* Use service disco path in redacted plan url
* Add viewType to Meta object and use it at the call sites
* Assign viewType passed from flags to state-locking cli commands
* Remove temp files
* Set correct mode for statelocker depending on json flag passed to commands
* Add StateLocker interface conformation check for StateLockerJSON
* Remove empty line at end of comment
* Pass correct ViewType to StateLocker from Backend call chain
* Pass viewType to backend migration and initialization functions
* Remove json processing info in process comment
* Restore documentation style of backendMigrateOpts
As explained by the deleted comments, this package was used to identify situations where the `terraform 0.12upgrade` command can help migrate 0.11 syntax. Current versions of terraform don't include this command, and it's not likely that users are attempting upgrades from 0.11 to 1.4+
The replacement init swaps the order of the module and backend initialization in order to prepare for the next commit.
Config initialization now takes the following approach:
1. Load the root module, but withhold diagnostic errors until after version check
2. Initialize the backend, but withhold diagnostic errors until after version check
3. Get modules
4. Load all config (root and modules)
5. Check terraform version requirements (this can be defined by nested modules) and display any errors. It's important to show these first because prior errors could be the result of a newer terraform version syntax
6. Finally, show any errors related to backed init or config loading
* Add mTLS support for http backend by way of client cert & key, as well as enterprise cacert.
* Fix style.
* Skip cert validation to be sure error is related to missing client cert; not untrusted server cert.
* Remove misplaced err check.
* Fix the size of test using http backend.
* Just for correctness, include all certs in the pem encoded cert - sometimes certs come with a chain of their signers.
* Adjusted names as recommended in PR comments.
* Adjusted names to be full-length and more descriptive.
* Added full-fledged testing with mTLS http server
* Fix goimports.
* Fix the names of the backend config.
* Exclusive lock for write and delete.
* Revert "Fix goimports."
This reverts commit 7d40f6099fbbb675fb2e25e35ee40aeafe3d0a22.
* goimports just for server test.
* Added the go:generation for the mock.
* Move the TLS configuration out to make it more readable - don't replace the HTTPClient as the retryablehttp already creates one - just configure its TLS.
* Just switch the client/data params - felt more natural this way.
* Update internal/backend/remote-state/http/backend.go
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
* Update internal/backend/remote-state/http/testdata/gencerts.sh
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
* Update internal/backend/remote-state/http/backend.go
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
* Update internal/backend/remote-state/http/backend.go
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
* Update internal/backend/remote-state/http/backend.go
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
* Update internal/backend/remote-state/http/backend.go
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
* the location of the file name is not sensitive.
* Added error if only one of client_certificate_pem and client_private_key_pem are set.
* Remove testify from test cases; use t.Error* for assert and t.Fatal* for require.
* Fixed import consistency
* Just use default openssl.
* Since file(...) is so trivial to use, changed the client cert, key, and ca cert to be the data.
See also https://github.com/hashicorp/terraform-provider-http/pull/211
Co-authored-by: Sheridan C Rawlins <scr@ouryahoo.com>
Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
Currently Terraform will use an entry from the global plugin cache only if
it matches a checksum already recorded in the dependency lock file. This
allows Terraform to produce a complete lock file entry on the first
encounter with a new provider, whereas using the cache in that case would
cause the lock file to only cover the single package in the cache and
thereefore be unusable on any other operating system or CPU architecture.
This temporary CLI config option is a pragmatic exception to support those
who cannot currently correctly use the dependency lock file but who still
want to benefit from the plugin cache. With this setting enabled,
Terraform has permission to produce a dependency lock file that is only
suitable for the current system if that would allow use of an existing
entry in the plugin cache.
We are introducing this option to resolve a conflict between the needs of
folks who are using the dependency lock file as expected and the needs of
folks who cannot use the dependency lock file for some reason. The hope
then is to give respite to those who need this exception in the meantime
while we understand better why they cannot use the dependency lock file
and improve its design so that everyone will be able to use it
successfully in a future version of Terraform. This option will become a
silent no-op in a future version of Terraform, once the dependency lock
file behavior is sufficient for all supported Terraform development
workflows.
* Use the new structured renderer in place of the old diffs package
* remove old plan tests
* refresh only plans should show moved resources in the refresh section
* remove attributes that do not match the relevant attributes filter
* fix formatting
* fix renderer function, don't drop irrelevant attributes just mark them as no-ops
* fix imports
* fix bugs in the renderer exposed by the equivalence tests
* imports
* gofmt
* remove attributes that do not match the relevant attributes filter
* fix formatting
* fix renderer function, don't drop irrelevant attributes just mark them as no-ops
* fix imports
* raw unmodified broken tests
* tests execute, no panics
* fix whitespace differences
* fix all the tests
* fix tests
* actually fix tests
* add missing plan metadata into the renderer
* address comments
* complete merge
* remove TODO raising questions about outputs, they are fixed
* missing bold on plan
* pause implementation
* change -> diff, value -> change
* add support for json and multiline strings to the primitive renderer
* goimports
* remove unused function
* go fmt
* address comments
* change -> diff, value -> change
* also update readme#
* pause
* Update internal/command/jsonformat/computed/diff.go
Co-authored-by: Alisdair McDiarmid <alisdair@users.noreply.github.com>
* add interface assertions for diff renderers
* Add support for different kinds of blocks, and for sensitive blocks
Co-authored-by: Alisdair McDiarmid <alisdair@users.noreply.github.com>