Commit Graph

2539 Commits

Author SHA1 Message Date
Martin Atkins 0ac663bb2b core: context plan tests update wanted output for new behavior
Previously Terraform Core was unaware of the structure of a resource type
schema and so the strange behavior of our testDiffFn caused some
attributes to not appear at all in the result. With core now more aware,
it "fills in" these missing items before calling, and as a result they
now appear in the diff even with the testDiffFn.

In real code, where helper/schema is constructing diffs, this situation
doesn't arise because the framework always produces schema-compatible
diffs.
2018-10-16 18:49:20 -07:00
Martin Atkins e850becf64 core: update context plan tests for new module address rendering
The diff stringer now uses the standard serialization of a module address,
so we need to update the golden representations to restore their
associated tests to passing.
2018-10-16 18:49:20 -07:00
Martin Atkins 1a547b5351 core: Rename "count" variables in context plan fixtures
This variable name is now reserved so we can support the count
meta-argument inside module blocks in a later release.
2018-10-16 18:49:20 -07:00
James Bardin cdc8abdae0 add missing Operation to the Evaluator 2018-10-16 18:48:28 -07:00
James Bardin d55d623ef0 handle unset computed values in tests
The old testDiffFn used th raw config to dynamically set computed values
in the diff. Since the schema now defines what values should be there,
all test diffs end up with unkown computed values. Filter these out by
looking for a value set to "compute"
2018-10-16 18:48:28 -07:00
Martin Atkins 77bc36abce core: Make context_plan_test failure output more helpful
Lots of the tests were previously only producing the actual result, and
not what was expected. Now we'll show both, to make debugging easier.
2018-10-16 18:48:28 -07:00
Martin Atkins cc5b1d452f core: NewInstanceInfo now produces correct "id" for data resources
We need to mimic the old API here, and we weren't doing that quite right
since the "data" prefix was missing from data resources.
2018-10-16 18:48:28 -07:00
Martin Atkins eb54715902 core: fix string rendering of modules in diffs
This was assuming our old practice of a slice starting with the string
"root". We'll normalize here and then stringify the result to ensure that
we get a string consistent with what's used elsewhere.

This is primarily aimed at fixing some of the context plan tests.
2018-10-16 18:48:28 -07:00
Martin Atkins 39dfc9f4e0 core: Fix schema-related issues in context plan tests
Most changes here just introduce some custom schema into the test mocks.
In some cases, a fixture is lightly updated to more modern assumptions.

The test for accessing count.index in a resource block without count set
is removed, because that is no longer valid under the new language
implementation.
2018-10-16 18:48:28 -07:00
Martin Atkins 2b3b6c2407 core: TestContext2Plan_countComputedModule expectedErr
The phrasing of this message changed as part of updating it to use HCL
diagnostics rather than just a string.
2018-10-16 18:48:28 -07:00
James Bardin e6478599c6 strip unknown values from the resource config
Computed values are now all added to the config value as unknowns. Strip
these out to match the legacy expatiations.
2018-10-16 18:48:28 -07:00
Martin Atkins d6d655f21d core: Context plan tests expect a new error message for prevent_destroy
This error message has been revised as part of changing it to use
diagnostics instead of an error string directly.
2018-10-16 18:48:28 -07:00
Martin Atkins 5a77045a61 core: Move invalid output context tests to "validate"
This problem should now be caught at validate time rather than plan time,
because we can use the schema to detect the problem before the resource
has been resolved.
2018-10-16 18:48:28 -07:00
Martin Atkins 824986b698 core: use correct provider config address when eval pending resources
The evaluate data source was using a guessed provider configuration
address from configuration in this case, but that isn't necessarily
correct since the resource might actually be associated with a config
inherited from a parent module.

We still need to retain that fallback to config because we are sometimes
asked to evaluate when state is incomplete (like in "terraform console"),
but if possible we'll take the stored provider address from the state
and use that, even if the resource is otherwise "pending".
2018-10-16 18:48:28 -07:00
James Bardin cae5c2feaa update apply tests 2018-10-16 18:48:28 -07:00
James Bardin 492a3b09fa deposed nodes need the resolved provider too
The provider is looked up by the ResolvedProvider
2018-10-16 18:48:28 -07:00
James Bardin f8b77030db destroy nodes can't be referenced directly
Destroy nodes were being referenced by their regular paths, which was
causing cycles in the graphs. Destroy nodes can't be referenced directly
in any way, so override the inherited method for a referenceable address.
2018-10-16 18:48:28 -07:00
James Bardin 7137d85522 ignore id when creating diffs
The id field is always computed, and never directly related to a diff.
Since that field is being converted to a regular schema attribute, we
need to handle the behavior in the mocks too.
2018-10-16 18:48:28 -07:00
Martin Atkins e528fe50e9 core: Misc. updates to the "plan" context tests
Mostly this is about updating ctx.Plan callers to expect diags instead of
err, but also includes a few light updates to test fixtures, and a fix to
testModuleInline.
2018-10-16 18:48:28 -07:00
James Bardin 6bf70427dd lock the provisioner mutex in ProvisionerSchema 2018-10-16 18:48:28 -07:00
James Bardin cdaeed4f26 a provisioner may not always have a connection 2018-10-16 18:48:28 -07:00
James Bardin 07042a95fa fixing context apply tests 2018-10-16 18:48:28 -07:00
James Bardin 3bd2293152 compare module by normalized path
The onld logic for locating comparing module paths no longer worked, and
we can simplify the comparison by using the addrs.ModuleInstance string.
2018-10-16 18:48:28 -07:00
Martin Atkins ea727d9918 core: Add mock schemas to the refresh context tests
There are still some other issues with some of these tests right now, but
all the ones that need to have schema should now have it.

It seems that there is a bug with the evaluation of child module input
variables where they can't find their schema even when a mock is provided.
Will attack this in a subsequent commit.
2018-10-16 18:48:28 -07:00
Martin Atkins 8b6ef7c8d3 core: EvalWriteOutput handle dynamic pseudo-type
This should actually have been caught by !val.IsWhollyKnown, since
DynamicVal is always unknown, but something isn't working quite right here
and so for now we'll redundantly check also if it's of the dynamic
pseudo-type, and then revisit cty later to see if there's a real bug
hiding down there.
2018-10-16 18:48:28 -07:00
Martin Atkins 5281afcc07 core: Actually read provider schema for data resources
We were passing the pointer into EvalReadDataDiff here, but because it was
not also passed to EvalGetProvider it was just always nil.
2018-10-16 18:48:28 -07:00
Martin Atkins 01a19e18ea core: Add ProviderAddr to all import context tests
The recent changes for v0.12 have moved the responsibilities around here
so that it's the caller's responsibility to specify the provider address
in all cases, with the real UI (in the "command" package) providing a
suitable default if nothing is specified.

Therefore the tests at _this_ level must all include an explicit provider
address, since these tests are acting as if they _are_ the UI code.
2018-10-16 18:48:28 -07:00
Martin Atkins 2c1ef35965 core: skip resource validation when count is unknown
The approach here is a little hacky, since this edge case applies only to
validate and all of the other evaluateResourceCountExpression callers
don't care about it: we overload the "count" return value as a flag to
allow NodeValidatableResource to allow it to detect this situation and
silently ignore errors in this case.
2018-10-16 18:48:28 -07:00
Martin Atkins b54342460c core: Check that resource exists in config before evaluating it
We were previously doing this for all of the reference types except this
one. Now we do it for resources and resource instances too, which both
allows us to produce a proper error message when one is missing (rather
than returning an unknown value) and allows us to properly handle the
case where there are no instances yet present in the state (e.g. because
we're in the validate walk) but "count" isn't set, and so a single
unknown value is expected rather than an empty tuple.
2018-10-16 18:48:28 -07:00
Martin Atkins 0c4c7c5a5f core: Context.InitProvider must cache providers using absolute addresses
Previously InitProvider was incorrectly using only the relative address,
which (due to the ambiguity in the string representation of absolute vs.
relative addresses) caused it to always initialize providers in the root
module.

Now we use the absolute address as the key, which then agrees with the
Provider method and ensures that each module gets its own separate
instance of each provider if explicit configuration is present.
2018-10-16 18:48:28 -07:00
Martin Atkins b8c3b8d45d core: Tolerate missing provider config schema in EvalValidateProvider
This should never happen in real code, but it comes up a lot in test code
where incomplete mock schemas are being used to test with very simple
configurations.
2018-10-16 18:48:28 -07:00
Martin Atkins e4e3876332 core: EvalValidateProvider must always call provider.Validate
Previously we were skipping all of the validation steps if a provider was
being configured implicitly, and thus had no block in configuration.

This is incorrect, since a provider must still get an opportunity to
configure itself with an empty configuration and possibly reject that
empty configuration with errors.
2018-10-16 18:48:28 -07:00
Martin Atkins b031e18332 core: Pass ProviderSchema to EvalValidateSelfRef
EvalValidateSelfRef needs schema in order to extract references. It was
previously expecting a *configschema.Block directly, but we weren't
actually passing that in from anywhere except the tests because it's not
available directly in that form during the evaltree for
node_resource_validate.

Instead, we now pass in the whole *ProviderSchema for the associated
provider and have this EvalNode find the schema itself based on the
address. This breaks some of the generality of this node (now only really
works for resource addresses) but that's okay since we have no other
use-case right now anyway.
2018-10-16 18:48:28 -07:00
Martin Atkins 54464e3f93 core: EvalWriteOutput must convert values to string
Our old state format requires all primitive values to be strings. We were
trying to enforce that before, but this didn't work properly because
gocty does not perform automatic type conversions.

Instead, we now convert to string first and then convert the result into
a native Go string afterwards.
2018-10-16 18:48:28 -07:00
Martin Atkins 6a859f1fe3 core: don't use functions in the input-interpolate-var fixture
Using functions here causes this to test more than it needs to, and
requires additional setup in the corresponding tests.
2018-10-16 18:48:28 -07:00
Martin Atkins 0b4ac6d9e3 core: Allow unknown values as variable outputs in EvalWriteOutput
At the moment this must be handled as a special case because we're still
using the old representation of output state, but we do still need to
handle this so that unknown values can properly pass between modules
during validate and plan.
2018-10-16 18:48:28 -07:00
Martin Atkins d5fda47751 core: Add schema to all of the "Context2Validate" tests
Some of them are still failing for other reasons, but they at least all
now have schema representing their configurations.
2018-10-16 18:48:28 -07:00
Martin Atkins 509c6557dd core: Don't crash EvalValidateProvisioner if no connection block present 2018-10-16 18:48:28 -07:00
Martin Atkins 5b1b564663 core: fix formatting of unexpected diagnostics in context tests 2018-10-16 18:48:28 -07:00
Martin Atkins 7efa010f24 core: Add schema to TestTestContext2Validate_interpolateMap 2018-10-16 18:48:28 -07:00
Martin Atkins fc7453c073 core: Update tests that use the apply-vars fixture
These now need to include a suitable schema in order to properly process
the configuration.
2018-10-16 18:48:28 -07:00
Martin Atkins a9a9cdaa15 core: Fix ProcessIgnoreChanges tests
Since our ignoring is now implemented in terms of cty objects and HCL
traversals, rather than flatmap keys, it no longer makes sense to test
for the flatmap detail of keeping the map count in a separate key.

It _does_ make sense to ignore an entire block or map, but that's already
covered by another existing tests for just []string{"resource"} above.
2018-10-16 18:48:28 -07:00
Martin Atkins 39a83b2fd1 core: fix test for buildProviderConfig
This was incorrectly comparing a cty.Value to an hcl.Body. Now we decode
the body first so we can compare two of cty.Value.

Also includes a fix to a stale comment in buildProviderConfig that was no
longer accurate.
2018-10-16 18:48:28 -07:00
Martin Atkins 0a59da418a core: Fix tests for EvalConfigProvider
The interface of this eval node has changed for v0.12, now requiring both
a provider address and the actual provider object.

We also need to give it a working ctx.EvalBlock implementation on the
mock EvalContext, so we just use installSimpleEval here to get our simple
implementation that just knows how to evaluate constant expressions.
2018-10-16 18:48:28 -07:00
Martin Atkins 9833d9991d core: Fix EvalWriteState tests
EvalWriteState now requires a provider address so that it can record the
last-used provider configuration in the state.
2018-10-16 18:48:28 -07:00
Martin Atkins dc7455887e core: fix tests for debug.go
The plan debug test now needs to provide a schema for the resource types
it uses.
2018-10-16 18:48:28 -07:00
Martin Atkins 0da8fe2087 core: Fix EvalValidateSelfRef tests
We must provide a schema for the synthetic body we use for testing so that
the references can be found within it.
2018-10-16 18:48:28 -07:00
Martin Atkins 4a002bf10b core: EvalValidateSelfRef must catch instances referencing their resources
An instance like aws_instance.foo[0] is not permitted to refer to
aws_instance.foo, since that result contains the individual instance along
with all other instances.
2018-10-16 18:48:28 -07:00
Martin Atkins fc5a3c5cec core: Fix tests for types in eval_validate.go
A schema is now required for any validation, so these tests now use the
simpleMockProvider function to produce a provider with a simple schema
already configured, and test against that schema.
2018-10-16 18:48:28 -07:00
Martin Atkins e6049d79b7 core: EvalContextMock code-based mocking of evaluation
EvaluateBlock and EvaluateExpr are often called multiple times in a single
operation, and our usual approach of mocking with static values is a poor
fit for those cases.

To accommodate more complex tests, we allow the test to optionally provide
a callback function to use instead of the static return values.

Since a pretty common need is to just evaluate the given block or
expression in a simple way, we also now have a helper method
installSimpleEval that installs reasonable implementations of these
two methods that can (assuming no other customization) just evaluate
constant expressions, which is sufficient for many tests.
2018-10-16 18:48:28 -07:00
Martin Atkins 8d0bec5728 core: Don't include "type" in connection block schema
The config loader already extracts this during its initial pass and saves
it as a separate field in a configs.Connection value, so requiring it
again here causes confusing errors about this attribute being provided but
not set.
2018-10-16 18:48:28 -07:00
Martin Atkins f148b26287 core: Fix RefreshGraphBuilder tests
A correct outcome from this test now requires resource type schema to be
available to the graph builder.
2018-10-16 18:48:28 -07:00
Martin Atkins 5e8938de98 core: Remove GraphWalkerPanicwrap, etc
These are some remnants of the shadow graph functionality that was added
to support the graph builder changes in v0.8, but that has since been
removed and so there are no remaining callers for these types and
functions.
2018-10-16 18:48:28 -07:00
Martin Atkins e1e4762b03 core: Update TestNodeApplyableModuleVariablePath for new address type 2018-10-16 18:48:28 -07:00
Martin Atkins feff252700 core: fix tests for checkInputVariables
The contract for this function has changed as part of the 0.12
reorganization so that, while before it would accept a partial variables
map if all missing variables were optional, it now expects that the caller
has already collected values for all variables and is just checking them
for type-correctness here.
2018-10-16 18:48:28 -07:00
Martin Atkins ce41553d56 core: Fix test for NodeDestroyResource.DynamicExpand
Provider addresses are now required for ResourceState, and the string
formatting is now different in the naming of destroy-deposed graph nodes.
2018-10-16 18:48:28 -07:00
Martin Atkins 26e820d829 addrs: Don't return zero-length slice in Reference.Remaining.
Although this rarely matters, making it always be nil when empty makes
deep assertions simpler in tests.

This also includes a minor update to the test in the core package that
first encountered this problem, to improve the quality of its output
on failure.
2018-10-16 18:48:28 -07:00
Martin Atkins e1bc27ef6c core: ApplyGraphBuilder tests to use the "test" mock provider
These tests now need schema available to run properly, so rather than
crafting a separate schema for each of these we'll just use the one
created by simpleMockProvider, which contains a resource type called
test_object that we'll now use as the basis for all of the tests here.
2018-10-16 18:48:28 -07:00
Martin Atkins f475b3b931 core: Fix DiffTransformer node addresses
In this codepath we're still using the old "internal" ResourceAddress
parser to parse resource addresses from the diff, but the string being
parsed does not include a module path and so the result is interpreted
as a resource in the root module.

We need to rewrite this to be in the correct module path as part of
converting to the new address representation, in order to get a correct
absolute address.
2018-10-16 18:48:28 -07:00
Martin Atkins 4472cffb35 core: NodeApplyableResourceInstance.References returns its result
A trivial mistake in the rework of this function meant that it was just
discarding its result rather than returning it. It will now return its
result as expected, allowing reference analysis to work for this node
type.
2018-10-16 18:48:28 -07:00
Martin Atkins 5863c581ee core: Fix misleading log message in ProviderTransformer
The final "<resource> provided by <provider>" message was showing the
original selection made by the resource itself rather than the provider
address finally resolved after inheritance, which caused the log to
misrepresent what was actually being created in the graph.
2018-10-16 18:48:28 -07:00
Martin Atkins f7b8e3b8be core: Fix tests for TestPlanGraphBuilder
Previously this was just stubbing out provider types, but we now need to
include schema for each of the providers and resource types the tests
use in order for the references to be properly detected.

The test fixtures are adjusted slightly here so we can use the
simpleTestSchema as the schema for all of the different blocks in these
tests. The relationships between the resources are still preserved, but
the attributes are renamed to comply with this schema.
2018-10-16 18:48:28 -07:00
Martin Atkins 168354c2e8 core: Tests for scale in and out need to mock EvalExpression
Since expression evaluation is now done via an EvalContext method, and
since these tests use the MockEvalContext, we need to provide a value for
the mock call to return. Previously expression evaluation happened at a
different layer that was not mocked here.
2018-10-16 18:48:28 -07:00
Martin Atkins bec0f56808 core: Pass components through to the destroy transformers
These transformers both construct temporary graphs using many of the same
transformers used in the apply graph, and properly doing this now requires
access to the providers and provisioners in order to obtain their schemas.

Along with this, we also update the tests here to use the
simpleMockComponentFactory helper to get a mock provider with a schema
already configured, which means we also need to update the test fixtures
and assertions to use the resource type and attributes defined in that
mock factory.
2018-10-16 18:48:28 -07:00
Martin Atkins 1a9ee72ecb core: Additional trace logging in attach resource config transformer 2018-10-16 18:48:28 -07:00
Martin Atkins 71d7a9e480 core: AttachSchemaTransformer fail gracefully with no schema
Having a missing schema is a programming error, but at the time of this
commit we're in the midst of introducing schema all over Terraform and so
there are inevitably some places -- particularly in older unit tests --
where schema isn't yet being provided.

This error allows us to catch those cases and fail gracefully, rather
than panicking further down here when we access t.Components methods.

Also includes some additional logging to aid debugging of this
transformer.
2018-10-16 18:48:28 -07:00
Martin Atkins b73e4ede5d core: use correct fallback provider address for abstract resource instance
Previously we were attempting to construct a default manually here, and
actually getting it wrong by using the resource type name as a whole
rather than the expected inferrence by prefix.

Now we use the method provided in the addrs package for this purpose,
which implements the standard behavior of shaving off the first
underscore-separated word from the resource type name.
2018-10-16 18:48:28 -07:00
Martin Atkins f82c192c49 core: mock provider factory functions for testing
Now that any configuration processing requires schema, we need either a
standalone schema or a provider/provisioner configured with one a lot more
often in tests.

To avoid adding loads of extra boilerplate to the tests, these new helper
functions produce objects pre-configured with a schema that should be
useful for a number of different cases, and can be customized further for
more interesting situations.

A lot of our tests can then just use these pre-defined object and
attribute names in their fixtures in situations where the canned schemas
here are good enough.
2018-10-16 18:48:28 -07:00
Martin Atkins 8fabcc0c08 core: Correct test TestOrphanResourceCountTransformer_zeroAndNone
The logic under test has intentionally changed here so that setting count
to any value -- even 1 -- causes Terraform to prefer to keep indexed
instances if both non-indexed and indexed are present.

Previously Terraform treated count = 1 as equivalent to count not set at
all, but we now recognize these as two different situations and treat
count = 1 as the same as any other non-zero count, to ensure that if
count is set conditionally it'll always produce indexed instances, even
if the dynamic expression ends up evaluating to 1.
2018-10-16 18:48:28 -07:00
Martin Atkins ad6bb4a1d5 core: NodeProvisioner.Name update for new address types
This function was previously checking for a path length greater than one
because the older path format included an always present "root" element
at the start.

We now need to check for a totally-empty list, because otherwise we fail
to add the expected prefix to the front of a path with only one element.

This also includes some adjustments to the related tests and transforms
that do not change behavior but do make the test results easier to
understand and debug.
2018-10-16 18:48:28 -07:00
Martin Atkins e40e3b9ad8 core: fix inheritence checks in ConfigTreeDependencies
Due to some disagreement about what representation of provider addresses
we were using, the inherited providers map wasn't matching. Now we'll
consistenly use the "compact" form (just the provider name and optional
alias).

Also includes some other tweaks to make this test better-behaved.
2018-10-16 18:48:28 -07:00
Martin Atkins 880d971328 core: TestStateAddModule old-style output
Although the AddModule method now takes a new-style
module address as an argument, internally we're still
shimming it to a []string.

Therefore this test needs to still expect [][]string as
a result, rather tan []addrs.ModuleInstance.
2018-10-16 18:48:28 -07:00
Martin Atkins 3ed396ad5c core: Update ProviderTransformer tests for new ImportTarget interface
Prior to the refactoring to move provider address parsing/selection up
into the frontend, there was some logic here to just-in-time default a
provider config based on the given resource type.

This is now expected to happen at a higher layer, with ImportTarget
expecting an already-valid provider configuration address.

The normal import codepath was already updated with this in mind, but some
of the provider transform tests are using ImportStateTransformer as a
shortcut for getting some resource nodes added to the graph, and so those
tests now need to include a valid provider address in their ImportTarget
values.

Also includes some adjustments to test output to make the tests easier
to debug.
2018-10-16 18:48:28 -07:00
Martin Atkins b0b1486c46 core: Clarify the MissingProviderTransformer logic
The prior implementation of this function (before the rewrite to use
addrs.AbsProviderConfig values) was relying on some implicit behavior of
our provider address normalization to generate an address in the root
module. Since that wasn't explicit, I introduced a bug here when
introducing the new address type, where I generated an address in the
node's own module, rather than in the root as expected.

This new implementation is functionally equivalent to the prior, but is
written to make the intent more obvious: take _just_ the type from the
node's provider address and create an implicit configuration for it
_in the root module_.

Along with the change in approach, this new implementation also has an
updated documentation comment that better describes its current intent
(previously it was outdated) and hopefully clearer trace logging to
better communicate what it's doing.
2018-10-16 18:48:28 -07:00
Martin Atkins e4e972db67 core: Fix MissingProviderTransformer matching existing providers
In the change to using addrs types rather than string keys directly here
I incorrectly made this use the _relative_ provider config instead of
the absolute one, causing MissingProviderTransformer to only match
providers defined in the root module (due to ambiguity in the string
representations of these address types).

The rest of this change is improved logging and test output that helped
with debugging this issue.
2018-10-16 18:48:28 -07:00
Martin Atkins 604c347128 core: Update test fixtures for ProviderTransformer tests
Some of these tests were using an outdated form to reference a local
directory as a module. While here, I also updated the provider references
to the new unquoted form, which is preferred from v0.12 onwards.
2018-10-16 18:48:28 -07:00
Martin Atkins 37dfda93ce core: Fix ReferenceTransformer tests
The changes to our GraphNodeReferencable and GraphNodeReferencer
interfaces were not also reflected in our testing structs here, and so
these tests were no longer working.

This updates these implementations to the new required signatures,
adapting the simplified model used in the structs to generate local
variable references, since the reference model no longer uses the
arbitrary strings that this test originally depended on.

We also remove some of the tests here since the functionality they were
testing no longer applies: inter-module dependencies are now handled by
the graph nodes producing extra ReferencableAddrs, and the "backup" form
is no longer used because our new address model is able to distinguish
resources from resource instances without the need for the magical
backup reference forms we previously used.
2018-10-16 18:48:28 -07:00
Martin Atkins a6ca01f49d core: Fix TargetsTransformer tests
Resolution of dependencies automatically from expressions now requires
a schema to be available. To avoid the need to provide mock schemas for
all of these different resource types, we instead use the depends_on
argument here to mark the dependencies explicitly.
2018-10-16 18:48:28 -07:00
Martin Atkins 17d8ec6b6f core: NodeAbstractResource correct default result from ProvidedBy
Previously we had a bug where we'd use the resource type name instead of
the provider name. Now we use the DefaultProviderConfig helper function
to extract the provider name from the resource type name.
2018-10-16 18:48:28 -07:00
Martin Atkins c8f186b303 core: TestTransitiveReductionTransformer needs a schema
The ReferenceTransformer can't do its work here unless our resources have
schema attached, since otherwise it doesn't know which attributes to
search to find references.
2018-10-16 18:48:28 -07:00
Martin Atkins 7188cabdaf core: Testing helpers for building provider schemas
Now that a schema is required to decode resource configuration, a lot more
tests than before need access to mock providers in order to get a schema.
These new helpers allow a mock provider with a schema to be constructed
concisely.
2018-10-16 18:48:28 -07:00
Martin Atkins c58bdc6390 core: fix the tests in variables_test.go
This test required some adaptation for the new variable handling model in
the HCL2-oriented codepaths, where more of the handling is now done in the
"command" package.

The initial reorganization of this test was not correct, so this is a
further revision to adapt the original assertions to the new model as much
as possible, removing a few tests that no longer make sense in the new
world.
2018-10-16 18:48:28 -07:00
Martin Atkins b33a970b62 core: fix test fixtures for HCL2 syntax idiom
A number of our test fixtures were previously using the non-idiomatic form
of including a single child attribute all on one line with the block
header and bounding braces.

This non-idiomatic form is an error in HCL2, and hclfmt has always "fixed"
it to the expected form of each attribute being on a line of its own, and
so here we just update all the affected test fixtures to canonical form
(using hclfmt), allowing them to be parsed as intended.

Since the these entire files were processed with hclfmt, there are some
other unrelated style changes included in situations where the file
layouts were non-idiomatic in other ways.
2018-10-16 18:46:46 -07:00
Martin Atkins c82e3ec92f core: even more nil checks to catch missing objects
These are all things that ought to be present in normal use but can end up
being nil in incorrect tests. Test debugging is simpler if these things
return errors gracefully, rather than crashing.
2018-10-16 18:46:46 -07:00
Martin Atkins 26c1584317 core: EvalConfigProvider shouldn't crash if its provider isn't set
While there's no good reason for this to happen in practice, it can arise
in tests if mocks aren't set up quite right, and so we'll catch it and
report it nicely to make test debugging a little easier.
2018-10-16 18:46:46 -07:00
Martin Atkins 7dacb6b6a8 core: Don't crash if EvaluateBlock returns nil during validation
There's actually no good reason for this to happen in the normal case, but
it can happen reasonably easy if a test doesn't properly configure the
MockEvalContext, and so having this check here makes test debugging a
little easier.
2018-10-16 18:46:46 -07:00
Martin Atkins 69d2fa0c15 terraform: fix crasher in TestProcessIgnoreChanges
Since this test case is using t.Run, it must be sure to pass the nested
*testing.T over to the testDiffs function or else calls to t.Fatal will
crash the whole test process, since they would otherwise be called on the
wrong instance of *testing.T.
2018-10-16 18:46:46 -07:00
Martin Atkins 0dd7677d1f core: fail gracefully if provider schemas aren't available
The only reason these cases are arising right now is because we have tests
that haven't yet been updated to properly support schema, but it can't
hurt to add some robustness here to reduce the risk of real crashes.
2018-10-16 18:46:46 -07:00
Martin Atkins 4a21b763aa core: Get tests compiling again
After the refactoring to integrate HCL2 many of the tests were no longer
using correct types, attribute names, etc.

This is a bulk update of all of the tests to make them compile again, with
minimal changes otherwise. Although the tests now compile, many of them
do not yet pass. The tests will be gradually repaired in subsequent
commits, as we continue to complete the refactoring and retrofit work.
2018-10-16 18:46:46 -07:00
Martin Atkins 20f6de735d core: Update MockResourceProvisioner to include GetConfigSchema
This method is now required for the ResourceProvisioner interface.
2018-10-16 18:46:46 -07:00
Martin Atkins 73053eb5ef core: Context.Eval method
Some of the objects that are referencable from expressions are transient
values computed only during a graph walk, and not persisted in state. In
order to support arbitrary evaluation of expressions, such as in the
"terraform console" CLI command, it's necessary to be able to evaluate
these values before we start evaluating.

This new Eval method achieves this by performing a special graph walk that
ignores resources (except for dependency resolution) and just focuses on
evaluating all of these transient values, before returning an evaluation
scope that can then resolve expressions in terms of that result.

This replaces the Context.Interpolator method, which was fraught with
various issues due to it not properly priming the state before evaluating.
2018-10-16 18:46:46 -07:00
Martin Atkins 630e3b4be2 core: evaluation for HCL2-flavored reference expressions
Here we replace the stub implementations in evaluationStateData with real
implementations that are based on their equivalents in the old
Interpolator type.

The behavior here is a little different due to the different semantics
expected under HCL2, but the principle remains the same: the main
references are resolved from the state, using config for validation
in order to produce some helpful error messages.
2018-10-16 18:46:46 -07:00
Martin Atkins 25e3ac56d2 core: Wire back in module input variables to the evaluator
I took some missteps here while doing the initial refactor for HCL2 types.
This restores the map of maps that retains all of the variable values, and
then makes it available to the evaluator.
2018-10-16 18:46:46 -07:00
Martin Atkins 4b5868f653 core: BuiltinEvalContext constructs evaluationStateData itself
Previously our evaluationStateData object was constructed inside
Evaluator.Scope, but this was awkward because all of the fields inside it
need to be populated from BuiltinEvalContext fields, and so the signature
of Evaluator.Scope kept growing new arguments over time.

Instead, we reassign the responsibilities here so that Evaluator.Scope
takes an already-constructed lang.Data, and then teach BuiltinEvalContext
to build this object itself from its own internal values.
2018-10-16 18:46:46 -07:00
Martin Atkins b0435cd533 core: ProviderConfigTransformer properly locates parent module
Due to a logic error here we were trying to find our our module's parent
as a descendent of itself, rather than as a descendent of the root. It
turns out that we can do this even more simply by just accessing the
Parent field on the given config, avoiding the need to traverse the tree
down from the root at all.

While here, this also switches to using the path.Call helper method rather
than manually slicing the path array, since this better communicates our
intent.
2018-10-16 18:46:46 -07:00
Martin Atkins d4cfe85361 core: pass InstanceKey to EvaluateBlock
This gives us the value we need to evaluate a "count.index" reference, and
later also the equivalent for the "for_each" argument once implemented.
2018-10-16 18:46:46 -07:00
Martin Atkins d4285dd27f core: Attach resource and provider config schemas during graph build
This is a little awkward since we need to instantiate the providers much
earlier than before. To avoid a lot of reshuffling here we just spin each
one up and then immediately shut it down again, letting our existing init
functionality during the graph walk still do the main initialization.
2018-10-16 18:46:46 -07:00
Martin Atkins ca67899827 core: NewLegacyResourceInstanceAddress correct handling of addrs.NoKey
Previously we were setting zero here, but the correct way to represent
"no index" in a *ResourceAddress is to set the index to -1.
2018-10-16 18:46:46 -07:00
Martin Atkins a28c93c3ce core: render variables, locals and outputs nicely in "terraform graph" 2018-10-16 18:46:46 -07:00
Martin Atkins 226d66bac8 core: include "root" element when constructing legacy ModuleState path
We've not yet adjusted any of the state structs to reflect our new address
types because they are used with encoding/json to produce our state file
format, but the shimming here previously was incorrect because it failed
to include the special "root" string that's always required at element
zero of a module path in the state.
2018-10-16 18:46:46 -07:00
Martin Atkins c937c06a03 terraform: ugly huge change to weave in new HCL2-oriented types
Due to how deeply the configuration types go into Terraform Core, there
isn't a great way to switch out to HCL2 gradually. As a consequence, this
huge commit gets us from the old state to a _compilable_ new state, but
does not yet attempt to fix any tests and has a number of known missing
parts and bugs. We will continue to iterate on this in forthcoming
commits, heading back towards passing tests and making Terraform
fully-functional again.

The three main goals here are:
- Use the configuration models from the "configs" package instead of the
  older models in the "config" package, which is now deprecated and
  preserved only to help us write our migration tool.
- Do expression inspection and evaluation using the functionality of the
  new "lang" package, instead of the Interpolator type and related
  functionality in the main "terraform" package.
- Represent addresses of various objects using types in the addrs package,
  rather than hand-constructed strings. This is not critical to support
  the above, but was a big help during the implementation of these other
  points since it made it much more explicit what kind of address is
  expected in each context.

Since our new packages are built to accommodate some future planned
features that are not yet implemented (e.g. the "for_each" argument on
resources, "count"/"for_each" on modules), and since there's still a fair
amount of functionality still using old-style APIs, there is a moderate
amount of shimming here to connect new assumptions with old, hopefully in
a way that makes it easier to find and eliminate these shims later.

I apologize in advance to the person who inevitably just found this huge
commit while spelunking through the commit history.
2018-10-16 18:46:46 -07:00
Martin Atkins a09498a8a3 core: load a provider's schema at initialization
This is currently not very ergonomic due to the API exposed by providers.
We'll smooth this out in a later change to improve the provider API, since
we know we always want the entire schema.
2018-10-16 18:44:26 -07:00
Martin Atkins c07b0a7806 configs: Re-unify the ManagedResource and DataResource types
Initially the intent here was to tease these apart a little more since
they don't really share much behavior in common in core, but in practice
it'll take a lot of refactoring to tease apart these assumptions in core
right now and so we'll keep these things unified at the configuration
layer in the interests of minimizing disruption at the core layer.

The two types are still kept in separate maps to help reinforce the fact
that they are separate concepts with some behaviors in common, rather than
the same concept.
2018-10-16 18:44:26 -07:00
Martin Atkins 4ed06a9227 terraform: HCL2-flavored module dependency resolver
For the moment this is just a lightly-adapted copy of
ModuleTreeDependencies named ConfigTreeDependencies, with the goal that
the two can live concurrently for the moment while not all callers are yet
updated and then we can drop ModuleTreeDependencies and its helper
functions altogether in a later commit.

This can then be used to make "terraform init" and "terraform providers"
work properly with the HCL2-powered configuration loader.
2018-10-16 18:44:26 -07:00
Martin Atkins ebafa51723 command: Various updates for the new backend package API
This is a rather-messy, complex change to get the "command" package
building again against the new backend API that was updated for
the new configuration loader.

A lot of this is mechanical rewriting to the new API, but
meta_config.go and meta_backend.go in particular saw some major
changes to interface with the new loader APIs and to deal with
the change in order of steps in the backend API.
2018-10-16 18:44:26 -07:00
Alex Somesan 00822c82c0 Remove a leftover test log file 2018-09-11 17:02:32 +02:00
James Bardin cfefeec926 walkDestroy is a form of "apply"
When computing the count value, make sure to include walkDestroy with
walkApply, as the former is only a special case of the latter.

When applying a saved plan, the computed count values are lost and we
can no longer query the state for those values. The apply walk was
already considered in the `resourceCountMax` function, but the destroy
walk was not.  This worked when destroying in a single operation
("terraform destroy"), since the state would still be updated with the
latest counts from the plan.
2018-04-10 11:46:29 -04:00
James Bardin 2f8532407a
Merge pull request #17071 from MarkFreebairn/Issue-16360-empty-target-points-to-all-resources-in-state
command: Fix #16360 - Fail fast if -target is specified but empty
2018-04-05 14:19:32 -04:00
James Bardin 060a3bc6d2
Merge pull request #17748 from reancloud/winrm-ntlm
Support NTLM for WinRM communicators.
2018-04-05 09:44:11 -04:00
James Bardin f25718b065
Merge pull request #17768 from hashicorp/jbardin/unused-destroy-outputs
unused outputs in a destroy should be pruned
2018-04-04 15:20:12 -04:00
James Bardin 620f1985a1 unused outputs in a destroy should be pruned
During a full destroy when outputs are removed, the
NodeDestroyableOutput was preventing it's sibling output from being
destroyed. Prune the output node if it only has its destroy node as a
dependent.

The destroy output test is simply run a second time with no state, which
would cause the output interpolation to fail if it remained in the
graph.
2018-04-03 13:19:04 -04:00
James Bardin 79b948c9cc detect scaled in resources when evaluating *s
If an existing resources is scaled back to 0, locals and outputs will
still have a multi-variable reference to evaluate, which should return
an empty list. Due to how the resource is removed, the resource will
still exist in the state but with no primary instance, which needs to be
ignored in the instance count.
2018-04-03 10:00:45 -04:00
Joe Khoobyar 852a74c49d first attempt at supporting NTLM authentication in Terraform 2018-03-30 21:11:53 -04:00
James Bardin 38e6309f03
Merge pull request #17642 from hashicorp/jbardin/GH-17462
remove more unneeded partial outputs
2018-03-20 11:11:54 -04:00
James Bardin a5c4f7e08e remove unneeded partial outputs
filterPartialOutputs was not taking into account that some dependent
resources might yet be removed from the graph. Check that they are not
in the targeted set before declaring that the output remain.
2018-03-19 21:20:06 -04:00
James Bardin e5f8adfc1a add failing test for invalid output with targets
Outputs that are missing references aren't always removed from the
graph, due to being filtered before their dependents are removed.
2018-03-19 20:32:37 -04:00
James Bardin 8fb8b2cffc make sure ReadState returns an error
ReadState would hide any errors, assuming that it was an empty state.
This can mask errors on Windows, where the OS enforces read locks on the
state file.
2018-03-19 18:17:25 -04:00
James Bardin 88e911af45 fix a provisionerFail test which was incorrect
The provisionerFail_createBeforeDestroy test was verifying the incorrect
output. The create_before_destroy instance in the state has an ID of
"bar" with require_new="abc", and a new instance would get an ID of
"foo" with require_new="xyz". The existing test was expecting the
following state:

aws_instance.bar: (1 deposed)
  ID = bar
  provider = provider.aws
  require_new = abc
  Deposed ID 1 = foo (tainted)

Which showed "bar" still the primary instance in the state, with the new
instance "foo" as being the deposed instance, though properly tainted.

The new output is:

aws_instance.bar: (tainted) (1 deposed)
  ID = foo
  provider = provider.aws
  require_new = xyz
  type = aws_instance
  Deposed ID 1 = bar

Showing the new "foo instance as being the primary instance in the
state, with "bar" as the deposed instance.
2018-03-15 16:04:05 -04:00
James Bardin b2d111c2bd return provisioner Apply errors
EvaApplyProvisioners was not returning errors if there was already a
multierror stored in the Error field. Always return the error to the
caller.
2018-03-15 16:04:05 -04:00
James Bardin a2718e4f79 ignore errors interpolating RawCount during apply
If a count field references another count field which is interpolated
but is attached to a resource already in the state, the result of that
first interpolation will be lost when a plan is serialized. This is
because the result of the first interpolation is stored directly in the
module config, in an unexported config field.

This is not a general fix for the above situation, which would require
refactoring how counts are handles throughout the config. Ignoring the
error works, because in most cases the count will be properly
handled during the resource's interpolation.
2018-03-09 19:16:04 -05:00
James Bardin f3d1fb3aff failing test for interpolated count from plan
An interpolated count value that is determined during plan, is lost
during plan serialization, causing apply to fail when the interpolation
string can't be evaluated.
2018-03-09 19:04:39 -05:00
James Bardin 7fd6f97899 Check for nil config in node_resource_refresh
While not normally possible, manual manipulation of the state and config
can cause us to end up with a nil config in
evalTreeManagedResourceNoState.

Regardless of how it got here, we can't ever assume the Config field is
not nil, and EvalInterpolate happily accepts a nil RawConfig
2018-03-06 17:53:09 -05:00
Paul Tyng c868092d2d
Standardize http.Client creation with User-Agent 2018-02-28 12:09:50 -05:00
James Bardin a37acb1837 gofmt with go1.10 2018-02-21 10:22:08 -05:00
James Bardin 1a68fdb4f6 add support for ssh host key checking
Add `host_key` and `bastion_host_key` fields to the ssh communicator
config for strict host key checking.

Both fields expect the contents of an openssh formated public key. This
key can either be the remote host's public key, or the public key of the
CA which signed the remote host certificate.

Support for signed certificates is limited, because the provisioner
usually connects to a remote host by ip address rather than hostname, so
the certificate would need to be signed appropriately. Connecting via
a hostname needs to currently be done through a secondary provisioner,
like one attached to a null_resource.
2018-02-14 15:35:41 -05:00
Ryan Uber 71ac5034e9 terraform: use hashicorp/go-uuid for lineage generation 2018-02-09 15:02:32 -08:00
James Bardin 7fbc35a36c Make sure outputs are removed when targeting
Similar to NodeApplyableOuptut, NodeDestroyableOutputs also need to stay
in the graph if any ancestor nodes

Use the same GraphNodeTargetDownstream method to keep them from being
pruned, since they are dependent on the output node and all its
descendants.
2018-01-31 13:51:40 -05:00
James Bardin ca4178b9ec gofmt bug will be fixed in 1.10 2018-01-30 15:46:24 -05:00
James Bardin a2f8482333 catch missing id attribute during interpolation
The id attribute can be missing during the destroy operation.
While the new destroy-time ordering of outputs and locals should prevent
resources from having their id attributes set to an empty string,
there's no reason to error out if we have the canonical ID field
available.

This still interrogates the attributes map first to retain any previous
behavior, but in the future we should settle on a single ID location.
2018-01-30 15:46:12 -05:00
James Bardin 99867f0082 add PruneUnusedValuesTransformer
Since outputs and local nodes are always evaluated, if the reference a
resource form the configuration that isn't in the state, the
interpolation could fail.

Prune any local or output values that have no references in the graph.
2018-01-30 10:47:17 -05:00
James Bardin 2d138d9917 add a more complex locals test
Using destroy provisioners again for edge cases during destroy.
2018-01-30 10:47:17 -05:00
James Bardin d31fe5ab9d delete outputs during destroy
Now that outputs are always evaluated, we still need a way to remove
them from state when they are destroyed.

Previously, outputs were removed during destroy from the same
"Applyable" node type that evaluates them. Now that we need to possibly
both evaluate and remove output during an apply, we add a new node -
NodeDestroyableOutput.

This new node is added to the graph by the DestroyOutputTransformer,
which make the new destroy node depend on all descendants of the output
node.  This ensures that the output remains in the state as long as
everything which may interpolate the output still exists.
2018-01-29 19:30:04 -05:00
James Bardin 08139557f8 always evaluate outputs too
Always evaluate outputs during destroy, just like we did for locals.
This breaks existing tests, which we will handle separately.

Don't reverse output/local node evaluation order during destroy, as they
are both being evaluated.
2018-01-29 18:10:34 -05:00
James Bardin 7ac0a46981 add destroy provisioner test with locals, outputs
Add a complex destroy provisioner testcase using locals, outputs and
variables.

Add that pesky "id" attribute to the instance states for interpolation.
2018-01-29 18:01:58 -05:00
James Bardin 7da1a39480 always evaluate locals, even during destroy
Destroy-time provisioners require us to re-evaluate during destroy.

Rather than destroying local values, which doesn't do much since they
aren't persisted to state, we always evaluate them regardless of the
type of apply. Since the destroy-time local node is no longer a
"destroy" operation, the order of evaluation need to be reversed. Take
the existing DestroyValueReferenceTransformer and change it to reverse
the outgoing edges, rather than in incoming edges. This makes it so that
any dependencies of a local or output node are destroyed after
evaluation.

Having locals evaluated during destroy failed one other test, but that
was the odd case where we need `id` to exist as an attribute as well as
a field.
2018-01-29 16:16:41 -05:00
James Bardin d29994e247
Merge pull request #17127 from hashicorp/jbardin/ignore_changes
don't ignore partial containers in diffs
2018-01-19 16:08:18 -05:00
Martin Atkins b511caf049 core: interpolate the count config during the apply walk
Previously we would interpolate the count config (ResourceConfig.RawCount)
only while preparing to dynamic-expand aggregate resource nodes. This is
problematic because we do not dynamic-expand any resource nodes during the
apply walk, and so previously the count value was not available for
interpolation during apply and would result in an error.

Now we interpolate RawCount once for each resource we visit during the
apply walk -- even though that redundantly interpolates the same config
multiple times when count > 1 -- to ensure that it's available by the
time we interpolate any remaining expressions in the config and any
expressions within "connection" and "provisioner" blocks.

This error was masked by us sharing a single RawConfig instance between
the plan and apply walks when "terraform apply" is run with no explicit
plan file argument, but was exposed by the workflow where the plan is
written first to disk since in that case the interpolation result from
during the plan phase is not present in the deflated plan object. For
this reason, the new context test serializes the plan into an in-memory
buffer and reloads it in order to simulate the effect of the two-step
workflow.
2018-01-19 13:06:00 -08:00
James Bardin 8d1e479fc7 don't ignore partial containers in diffs
Containers (maps, lists, sets) in an InstanceDiff need to be handled in
their entirety.  Unchanged values cannot be filtered out from diffs, as
providers expect attribute containers to be complete.

If a value in ignore_changes maps to a single key in an attribute
container, and there are other changes present, that ignored value must
be included in the diff as well.
2018-01-17 19:13:32 -05:00
James Bardin c19fb49bda reset old ignore_changes test back to correct diff
The output for the flatmap ignore_changes test was incorrectly modified.
Providers expect diffs of complex attributes to contain all or nothing.
2018-01-17 15:31:21 -05:00
Masayuki Morita f440dba137 Standardize on log level "WARN" rather than "WARNING" 2018-01-16 18:05:26 -08:00
Mark Freebairn 1384cf6861 Issue 16360 - Empty -target= points to all resources in state 2018-01-09 21:00:55 +00:00
James Bardin 7d5f7cb22f
Merge pull request #16961 from hashicorp/jbardin/mock-provider-race
minor race issue in mockResourceProvider
2018-01-08 16:47:58 -05:00
James Bardin bf5944a92c
Merge pull request #16972 from hashicorp/jbardin/ssh-agent-identity
ssh connection `agent_identity`
2018-01-05 16:57:30 -05:00
James Bardin 504ea578ee
Merge pull request #16920 from hashicorp/jbardin/init-future-state
check state version during init
2018-01-05 16:54:41 -05:00
James Bardin 3cde03bab1
Merge pull request #17035 from hashicorp/jbardin/close-providers
Close providers
2018-01-05 16:54:16 -05:00
James Bardin 6210b1749b use the full provider name for CloseProvider
CloseProviderTransformer wasn't using the full provider when creating
the graph node, so the Close wasn't actually being called on the
provider.
2018-01-04 15:03:27 -05:00
James Bardin ba749db9ed add test checking CloseProvider
There was no test checking that Close wsa called on the mock provider.
This fails now since the CloseProviderTransformer isn't using the fully
resolved provider name.
2018-01-04 15:00:09 -05:00
James Bardin 35ce444851 add validation for the new connection field 2017-12-26 16:27:18 -05:00
James Bardin 4b49a323c3 go fmt
slight change to go fmt coming in 0.10
2017-12-26 13:26:38 -05:00
James Bardin cba592d54f minor race issue in mockResourceProvider
The interrupt tests for providers no longer check for the condition
during the diff operation. defer the lock so other test's DiffFns don't
need to be as carefull locking themselves.
2017-12-20 09:18:38 -05:00
James Bardin ea4cb6a20e check state version during init
The init command needs to parse the state to resolve providers, but
changes to the state format can cause that to fail with difficult to
understand errors. Check the terraform version during init and provide
the same error that would be returned by plan or apply.
2017-12-15 11:17:59 -05:00
James Bardin f00dc45e8f
Merge pull request #16780 from nevans-sofi/processIgnoreChangesPatch
Ignore redundant IgnoreChanges attributes
2017-12-13 16:07:35 -05:00
Florian Forster 6680b1f16b core: check for negative indices in ResourceConfig.get
The bounds checking in ResourceConfig.get() was insufficient: it detected when the index was greater than or equal to cv.Len() but not when the index was less than zero. If the user provided an (invalid) configuration that referenced "foo.-1.bar", the provider would panic.

Now it behaves the same way as if the index were too high.
2017-12-12 09:18:38 -08:00
Rob Campbell 5daeee5f6d Update various files for new version of "stringer"
The latest version of stringer now uses strconv instead of fmt.
2017-12-11 13:26:29 -08:00
James Bardin df38c2e3ea make the mock provider stoppable
The mock provider couldn't be stopped during diff, because the single
mutex was held through the oepration. Release the mutex so Stop can be
called.
2017-12-05 10:17:20 -05:00
James Bardin fc2913d610
Merge pull request #16619 from hashicorp/jbardin/implicit-providers
Allow overriding an implicitly used provider
2017-11-28 17:07:59 -05:00
James Bardin 5fa24a0128 output warning flag 2017-11-28 14:18:54 -05:00
Martin Atkins ba0514106a return tfdiags.Diagnostics from validation methods
Validation is the best time to return detailed diagnostics
to the user since we're much more likely to have source
location information, etc than we are in later operations.

This change doesn't actually add any detail to the messages
yet, but it changes the interface so that we can gradually
introduce more detailed diagnostics over time.

While here there are some minor adjustments to some of the
messages to improve their consistency with terminology we
use elsewhere.
2017-11-28 11:15:29 -08:00
Nathan Evans 45439d0ac3 Add inequality check to ignore redundant diff attributes 2017-11-28 10:11:19 -07:00
James Bardin 29264df7c0 normalize missing provider names
The provider name coming from ProvidedBy may be resolved if it only
exists in the state. Make sure to strip the module and provider
prefixes for the provider name when adding missing providers.
2017-11-14 15:53:37 -05:00
James Bardin 105b66e74d error out when a referenced provider is missing 2017-11-13 20:41:38 -05:00
James Bardin b9b418bcb0 test passing in implicitly used provider 2017-11-13 20:41:38 -05:00
James Bardin 8bf270daa9 rewrite the ProviderConfigTransformer
It's become apparent that passing in a provider config for an implicitly
used provider would be very useful. While the ProviderConfigTransformer
efficiently added providers to the graph, the algorithm was reversed
from what would be needed to allow overriding implicit providers.

Change the ProviderConfigTransformer to fist add all configured
provider, even if they are empty stubs. Then run through all providers
being passed in from the parent, and replace the provider nodes we
created with proxies, and add implicit proxies where none existed. The
extra nodes will then be pruned later.
2017-11-13 20:41:38 -05:00
James Bardin b357c02ad1 don't panic 2017-11-10 11:01:32 -05:00
James Bardin ca191a3b2f
Merge pull request #16599 from hashicorp/jbardin/orphaned-module-outputs
Remove modules and module outputs from state
2017-11-09 12:33:35 -05:00
James Bardin e3ea3150ae make NodeOutputOrphan referenceable
The removed output need to be referencable so if its parent module is
also being remove, the removal happens in the correct order.
2017-11-09 10:52:46 -05:00
James Bardin e0ad3300c6 fix References used by the ReferenceTransformer
There was a bug where all references would be discarded in the case when
a self-reference was encountered. Since a module references all
descendants by it's own path, it returns a self-reference by definition.
2017-11-09 10:36:42 -05:00
James Bardin 7e4dcdb9f0 run RemovedModuleTransformer before References
Also add RemovedModuleTransformer to the plan graph for parity.
2017-11-09 10:34:56 -05:00
James Bardin 3916f3a5a3 only add nodes in RemovedModuleTransformer
Let the ReferenceTransformer connect them once it's fixed.
2017-11-09 10:32:01 -05:00
James Bardin 5915d883d2 make NodeModuleRemoved a GraphNodeReferencer
This was the node can be automatically connected by the
ReferenceTransformer.
2017-11-09 10:30:55 -05:00
James Bardin 14cc654b16 preserve order when removing module from state 2017-11-08 22:12:35 -05:00
James Bardin ccc9b1d767 replacing orphaned with removed 2017-11-08 22:10:43 -05:00
Martin Atkins 4cde21501c core: more explanation when a provider block cannot be found
Our new resource-to-provider matching is stricter about explicitly
matching aliases when config is present (no longer automatically
inherited) and with locating providers to destroy removed resources.

With this in mind, this is an attempt to expand slightly on this error
message now that users are more likely to see it.

In future it would be nice to do some explicit validation of this a bit
closer to the UI, so we can have room for more explanatory text, but this
additional messaging is intended to help users understand why they might
be seeing this message after removing a provider configuration block from
configuration, whether directly or as a side-effect of removing a module.
2017-11-08 17:00:35 -08:00
James Bardin 15ea04af8a remove modules from state
Remove the module entry from the state if a module is no longer in the
configuration. Modules are not removed if there are any existing
resources with the module path as a prefix. The only time this should be
the case is if a module was removed in the config, but the apply didn't
target that module.

Create a NodeModuleRemoved and an associated EvalDeleteModule to track
the module in the graph then remove it from the state. The
NodeModuleRemoved dependencies are simply any other node which contains
the module path as a prefix in its path.

This could have probably been done much easier as a step in pruning the
state, but modules are going to have to be promoted to full graph nodes
anyway in order to support count.
2017-11-08 19:11:53 -05:00
James Bardin aa2bd0945b properly find orphaned outputs
You can't find orphans by walking the config, because by definition
orphans aren't in the config.

Leaving the broken test for when empty modules are removed from the
state as well.
2017-11-08 14:28:02 -05:00
James Bardin 9283568dca add OrphanOutputTransformer to the plan graph
make sure orphaned outputs appear in the plan as well
2017-11-08 14:28:02 -05:00
James Bardin 68b07a766a add failing test for orphaned modules outputs
When an entire module is removed from the config, that module's outputs
are not removed from the state.
2017-11-08 14:28:02 -05:00
James Bardin b8b7548614 remove module referencing existing provider 2017-11-07 22:05:52 -05:00
James Bardin 3801ca5bbf test that Refresh updates Provider fields in state 2017-11-07 21:42:30 -05:00
James Bardin d613959cda write provider to state for import nodes
and update the test state strings
2017-11-07 21:05:37 -05:00
James Bardin 3977fe8b2d write provider to state for refresh nodes
and update the test state strings
2017-11-07 21:05:28 -05:00
James Bardin c2f3522f7d write providers to state for data resources
And update the test state strings

Destroying with no config is no longer allowed, run an exlpicit destroy
for the destroyOrder test.
2017-11-07 21:05:21 -05:00
James Bardin 8dfaae1f23 rewrite all of the test state string for providers
Now that the resolved provider is always stored in state, we need to
udpate all the test data to match. There will probably be some more
breakage once the provider field is properly diffed.
2017-11-07 13:49:43 -05:00
James Bardin b79adeae02 save resolved providers for resources to state
Use the ResourceState.Provider field to store the full name of the
provider used during apply. This field is only used when a resource is
removed from the config, and will allow that resource to be removed by
the exact same provider with which it was created.

Modify the locations which might accept the alue of the
ResourceState.Provider field to detect that the name is resolved.
2017-11-07 13:09:36 -05:00
James Bardin 990acca758 remove commented out fields 2017-11-07 10:15:11 -05:00
James Bardin b9b4912bfb complete passing providers through modules
Here we complete the passing of providers between modules via the
module/providers configuration, add another test and update broken test
outputs.

The DisbableProviderTransformer is being removed, since it was really
only for provider configuration inheritance. Since configuration is no
longer inherited, there's no need to keep around unused providers. The
actually shouldn't be any unused providers going into the graph any
longer, but put off verifying that condition for later.  Replace it's
usage with the PruneProviderTransformer, and use that to also remove the
unneeded proxy provider nodes.
2017-11-07 09:41:57 -05:00
James Bardin 49e6ecfd7a pass providers into modules via config
Implement the adding of provider through the module/providers map in the
configuration.

The way this works is that we start walking the module tree from the
top, and for any instance of a provider that can accept a configuration
through the parent's module/provider map, we add a proxy node that
provides the real name and a pointer to the actual parent provider node.
Multiple proxies can be chained back to the original provider.  When
connecting resources to providers, if that provider is a proxy, we can
then connect the resource directly to the proxied node. The proxies are
later removed by the DisabledProviderTransformer.

This should re-instate the 0.11 beta inheritance behavior, but will
allow us to later store the actual concrete provider used by a resource,
so that it can be re-connected if it's orphaned by removing its module
configuration.
2017-11-06 21:57:06 -05:00
James Bardin 6302916e65
Merge pull request #16572 from hashicorp/jbardin/provider-config
don't add missing provider aliases to the graph
2017-11-06 15:03:27 -05:00
James Bardin 72d4e15c47 ProvidedBy return value is a single string
Clean up ProvidedBy, which doesn't need to be a slice.
2017-11-06 14:27:01 -05:00
James Bardin d9d21d4200 don't add missing provider aliases to the graph
A missing provider alias should not be implicitly added to the graph.

Run the AttachaProviderConfigTransformer immediately after adding the
providers, since the ProviderConfigTransformer should have just added
these nodes.
2017-11-06 14:21:28 -05:00
Martin Atkins 37e276e043 core: test correct behavior of plan+apply with unstable values
We have a few pesky functions that don't act like proper functions and
instead return different values on each call. These are tricky because
we need to make sure we don't trip over ourselves by re-generating these
between plan and apply.

Here we add a context test to verify correct behavior in the presence
of such functions.

There's actually a pre-existing bug which this test caught as originally
written: we re-evaluate the interpolation expressions during apply,
causing these unstable functions to produce new values, and so the
applied value ends up not exactly matching the plan. This is a bug that
needs fixing, but it's been around at least since v0.7.6 (random old
version I tried this with to see) so we'll put it on the list and address
it separately. For now, this part of the test is commented out with a
TODO attached.
2017-11-03 16:11:13 -07:00
Martin Atkins c003e8f9a6 core: don't compare attribute values in Diff.Same
We previously didn't compare values but had a TODO to start doing so,
which we then recently did. Unfortunately it turns out that we _depend_
on not comparing values here, because when we use EvalCompareDiff (a key
user of Diff.Same) we pass in a diff made from a fresh re-interpolation
of the configuration and so any non-pure function results (timestamp,
uuid) have produced different values.
2017-11-03 16:11:13 -07:00
James Bardin 9b489c452e further simplify the missing provider transformer
We can remove the AllowAny option which is no longer used, and providers
don't need to be connected to their resources at this stage, since that
will happen in the ProviderTransformer.
2017-11-03 10:26:03 -04:00
James Bardin ecdba2b0b2 add transform step logs from GraphTransformMulti 2017-11-02 16:38:32 -04:00
James Bardin 241dae7ead resintate disabled tests
Reinstate the disabled tests that required some sort of inheritance
during graph evaluation.
2017-11-02 15:29:51 -04:00
James Bardin 05ef30be2c udpate test graph outputs
Some of the test graph outputs have changes now that implicit providers
are no longer added in the config.
2017-11-02 15:29:51 -04:00
James Bardin a782568645 simplify MissingProvider and ParentProvider transf
Simplify the MissingProviderTransformer so that it only adds missing
providers at the root level. There's no need for the multitple providers
added at every level of the path

ParentProviderTransformer then only needs to connect providers with the
equivalent type at the root level.
2017-11-02 15:29:51 -04:00
James Bardin 341ec39174 udpate more tests to remove intermediate providers
The new missing provider transformer doesn't add these nay longer
2017-11-02 15:29:51 -04:00
James Bardin 94ee4d9111 Add new test and update graph outputs
The the grandChild missing test has a provider declared in a child
module which is missing in a grandchildmodule. Verify that the
grandchild gets connected to the child provider, and they all are
connected to the root providers.

Update some test outputs to match the expected behavior of only adding
missing providers at the root level.
2017-11-02 15:00:06 -04:00
James Bardin 2f91007999 group the provider transformations
The series of provider transformations is important, and often repeated.
Group these together in a single transform function.
2017-11-02 15:00:06 -04:00
James Bardin 12a4a29cbd update missing provider transform test
The CloserProviderTransformer requires that the resources be connected
to their provider first, so that it cen get the correct dependencies,
and adding the ProviderTransformer changed the test output slightly.
2017-11-02 15:00:06 -04:00
James Bardin 8388dfd2f9 update GraphBuilder_targetModule test
The updates CLoseProviderTransformer connects all provider instances,
which is technically the correct behavior.
2017-11-02 15:00:06 -04:00
James Bardin a14fd0344c WIP reference providers by full name
This turned out to be a big messy commit, since the way providers are
referenced is tightly coupled throughout the code. That starts to unify
how providers are referenced, using the format output node Name method.

Add a new field to the internal resource data types called
ResolvedProvider. This is set by a new setter method SetProvider when a
resource is connected to a provider during graph creation. This allows
us to later lookup the provider instance a resource is connected to,
without requiring it to have the same module path.

The InitProvider context method now takes 2 arguments, one if the
provider type and the second is the full name of the provider. While the
provider type could still be parsed from the full name, this makes it
more explicit and, and changes to the name format won't effect this
code.
2017-11-02 15:00:06 -04:00
James Bardin 1d54d4b10d WIP start only referring to provier by adddress
Don't try to build a full adress based on the context path for providers
in EvalContextBuiltin. Only use the name explicitly provided.
2017-11-02 15:00:06 -04:00
James Bardin f0727501c1 WIP only add missing providers at the root level
When looking for providers to connect to resources, walk up the resource
path to find the appropriate provider.
2017-11-02 15:00:06 -04:00
James Bardin 0986d01223 add providers directly from the configuration
The first step in only using the required provider nodes in a graph is
to be able to specifically add them from the configuration.

The MissingProviderTransformer was previously responsible for adding
all providers. Now it is really just adding any that are missing from
the config.
2017-11-02 15:00:06 -04:00
Chris Marchesi 5031767b93 terraform: Add more exception cases for value comparison
Needed to add more cases to support value comparison exceptions that the
rest of TF expects to work (this fixes tests in various places).

Also moved things to a switch block so that it's a little more compact.
2017-11-01 14:25:32 -07:00
Chris Marchesi 12378b4ee2 terraform: Add value check to diff.Same
A diff new needs to pass basic value checks to be considered the
"same". Several provisions have been added to ensure that the list, set,
and RequiresNew behaviours that have needed some exceptions in the past
are preserved in this new logic.

This ensures that we are checking for value equality as much as
possible, which will be more important when we transition to the
possibility of diffs being sourced from external data.
2017-11-01 14:25:32 -07:00
James Bardin 3a495ffe56 rename ModuleStorage to Storage
get rid of stutter and use module.Storage
2017-10-27 13:11:21 -04:00
James Bardin 70a5b1b734 make terraform work with ModuleStorage 2017-10-27 13:06:07 -04:00
James Bardin fef687c340 enable output errors in dev branch 2017-10-27 09:13:52 -04:00
James Bardin 402f321abe change import module inheritance test
Importing into a module requires a provider config. Update the
inheritance test to reflect the new import restrictions.
2017-10-27 09:08:15 -04:00
James Bardin 2e505083cd change ProviderConfig.Scope to Path
Though it's intended for "interpolation scope", Path is generally used
for this elsewhere.
2017-10-27 09:08:15 -04:00
James Bardin f08bf76ef2 only cache Input "answers", always call Input
While merging the cached Input configs in the correct order prevents
overwriting existing config values, it doesn't prevent an earlier
provider from inserting unwanted values into later provider
configurations.

Diff the key-values returned by Input with the pre-input config, and
store only the "answers" that were added during the Input call.

Always call Input, even if we already have some values, since a
previously cached config may not be complete.
2017-10-27 09:08:15 -04:00
James Bardin d8f4c1f618 reverse the merge order for cached provider Input
Previously when looking up cached provider input, the Input was taken in
its entirety, and only provider configuration fields that weren't in the
saved input were added. This would cause providers in modules to use the
entire configuration from parent modules, even if they themselves had
entirely different configs.

Note: this is only marginally beter than the old behavior. It may be
slightly more correct, but stil can't account for the user's intent, and
may be adding configured values from one provider into another.

Change the PathCacheKey to just join the path on a non-path character
(|), which makes for easier debugging.
2017-10-27 09:08:15 -04:00
James Bardin 1536c531ff cleanup 2017-10-27 09:08:15 -04:00
James Bardin db7596c045 use the inherited provider configs in the graph
Use the configured providers directly, rather than looking for inherited
provider configuration during graph evaluation.

First remove the provider config cache, and the associated
SetProviderConfig and ParentProviderConfig methods on the eval context.
Every provider must be configured, so there's no need to look for
configuration from other provider instances.

The config.ProviderConfig struct now has a Scope field which stores the
proper path for the interpolation scope. To get this metadata to the
interpolator, we add an EvalInterpolatProvider node which can carry the
ProviderConfig, and an InterpolateProvider context method to carry the
ProviderConfig.Scope into the InterplationScope.

Some of the tests could be adjusted to account for the new inheritance
behavior, and some were simply no longer valid and will be removed.

The remaining tests have questions on how they should work in practice.
This mostly concerns orphaned modules where there is no longer a way to
obtain a provider. In some cases we may require that a minimal provider
config be present to handle the destroy process, but we need further
testing.

All disabled code was commented out in this commit to record any
additional comments. The following commit will be a cleanup pass.
2017-10-27 09:08:15 -04:00
James Bardin 36b8be43e8 use the new version package
Update all references to the version values to use the new package.
The VersionString function was left in the terraform package
specifically for the aws provider, which is vendored. We can remove that
last call once the provider is updated.
2017-10-19 21:48:08 -04:00
Martin Atkins 183833affc core: terraform.ResourceProvider.GetSchema method
In order to parse provider, resource and data source configuration from
HCL2 config files, we need to know the relevant configuration schema.
This new method allows Terraform Core to request these from a provider.

This is a breaking change to this interface, so all of its implementers
in this package are updated too. This includes concrete implementations
of the new method in helper/schema that use the schema conversion code
added in an earlier commit to produce a configschema.Block automatically.

Plugins compiled against prior versions of helper/schema will not have
support for this method, and so calls to them will fail. Callers of
this new method will therefore need to sniff for support using the
SchemaAvailable field added to both ResourceType and DataSource.

This careful handling will need to persist until next time we increment
the plugin protocol version, at which point we can make the breaking
change of requiring this information to be available.
2017-10-17 07:23:41 -07:00
James Bardin 67be68b521 Merge pull request #16242 from hashicorp/jbardin/race
minor race fix in tests
2017-10-02 16:50:02 -04:00
James Bardin 08ac4f3a2e Merge pull request #16089 from wgliang/optimization-merge-slice
Optimization merge slice
2017-10-02 16:40:13 -04:00
James Bardin 3ed7b1abec fix the providerWithLocals test
This test was set to fail once this issue was fixed, and now it's fixed.
2017-10-02 16:21:37 -04:00
James Bardin 3c2b3df5a9 add some output error tests
Add some tests for output errors and catch the errors behind the output
errors feature flag.
2017-10-02 16:20:29 -04:00
James Bardin 715036d209 put output errors behind a feature flag
We're going to start merging breaking functgionality behind feature
flags, to reduce the need for long-lived feature branches.
2017-10-02 16:20:29 -04:00
James Bardin 35c6a4e89d add DestroyValueReferenceTransformer
DestroyValueReferenceTransformer is used during destroy to reverse the
edges for output and local values. Because destruction is going to
remove these from the state, nodes that depend on their value need to be
visited first.
2017-10-02 16:20:29 -04:00
James Bardin 3414e1b996 remove dead code 2017-10-02 16:20:29 -04:00
James Bardin 7fde7d9f20 make a destroy plan work the same as destroy
When working on an existing plan, the context always used walkApply,
even if the plan was for a full destroy. Mark in the plan if it was
icreated for a destroy, and transfer that to the context when reading
the plan.
2017-10-02 16:20:29 -04:00
James Bardin 78964d305c remove broken outputs from targeted graph
A Targeted graph may include outputs that were transitively included,
but if they are missing any dependencies they will fail to interpolate
later on.

Prune any outputs in the TargetsTransformer that have missing
dependencies, and are not depended on by any resource. This will
maintain the existing behavior of outputs failing silently ni most
cases, but allow errors to be surfaced where the output value is
required.
2017-10-02 16:20:29 -04:00
James Bardin a048bcffa0 continue on output errors during Input
Module outputs may not have complete information during Input, because
it happens before refresh. Continue process on output interpolation
errors during the Input walk.
2017-10-02 16:20:29 -04:00
James Bardin 1ad97f6be8 use an EvalOpFilter for module variables
Remove the Input flag threaded through the input graph creation process
to prevent interpolation failures on module variables.
Use an EvalOpFilter instead to inset the correct EvalNode during
walkInput. Remove the EvalTryInterpolate type, and use the same
ContinueOnErr flag as the output node for consistency and to try and
keep the number possible eval node types down.
2017-10-02 16:20:29 -04:00
James Bardin c4dd31e62b "destroy" outputs too
Ouptuts don't need to be re-evaluated during destroy, since everything
is already in the state, so we can simply remove them.
2017-10-02 16:20:29 -04:00
James Bardin fc9ada463c minor race fix in tests 2017-10-02 16:19:01 -04:00
James Bardin 71e47e56a0 release: clean up after v0.10.7 2017-10-02 18:54:33 +00:00
James Bardin 8ba8fc79c1
v0.10.7 2017-10-02 18:46:49 +00:00
James Bardin da0e74276a fix provider with local value test and docs
Make sure this fails during destroy

Add a note in the documentation that local values may fail during
destroy.
2017-09-29 17:14:07 -04:00
James Bardin 061597304c add test for destroying with locals in a provider
Verify that locals aren't removed from the state before providers are
evaluated during destroy.
2017-09-28 15:31:41 -04:00
James Bardin 77396107c4 don't evaluate locals during destroy
Locals don't need to be evaluated during destroy.  Rather than simply
skipping them, remove them from the state as they are encountered. Even
though they are not persisted in the state, it keeps the state up to
date as the destroy happens, and we reduce the chance of other
inconstancies later on.
2017-09-28 12:56:25 -04:00
James Bardin 9d8ab55658 Add failing test for destroy with locals 2017-09-28 11:06:37 -04:00
Martin Atkins 2360f48a7d release: clean up after v0.10.6 2017-09-19 14:08:54 +00:00
Martin Atkins 8712b03839
v0.10.6 2017-09-19 13:56:27 +00:00
Martin Atkins 67bdadf5c6 release: clean up after v0.10.5 2017-09-14 21:40:05 +00:00
Martin Atkins 1f054df752
v0.10.5 2017-09-14 18:15:35 +00:00
Wang Guoliang 9a97c348f0
optimization:Merge slices 2017-09-13 21:08:41 +08:00
James Bardin 25f6e61047 release: clean up after v0.10.4 2017-09-06 20:33:48 +00:00
James Bardin 10df48ef40
v0.10.4 2017-09-06 20:22:10 +00:00
Martin Atkins 892f60efe0 core: test that we skip hooks for data source destroy
Data source destroy is an implementation detail and not something that
external callers should see or expect.
2017-09-01 17:55:05 -07:00
Martin Atkins e7a0aa96c8 core: add testHook for testing correct interaction with hooks 2017-09-01 17:55:05 -07:00
Martin Atkins 6712192724 core: don't advertise data source destroy via hooks
The fact that we clean up data source state by applying a "destroy" action
for them is an implementation detail, and so should not be visible to
outside callers or to the user.

Signalling these as real destroys creates confusion for users because
they see Terraform say things like:

    data.template_file.foo: Refreshing state..."

...which, to an understandably-nervous sysadmin, might make them suspect
that the underlying object was deleted, rather than just Terraform's
record of it.
2017-09-01 17:55:05 -07:00
Martin Atkins d4efc95191 command: show resource actions using resource addresses
Previously we were using the internal resource id syntax in the UI. Now
we'll use the standard user-facing resource address syntax instead.
2017-09-01 17:55:05 -07:00
Martin Atkins 3ea159297c command/format: improve consistency of plan results
Previously the rendered plan output was constructed directly from the
core plan and then annotated with counts derived from the count hook.
At various places we applied little adjustments to deal with the fact that
the user-facing diff model is not identical to the internal diff model,
including the special handling of data source reads and destroys. Since
this logic was just muddled into the rendering code, it behaved
inconsistently with the tally of adds, updates and deletes.

This change reworks the plan formatter so that it happens in two stages:
- First, we produce a specialized Plan object that is tailored for use
  in the UI. This applies all the relevant logic to transform the
  physical model into the user model.
- Second, we do a straightforward visual rendering of the display-oriented
  plan object.

For the moment this is slightly overkill since there's only one rendering
path, but it does give us the benefit of letting the counts be derived
from the same data as the full detailed diff, ensuring that they'll stay
consistent.

Later we may choose to have other UIs for plans, such as a
machine-readable output intended to drive a web UI. In that case, we'd
want the web UI to consume a serialization of the _display-oriented_ plan
so that it doesn't need to re-implement all of these UI special cases.

This introduces to core a new diff action type for "refresh". Currently
this is used _only_ in the UI layer, to represent data source reads.
Later it would be good to use this type for the core diff as well, to
improve consistency, but that is left for another day to keep this change
focused on the UI.
2017-09-01 17:55:05 -07:00
Martin Atkins 4750f0607d core: stabilize ResourceAddress.Less results
The implementation of ResourceAddress.Less was flawed because it was only
testing each field in the "less than" direction, and falling through in
cases where an earlier field compared greater than a later one.

Now we test for inequality first as the selector, and only fall through
if the two values for a given field are equal.
2017-09-01 17:55:05 -07:00
Martin Atkins 0a342e8dc2 config: allow local value interpolations in count
There is some additional, early validation on the "count" meta-argument
that verifies that only suitable variable types are used, and adding local
values to this whitelist was missed in the initial implementation.
2017-09-01 17:54:05 -07:00
Martin Atkins 8cd0ee80e5 config: merge/append for local values
It seems that this somehow got lost in the commit/rebase shuffle and
wasn't caught by the tests that _did_ make it because they were all using
just one file.

As a result of this bug, locals would fail to work correctly in any
configuration with more than one .tf file.

Along with restoring the append/merge behavior, this also reworks some of
the tests to exercise the multi-file case as better insurance against
regressions of this sort in future.

This fixes #15969.
2017-09-01 17:51:13 -07:00
Martin Atkins adb6a089ff release: clean up after v0.10.3 2017-08-30 21:56:26 +00:00
Martin Atkins 1511d447e7
v0.10.3 2017-08-30 21:41:28 +00:00
James Bardin 593bf683dc Merge pull request #15448 from hashicorp/jbardin/state-meta-equal
make sure marshaled Meta fields are still equal
2017-08-30 16:00:00 -04:00
Sunny 2d849f8650 command/init: check required_version
Previously we were checking required_version only during "real" operations, and not during initialization. Catching it during init is better because that's the first command users run on a new working directory.
2017-08-28 11:25:16 -07:00
Martin Atkins c12d64f340 Use t.Helper() in our test helpers
Go 1.9 adds this new function which, when called, marks the caller as
being a "helper function". Helper function stack frames are then skipped
when trying to find a line of test code to blame for a test failure, so
that the code in the main test function appears in the test failure output
rather than a line within the helper function itself.

This covers many -- but probaly not all -- of our test helpers across
various packages.
2017-08-28 09:59:30 -07:00
Martin Atkins 1da54955c6 core: remove shadow graph infrastructure
The shadow graph was incredibly useful during the 0.7 cycle but these days
it is idle, since we're not planning any significant graph-related changes
for the forseeable future.

The shadow graph infrastructure is somewhat burdensome since any change
to the ResourceProvider interface must have shims written. Since we _are_
expecting changes to the ResourceProvider interface in the next few
releases, I'm calling "YAGNI" on the shadow graph support to reduce our
maintenence burden.

If we do end up wanting to use shadow graph again in future, we'll always
be able to pull it out of version control and then make whatever changes
we skipped making in the mean time, but we can avoid that cost in the
mean time while we don't have any evidence that we'll need to pay it.
2017-08-28 08:40:22 -07:00
Martin Atkins 3a30bfe845 core: evaluate locals and return them for interpolation
We stash the locals in the module state in a map that is ignored for JSON
serialization. We don't include locals in the persisted state because they
can be trivially recomputed and this allows us to assume that they will
pass through verbatim, without any normalization or other transforms
caused by the JSON serialization.

From a user standpoint a local is just a named alias for an expression,
so it's desirable that the result passes through here in as raw a form
as possible, so it behaves as closely as possible to simply using the
given expression directly.
2017-08-21 15:15:25 -07:00
Martin Atkins 5b66953d1d core: graph nodes and edges for local values
A local value is similar to an output in that it exists only within state
and just always evaluates its value as best it can with the current state.
Therefore it has a single graph node type for all walks, which will
deal with that evaluation operation.
2017-08-21 15:15:25 -07:00
James Bardin f1042a1338 Merge pull request #15835 from hashicorp/jbardin/mock-provider-race
fix race in MockResourceProvider
2017-08-16 16:33:58 -04:00
Martin Atkins bf97909b8a core: document all of the fields on the Plan struct 2017-08-16 13:30:02 -07:00
James Bardin db6ef69e5b fix race in MockResourceProvider
Input can be called concurrently from multiple nodes in the graph.
2017-08-16 15:19:17 -04:00
James Bardin 08339b004b release: clean up after v0.10.2 2017-08-16 17:38:16 +00:00
James Bardin a1d06eb973
v0.10.2 2017-08-16 17:25:37 +00:00
James Bardin bb00fd47c0 release: clean up after v0.10.1 2017-08-15 22:21:17 +00:00
James Bardin f6d16263a0
v0.10.1 2017-08-15 21:50:02 +00:00
Radek Simko 93613ee526
terraform+dag: Set lower log levels 2017-08-14 11:43:45 +02:00
James Bardin 1664d4e228 test with bad interpolation during Input
The interpolation going into a module variable here will be valid after
Refresh, but Refresh doesn't happen for the Input phase.
2017-08-10 14:14:29 -04:00
James Bardin 97bb7cb65c Don't allow interpolation failure to stop Input
Allow module variables to fail interpolation during input. This is OK
since they will be verified again during Plan.  Because Input happens
before Refresh, module variable interpolation can fail when referencing
values that aren't yet in the state, but are expected after Refresh.
2017-08-10 14:14:29 -04:00
James Bardin 11668d5c8a Merge pull request #15599 from alrs/terraform-tests-swallowed-errors
Fix swallowed tests in terraform package tests
2017-08-04 12:09:00 -04:00
Jake Champlin 8e6a0845c1
Cleanup after 0.10 release 2017-08-02 14:40:37 -04:00
Lars Lehtonen 822a98a0b4
Fix swallowed tests in terraform package tests 2017-07-20 02:23:43 -07:00
Martin Atkins 1fac5de738 release: clean up after v0.10.0-rc1 2017-07-19 14:07:06 -07:00
Martin Atkins 243951c70a
v0.10.0-rc1 2017-07-19 14:05:43 -07:00
James Bardin a1727ec4c2 Add warning to mismatched plan state
Forward-port the plan state check from the 0.9 series.
0.10 has improved the serial handling for the state, so this adds
relevant comments and some more test coverage for the case of an
incrementing serial during apply.
2017-07-17 10:41:29 -04:00
James Bardin 501cbeaffe testState shouldn't rely on mods from WriteState
The state returned from the testState helper shouldn't rely on any
mutations caused by WriteState. The Init function (which is analogous to
NewState) shoudl set any required fields.
2017-07-05 17:47:05 -04:00
Martin Atkins 4d53eaa6df state: more robust handling of state Serial
Previously we relied on a constellation of coincidences for everything to
work out correctly with state serials. In particular, callers needed to
be very careful about mutating states (or not) because many different bits
of code shared pointers to the same objects.

Here we move to a model where all of the state managers always use
distinct instances of state, copied when WriteState is called. This means
that they are truly a snapshot of the state as it was at that call, even
if the caller goes on mutating the state that was passed.

We also adjust the handling of serials so that the state managers ignore
any serials in incoming states and instead just treat each Persist as
the next version after what was most recently Refreshed.

(An exception exists for when nothing has been refreshed, e.g. because
we are writing a state to a location for the first time. In that case
we _do_ trust the caller, since the given state is either a new state
or it's a copy of something we're migrating from elsewhere with its
state and lineage intact.)

The intent here is to allow the rest of Terraform to not worry about
serials and state identity, and instead just treat the state as a mutable
structure. We'll just snapshot it occasionally, when WriteState is called,
and deal with serials _only_ at persist time.

This is intended as a more robust version of #15423, which was a quick
hotfix to an issue that resulted from our previous slopping handling
of state serials but arguably makes the problem worse by depending on
an additional coincidental behavior of the local backend's apply
implementation.
2017-07-05 12:34:30 -07:00
Jake Champlin 9944ea6886
core: Skip provider checksum validation based on env var
Skips checksum validation if the `TF_SKIP_PROVIDER_VERIFY` environment variable is set. Undocumented variable, as the primary goal is to significantly improve the local provider development workflow.
2017-07-03 13:59:13 -04:00
James Bardin 124b80398e make sure marshaled Meta fields are still equal
When the InstanceState.Meta fields are marshaled, numeric values may
change types. The timeout system currently inserts integer values, which
will be unmarshal as float64s.

To ensure that a state which has round-tripped through json is equal to
itself, compare the json representation of the Meta values.
2017-06-30 18:29:42 -04:00
Martin Atkins 45a4ba1ea7 Merge #15344: Avoid double-counting resources to create 2017-06-27 10:48:45 -07:00
Chris Marchesi 0ca5eab545 core: Context-level test for stub EvalDiff
Added a new test that ensures that pre/post-diff hooks are not called
when EvalDiff is run with Stub set, tested through a full refresh run.
This helps test the expected behaviour of EvalDiff itself, versus the
end result of the diff being counted in a plan, which is what the
TestLocal_planScaleOutNoDupeCount test in backend/local checks.
2017-06-24 22:41:12 -07:00
Chris Marchesi 5654a676d9 core: Skip diff hooks for stubs on eval altogether
Rather than overloading InstanceDiff with a "Stub" attribute that is
going to be largely meaningless, we are just going to skip
pre/post-diff hooks altogether. This is under the notion that we will
eventually not need to "stub" a diff for scale-out, stateless nodes on
refresh at all, so diff behaviour won't be necessary at that point, so
we should not assume that hooks will run at this stage anyway.

Also as part of this removed the CountHook test that is now failing
because CountHook is out of scope of the new behaviour.
2017-06-24 08:01:17 -07:00
Chris Marchesi 656115387b core: Simplify TestNodeRefreshableManagedResourceEvalTree_scaleOut
This should make things a bit more clear as to what we are doing in the
EvalTree scale-out test - ensuring that we get the correct eval sequence
for a node with no state through EvalTree.
2017-06-23 17:37:51 -07:00
Chris Marchesi b486780cf0 core: evalTreeManagedScaleOutResource -> evalTreeManagedResourceNoState
We want to be a bit more explicit here as to when this eval sequence is
carried out. The why is now in the top-level comments.
2017-06-23 17:35:30 -07:00
Martin Atkins c4857bdbaf release: clean up after v0.10.0-beta1 2017-06-22 22:20:23 +00:00
Martin Atkins a26ff83279
v0.10.0-beta1 2017-06-22 20:55:33 +00:00
James Bardin 77cbd3bfc8 Merge pull request #15371 from hashicorp/jbardin/reinit-error
better UI output for requesting plugin related init
2017-06-22 15:53:13 -04:00
James Bardin b14677bd9a look for new error output 2017-06-22 15:37:32 -04:00
James Bardin 5be15ed77c have the local backend provide a plugin init msg
During plan and apply, because the provider constraints need to be built
from a plan, they are not checked until the terraform.Context is
created. Since the context is always requested by the backend during the
Operation, the backend needs to be responsible for generating contextual
error messages for the user.

Instead of formatting the ResolveProviders errors during NewContext,
return a special error type, ResourceProviderError to signal that
init will be required. The backend can then extract and format the
errors.
2017-06-22 13:15:30 -04:00
Rob Phoenix de2927d0b4 core: fix some typos in comments 2017-06-22 07:09:07 -07:00
Martin Atkins 53c0ff4017 core: ParseResourceAddressForInstanceDiff function
This is a specialized thin wrapper around parseResourceAddressInternal
that can be used to obtain a ResourceAddress from the keys in
ModuleDiff.Resources.

This is not something we'd ideally expose, but since the internal address
format is already exposed in the ModuleDiff object this ends up being
necessary to process the ModuleDiff from other packages, e.g. for
display in the UI.
2017-06-22 07:03:23 -07:00
Martin Atkins 482c1f1ea5 core: ResourceAddress.Less for sorting resource addresses
Lexicographic sorting by the string form produces the wrong result because
[9] sorts after [10], so this custom comparison function takes that into
account and compares each portion separately to get a more intuitive
result.
2017-06-22 07:03:23 -07:00
Chris Marchesi 0e3aedcea3 core: Remove ResourceRefreshPlannableTransformer
This transformer is no longer needed, as we are not transforming
scale-out resource nodes into plannable nodes anymore, but rather just
taking a different eval sequence for resource refresh nodes with no
state.
2017-06-22 04:14:35 -07:00
Chris Marchesi 01e3386e13 core: Add resource count scale-out EvalTree test
This test ensures that the right EvalSequence gets set for a refresh
node with no state. This will ultimately assert that nodes on scale out
will not go down the regular refresh path, which would result in an
error due to the nil state - instead, we stub this node so that we get a
diff on it that can be used to effect computed/unknown values on
interpolations that may depend on this node.
2017-06-22 03:44:16 -07:00
Chris Marchesi 42ebbc6e0e core: ScaleIn should have been ScaleOut
We are actually acting on/fixing the scale-out here (ie: new child node
from count with no state), not scale-in.
2017-06-22 03:43:05 -07:00
Chris Marchesi 565790d8da core: Fix scale-out refresh graph test
Since the transformer that changed stateless nodes in refresh to
NodePlannableResourceInstance is not being used anymore, this test
needed to be adjusted to ensure that the right output was expected.
2017-06-21 09:15:50 -07:00
Chris Marchesi 45528b2217 core: Instance/EvalDiff.Quiet -> Stub
Changed the language of this field to indicate that this diff is not a
"real" diff, in that it should not be acted on, versus a "quiet" mode,
which would indicate just simply to act silently.
2017-06-21 09:15:08 -07:00
Chris Marchesi eef933f2a7 core: Don't count scaled-out resources twice in the UI
This fixes a bug with the new refresh graph behaviour where a resource
was being counted twice in the UI on part of being scaled out:

 * We are no longer transforming refresh nodes without state to
   plannable resources (the transformer will be removed shortly)
 * A Quiet flag has been added to EvalDiff and InstanceDiff - this
   allows for the flagging of a diff that should not be treated as real
   diff for purposes of planning
 * When there is no state for a refresh node now, a new path is taken
   that is similar to plan, but flags Quiet, and does nothing with the
   diff afterwards.

Tests pending - light testing has confirmed this should fix the double
count issue, but we should have some tests to actually confirm the bug.
2017-06-20 07:37:32 -07:00
Martin Atkins a8c58b081c core: -target option to also select resources in descendant modules
Previously the behavior for -target when given a module address was to
target only resources directly within that module, ignoring any resources
defined in child modules.

This behavior turned out to be counter-intuitive, since users expected
the -target address to be interpreted hierarchically.

We'll now use the new "Contains" function for addresses, which provides
a hierarchical "containment" concept that is more consistent with user
expectations. In particular, it allows module.foo to match
module.foo.module.bar.aws_instance.baz, where before that would not have
been true.

Since Contains isn't commutative (unlike Equals) this requires some
special handling for targeting specific indices. When given an argument
like -target=aws_instance.foo[0], the initial graph construction (for
both plan and refresh) is for the resource nodes from configuration, which
have not yet been expanded to separate indexed instances. Thus we need
to do the first pass of TargetsTransformer in mode where indices are
ignored, with the work then completed by the DynamicExpand method which
re-applies the TargetsTransformer in index-sensitive mode.

This is a breaking change for anyone depending on the previous behavior
of -target, since it will now select more resources than before. There is
no way provided to obtain the previous behavior. Eventually we may support
negative targeting, which could then combine with positive targets to
regain the previous behavior as an explicit choice.
2017-06-16 16:36:08 -07:00
Martin Atkins d3eb2b2d28 core: ResourceAddress.Contains method
This is similar in purpose to Equals but it takes a hierarchical approach
where modules contain their child modules, resources are contained by
their modules, and indexed resource instances are contained by their
resource names.

Unlike "Equals", Contains is intended to be transitive, so if A contains B
and B contains C, then C necessarily contains A. It is also directional:
if A contains B then B does not also contain A unless A and B are
identical. This results in more intuitive behavior for use-cases where
the goal is to select a portion of the address space for an operation.
2017-06-16 16:36:08 -07:00
Martin Atkins d4e5abe0eb core: terraform.env variable is now terraform.workspace
As part of our terminology shift, the interpolation variable for the name
of the current workspace changes to terraform.workspace. The old name
continues to be supported for compatibility.

We can't generate a deprecation warning from here so for now we'll just
silently accept terraform.env as an alias, but not mention it at all in
the error message in the hope that its use phases out over time before we
actually remove it.
2017-06-09 15:01:39 -07:00
Martin Atkins 1b673746fd core: don't allow core or providers to change between plan and apply
The information stored in a plan is tightly coupled to the Terraform core
and provider plugins that were used to create it, since we have no
mechanism to "upgrade" a plan to reflect schema changes and so mismatching
versions are likely to lead to the "diffs didn't match during apply"
error.

To allow us to catch this early and return an error message that _doesn't_
say it's a bug in Terraform, we'll remember the Terraform version and
plugin binaries that created a particular plan and then require that
those match when loading the plan in order to apply it.

The planFormatVersion is increased here so that plan files produced by
earlier Terraform versions _without_ this information won't be accepted
by this new version, and also that older versions won't try to process
plans created by newer versions.
2017-06-09 14:03:59 -07:00
Martin Atkins aa1c644499 core: allow setting required plugin hashes on Context
When set, this information gets passed on to the provider resolver as
part of the requirements information, causing us to reject any plugins
that do not match during initialization.
2017-06-09 14:03:59 -07:00
Martin Atkins 190626e2a8 core: improve consistency of ParseResourceAddress errors
Previously one of the errors had a built-in context message and the other
did not, making it hard for callers to present a user-friendly message
in both cases.

Now we generate an error message of the same form in both cases, with one
case providing additional information. Ideally the main case would be
able to give more specific guidance too, but that's hard to achieve with
the current regexp-based parsing implementation.
2017-06-09 14:03:59 -07:00
Martin Atkins b82ef2e30e core: ResourceAddress.MatchesConfig method
This is a useful building block for filtering configuration based on a
resource address. It is similar in principle to state filtering, but for
specific resource configuration blocks.
2017-06-09 14:03:59 -07:00
Martin Atkins edf3cd7159 core: ResourceAddress.WholeModuleAddress method
This allows growing the scope of a resource address to include all of the
resources in the same module as the targeted resource. This is useful to
give context in error messages.
2017-06-09 14:03:59 -07:00
Martin Atkins 05a5eb0047 core: ResourceAddress.HasResourceSpec method
The resource address documentation defines a resource address as being in
two parts: the module path and the resource spec. The resource spec can
be omitted, which represents addressing _all_ resources in a module.

In some cases (such as import) it doesn't make sense to address an entire
module, so this helper makes it easy for validation code to check for
this to reject insufficiently-specific resource addresses.
2017-06-09 14:03:59 -07:00
James Bardin 7d2d951f27 Rename VersionSet to Constraints
VersionSet is a wrapper around version.Contraints, so rename it it as
such.
2017-06-09 14:03:59 -07:00
Martin Atkins ccb3a7c584 core: expose terraform.ModuleTreeDependencies as a public function
This is a generally-useful utility for computing dependency trees, so no
reason to restrict it to just the terraform package.
2017-06-09 14:03:59 -07:00
Martin Atkins 4ab8973520 core: provide config to all import context tests
We're going to use config to determine provider dependencies, so we need
to always provide a config when instantiating a context or we'll end up
loading no providers at all.

We previously had a test for running "terraform import -config=''" to
disable the config entirely, but this test is now removed because it makes
no sense. The actual functionality its testing still remains for now,
but it will be removed in a subsequent commit when we start requiring that
a resource to be imported must already exist in configuration.
2017-06-09 14:03:59 -07:00
Martin Atkins c835ef8ff3 Update tests for the new ProviderResolver interface
Rather than providing an already-resolved map of plugins to core, we now
provide a "provider resolver" which knows how to resolve a set of provider
dependencies, to be determined later, and produce that map.

This requires the context to be instantiated in a different way, so this
very noisy diff is a mostly-mechanical update of all of the existing
places where contexts get created for testing, using some adapted versions
of the pre-existing utilities for passing in mock providers.
2017-06-09 14:03:59 -07:00
Martin Atkins 7ca592ac06 core: use ResourceProviderResolver to resolve providers
Previously the set of providers was fixed early on in the command package
processing. In order to be version-aware we need to defer this work until
later, so this interface exists so we can hold on to the possibly-many
versions of plugins we have available and then later, once we've finished
determining the provider dependencies, select the appropriate version of
each provider to produce the final set of providers to use.

This commit establishes the use of this new mechanism, and thus populates
the provider factory map with only the providers that result from the
dependency resolution process.

This disables support for internal provider plugins, though the
mechanisms for building and launching these are still here vestigially,
to be cleaned up in a subsequent commit.

This also adds a new awkward quirk to the "terraform import" workflow
where one can't import a resource from a provider that isn't already
mentioned (implicitly or explicitly) in config. We will do some UX work
in subsequent commits to make this behavior better.

This breaks many tests due to the change in interface, but to keep this
particular diff reasonably easy to read the test fixes are split into
a separate commit.
2017-06-09 14:03:59 -07:00
Martin Atkins ba3ee00837 core: ResourceProviderResolver interface
ResourceProviderResolver is an extra level of indirection before we
get to a map[string]ResourceProviderFactory, which accepts a map of
version constraints and uses it to choose from potentially-many available
versions of each provider to produce a single ResourceProviderFactory
for each one requested.

As of this commit the ResourceProviderResolver interface is not used. In
a future commit the ContextOpts.Providers map will be replaced with a
resolver instance, with the creation of the factory delayed until the
version constraints have been resolved.
2017-06-09 14:03:59 -07:00
Martin Atkins 1c0b715999 core: return explicit caption if tests fail to construct context
The previous error was very generic, making it hard to quickly tell from
the test output that the error was during context initialization.
2017-06-09 14:03:59 -07:00
Martin Atkins 8bfc6e7b1c core: add missing ResourceState types in context tests
Previously the Type of a ResourceState was generally ignored, but we're
now starting to use it to figure out which providers are needed to
support the resources in state so our tests need to set it accurately
in order to get the expected result.
2017-06-09 14:03:59 -07:00
Martin Atkins 25a6d8f471 core: build a module dependency tree from config+state
This new private function takes a configuration tree and a state structure
and finds all of the explicit and implied provider dependencies
represented, returning them as a moduledeps.Module tree structure.

It annotates each dependency with a "reason", which is intended to be
useful to a user trying to figure out where a particular dependency is
coming from, though we don't yet have any UI to view this.

Nothing calls this yet, but a subsequent commit will use the result of
this to produce a constraint-conforming map of provider factories during
context initialization.
2017-06-09 14:03:59 -07:00
Martin Atkins 0b14c2cdb3 Resolve resource provider types in config package
Previously the logic for inferring a provider type from a resource name
was buried a utility function in the 'terraform' package. Instead here we
lift it up into the 'config' package where we can make broader use of it
and where it's easier to discover.
2017-06-09 14:03:59 -07:00
Martin Atkins 9e0c52c6db release: clean up after v0.9.8 2017-06-08 00:26:19 +00:00
Martin Atkins 8d560482c3
v0.9.8 2017-06-08 00:14:54 +00:00
stack72 1b78f50db5 release cleanup after v0.9.7 2017-06-07 17:45:11 +03:00
stack72 20ca74d0a0
v0.9.7 2017-06-07 14:34:30 +00:00
Radek Simko 1244309579 Fix stringer comments (#15069) 2017-06-05 10:17:35 +01:00
He Guimin 87562be855 provider/alicloud: Add the function of replacing ecs instance's system disk (#15048)
* add replacing system disk function for ecs

* remove ForceNew of system_disk_size
2017-06-05 11:27:49 +03:00
Gavin Williams 401c6a95a7 provider/openstack: Add Terraform version to UserAgent string (#14955)
* core: Add 'UserAgentString' helper function to generate a standard UserAgent string. Example generation: 'Terraform 0.9.7-dev (go1.8.1)'

* provider/openstack: Add Terraform version to UserAgent string
2017-06-01 22:12:25 -06:00
Jake Champlin ac177492fb
core: Revert stringer changes from earlier commits 2017-06-01 11:37:12 -04:00
Thomas Schaaf 79c91e11c8 provider/aws: Add aws elastic beanstalk solution stack (#14944)
* Add aws elastic beanstalk solution stack

Signed-off-by: Thomas Schaaf <thomaschaaf@Thomass-MBP.fritz.box>

* Fix incorrect naming

Signed-off-by: Thomas Schaaf <thomaschaaf@Thomass-MBP.fritz.box>

* Use unique go variable/function names

Signed-off-by: Thomas Schaaf <thomaschaaf@Thomass-MacBook-Pro.local>

* Add docs to sidebar

* Sort provider by alphabet

* Fix indent

* Add required statement

* Fix acceptance test
2017-06-01 02:23:06 +03:00
clint d6fcc82ecc release: clean up after v0.9.6 2017-05-25 16:09:31 +00:00
clint 85e0979c6a
v0.9.6 2017-05-25 15:56:03 +00:00
Martin Atkins 410b60cb7f Stop requiring multi-vars (splats) to be in array brackets
Prior to Terraform 0.7, lists in Terraform were just a shallow abstraction
on top of strings with a magic delimiter between items. Wrapping a single
string in brackets in the configuration was Terraform's prompt that it
needed to split the string on that delimiter during interpolation.

In 0.7, when first-class lists were added, this convention was preserved
by flattening lists-of-lists by one level when they were encountered in
configuration. However, there was an oversight in that change where it
did not correctly handle the case where the inner list was unknown.

In #14135 we removed some code that was flattening partially-unknown lists
into fully-unknown (untyped) values. This inadvertently exposed the missed
case from the previous paragraph, causing issues for list-wrapped splat
expressions with unknown members. While this worked fine for resources,
due to some fixup done inside helper/schema, this did not work for other
interpolation contexts such as module blocks.

Various attempts to fix this up and restore the flattening behavior
selectively were unsuccessful, due to a proliferation of assumptions all
over the core code that would be too risky to change just to fix this bug.

This change, then, takes the different approach of removing the
requirement that splats be presented inside list brackets. This
requirement didn't make much sense anymore anyway, since no other
list-returning expression had this constraint and so the rest of Terraform
was already successfully dealing with both cases.

This leaves us with two different scenarios:

- For resource arguments, existing normalization code in helper/schema
  does its own flattening that preserves compatibility with the common
  practice of using bracketed splats. This change proves this with a test
  within the "test" provider that exercises the whole Terraform core and
  helper/schema stack that assigns bracketed splats to list and set
  attributes.

- For arguments in other blocks, such as in module callsites, the
  interpolator's own flattening behavior applies to known lists,
  preserving compatibility with configurations from before
  partially-computed splats were possible, but those wishing to use
  partially-computed splats are required to drop the surrounding brackets.
  This is less concerning because this scenario was introduced only in
  0.9.5, so the scope for breakage is limited to those who adopted this
  new feature quickly after upgrading.

As of this commit, the recommendation is to stop using brackets around
splats but the old form continues to be supported for backward
compatibility. In a future _major_ version of Terraform we will probably
phase out this legacy form to improve consistency, but for now both
forms are acceptable at the expense of some (pre-existing) weird behavior
when _actual_ lists-of-lists are used.

This addresses #14521 by officially adopting the suggested workaround of
dropping the brackets around the splat. However, it doesn't yet allow
passing of a partially-unknown list between modules: that still violates
assumptions in Terraform's core, so for the moment partially-unknown lists
work only within a _single_ interpolation expression, and cannot be
passed around between expressions. Until more holistic work is done to
improve Terraform's type handling, passing a partially-unknown splat
through to a module will result in a fully-unknown list emerging on
the other side, just as was the case before #14135; this change just
addresses the fact that this was failing with an error in 0.9.5.
2017-05-23 11:22:37 -07:00
Jake Champlin 91ab75991d
core: use codified default for prerelease string 2017-05-22 11:28:15 -04:00
Jake Champlin bd68789006
core: Use environment variables to set VersionPrerelease at compile time
Instead of using a hardcoded version prerelease string, which makes release automation difficult, set the version prerelease string from an environment variable via the go linker tool during compile time.

The environment variable `TF_RELEASE` should only be set via the `make bin` target, and thus leaves the version prerelease string unset. Otherwise, when running a local compile of terraform via the `make dev` makefile target, the version prerelease string is set to `"dev"`, as usual.

This also requires some changes to both the circonus and postgresql providers, as they directly used the `VersionPrerelease` constant. We now simply call the `VersionString()` function, which returns the proper interpolated version string with the prerelease string populated correctly.

`TF_RELEASE` is unset:

```sh
$ make dev
==> Checking that code complies with gofmt requirements...
go generate $(go list ./... | grep -v /terraform/vendor/)
2017/05/22 10:38:19 Generated command/internal_plugin_list.go
==> Removing old directory...
==> Building...
Number of parallel builds: 3

-->     linux/amd64: github.com/hashicorp/terraform

==> Results:
total 209M
-rwxr-xr-x 1 jake jake 209M May 22 10:39 terraform

$ terraform version
Terraform v0.9.6-dev (fd472e4a86500606b03c314f70d11f2bc4bc84e5+CHANGES)
```

`TF_RELEASE` is set (mimicking the `make bin` target):

```sh
$ TF_RELEASE=1 make dev
==> Checking that code complies with gofmt requirements...
go generate $(go list ./... | grep -v /terraform/vendor/)
2017/05/22 10:40:39 Generated command/internal_plugin_list.go
==> Removing old directory...
==> Building...
Number of parallel builds: 3

-->     linux/amd64: github.com/hashicorp/terraform

==> Results:
total 121M
-rwxr-xr-x 1 jake jake 121M May 22 10:42 terraform

$ terraform version
Terraform v0.9.6
```
2017-05-22 10:49:15 -04:00
Martin Atkins 45b04c826a core: don't crash if no module state exists for multi var
For child modules, a ModuleState isn't allocated until the first time a
module instance is inserted into the state under the module's path.
Normally interpolations of resource attributes are delayed until at least
one resource has been created due to the nature of the dependency graph,
but if the interpolation value is a multi-var (splat) then it is possible
that the referenced resource has count=0 and thus created _no_ resource
states when it was visited.

Previously we would crash when trying to access the resource map for the
nil module in order to count how many instances are present. Since we know
there can't be any instances present in a nil module, we now preempt
this crash by returning zero early.

This edge-case does not apply to the root module because its ModuleState
is allocated as part of initializing the main State instance.

This fixes #14438.
2017-05-16 09:54:33 -07:00
Chris Marchesi 11b4794612 core: Test for new refresh graph behaviour
Tests on DynamicExpand for both resources and data sources, cover scale
in/out scenarios, and also a verification for the behaviour of config
orphans.
2017-05-12 15:45:06 -07:00
Chris Marchesi 7b1618efde core: Fix destroy factory in data source refresh expander 2017-05-12 15:45:06 -07:00
Chris Marchesi b807505d55 core: New refresh graph building behaviour
Currently, the refresh graph uses the resources from state as a base,
with data sources then layered on. Config is not consulted for resources
and hence new resources that are added with count (or any new resource
from config, for that matter) do not get added to the graph during
refresh.

This is leading to issues with scale in and scale out when the same
value for count is used in both resources, and data sources that may
depend on that resource (and possibly vice versa). While the resources
exist in config and can be used, the fact that ConfigTransformer for
resources is missing means that they don't get added into the graph,
leading to "index out of range" errors and what not.

Further to that, if we add these new resources to the graph for scale
out, considerations need to be taken for scale in as well, which are not
being caught 100% by the current implementation of
NodeRefreshableDataResource. Scale-in resources should be treated as
orphans, which according to the instance-form NodeRefreshableResource
node, should be NodeDestroyableDataResource nodes, but this this logic
is currently not rolled into NodeRefreshableDataResource. This causes
issues on scale-in in the form of race-ish "index out of range" errors
again.

This commit updates the refresh graph so that StateTransformer is no
longer used as the base of the graph. Instead, we add resources from the
state and config in a hybrid fashion:

 * First off, resource nodes are added from config, but only if
   resources currently exist in state.  NodeRefreshableManagedResource
   is a new expandable resource node that will expand count and add
   orphans from state. Any count-expanded node that has config but no
   state is also transformed into a plannable resource, via a new
   ResourceRefreshPlannableTransformer.
 * The NodeRefreshableDataResource node type will now add count orphans
   as NodeDestroyableDataResource nodes. This achieves the same effect
   as if the data sources were added by StateTransformer, but ensures
   there are no races in the dependency chain, with the added benefit of
   directing these nodes straight to the proper
   NodeDestroyableDataResource node.
 * Finally, config orphans (nodes that don't exist in config anymore
   period) are then added, to complete the graph.

This should ensure as much as possible that there is a refresh graph
that best represents both the current state and config with updated
variables and counts.
2017-05-12 15:45:06 -07:00
Chris Marchesi dfb5be2413 Rename NodeRefreshableResource to NodeRefreshableResourceInstance
In prep for NodeRefreshableResource becoming an
NodeAbstractCountResource and implementing GraphNodeDynamicExpandable.
2017-05-12 15:40:13 -07:00
Martin Atkins 7bdf4a925d core: Allow downstream targeting of certain node types
The previous behavior of targets was that targeting a particular node
would implicitly target everything it depends on. This makes sense when
the dependencies in question are between resources, since we need to
make sure all of a resource's dependencies are in place before we can
create or update it.

However, it had the undesirable side-effect that targeting a resource
would _exclude_ any outputs referring to it, since the dependency edge
goes from output to resource. This then causes the output to be "stale",
which is problematic when outputs are being consumed by downstream
configs using terraform_remote_state.

GraphNodeTargetDownstream allows nodes to opt-in to a new behavior where
they can be targeted by _inverted_ dependency edges. That is, it allows
outputs to be considered targeted if anything they directly depend on
is targeted.

This is different than the implied targeting behavior in the other
direction because transitive dependencies are not considered unless the
intermediate nodes themselves have TargetDownstream. This means that
an output1→output2→resource chain can implicitly target both outputs, but
an output→resource1→resource2 chain _won't_ target the output if only
resource2 is targeted.

This behavior creates a scenario where an output can be visited before
all of its dependencies are ready, since it may have a mixture of both
targeted and untargeted dependencies. This is fine for outputs because
they silently ignore any errors encountered during interpolation anyway,
but other hypothetical future implementers of this interface may need to
be more careful.

This fixes #14186.
2017-05-11 11:57:46 -07:00
stack72 7cb334b635 release: clean up after v0.9.5 2017-05-11 09:32:32 +00:00
stack72 a59ee0b30e
v0.9.5 2017-05-11 09:22:11 +00:00
Martin Atkins 58f5257678 core: context test for partially-unknown splat lists
This is a context test for the behavior enabled by #14135, as some
insurance to decrease the chance that we break it again.
2017-05-04 16:55:32 -07:00
Martin Atkins b4df03bca4 core: allow partially-unknown lists from splat syntax
This was actually redundant anyway since HIL itself applied a similar
rule where any partially-unknown list would be automatically flattened
to a single unknown value.

However, now we're changing HIL to explicitly permit partially-unknown
lists so that we can allow the index operator [...] to succeed when
applied to one of the elements that _is_ known.

This, in conjunction with hashicorp/hil#51 and hashicorp/hil#52,
fixes #3449.
2017-05-04 15:56:35 -07:00
James Bardin 78c2720a4c Merge pull request #13793 from paybyphone/data_source_plan_count_boundary
core: Add CountBoundaryTransformer to the plan graph builder
2017-04-27 11:22:57 -04:00
tombuildsstuff 74eec4fab5 release: clean up after v0.9.4 2017-04-26 12:45:27 +00:00
tombuildsstuff 277bbf65d1
v0.9.4 2017-04-26 12:35:28 +00:00
Martin Atkins b1763e262a Restore stringer-generated files back to new version
stringer has changed the boilerplate it generates in a recent version.
We'd previously updated to the new format but accientally rolled back
to the old while merging a long-running feature branch.

This restores us back to the new format again.
2017-04-21 14:49:18 -07:00
James Bardin f4a37ed19a Merge pull request #13854 from hashicorp/jbardin/testraces
fix a few races in the context tests
2017-04-21 13:23:12 -04:00
James Bardin ad1cef4227 fix a few races in the context tests
these were so infrequent that the race detector couldn't catch them
either, but on a heavily loaded CI host they occasionally fail.
2017-04-21 12:30:53 -04:00
Jasmin Gacic 61499cfcf0 Provider Oneandone (#13633)
* Terraform Provider 1&1

* Addressing pull request remarks

* Fixed imports

* Fixing remarks

* Test optimiziation
2017-04-21 17:19:10 +03:00
Chris Marchesi 744727a28a core: Trap warnings as well as errors on resourceNestedCount test 2017-04-20 07:31:44 -07:00
Chris Marchesi d41b806789 core: Restore CountBoundaryTransformer to apply, add/adjust tests
Moving the transformer wholesale looks like it broke some tests, with
some actually doing legit work in normalizing singular resources from a
foo.0 notation to just foo.

Adjusted the TestPlanGraphBuilder to account for the extra
meta.count-boundary nodes in the graph output now, as well as added
another context test that tests this case. It appears the issue happens
during validate, as this is where the state can be altered to a broken
state if things are not properly transformed in the plan graph.
2017-04-19 22:23:52 -07:00
Chris Marchesi 2802d319d2 core: Move CountBoundaryTransformer to the plan graph builder
This fixes interpolation issues on grandchild data sources that have
multiple instances (ie: counts). For example, baz depends on bar, which
depends on foo.

In this instance, after an initial TF run is done and state is saved,
the next refresh/plan is not properly transformed, and instead of the
graph/state coming through as data.x.bar.0, it comes through as
data.x.bar.  This breaks interpolations that rely on splat operators -
ie: data.x.bar.*.out.
2017-04-19 16:56:54 -07:00
Sander van Harmelen 3d0073e05c core: fix a crash by suggesting a different approach to solve #11170 (#13541)
* Revert #11245, #11321, #11498 and #11757

These PR’s are all related to issue #11170 for which I would like to propose a different solution then the one currently implemented.

* A different approach to solve #11170

This approach has (IMHO) a few advantages with regards to the solution currently implemented. I will elaborate on this in the PR.
2017-04-14 22:32:30 +02:00
James Bardin 928e60672f context Refresh and Apply sometimes return nil
The documentation for Refresh indicates that it will always return a
valid state, but that wasn't true in the case of a graph builder error.
While this same concept wasn't documented for Apply, it was still
assumed in the terraform apply code.

Since the helper testing framework relies on the absence of a state to
determine if it can call Destroy, the Context can't can't start
returning a state in all cases. Document this, and use the State method
to fetch the correct state value after Apply.

Add a nil check to the WriteState function, so that writing a nil state
is a noop.

Make sure to init before sorting the state, to make sure we're not
attempting to sort nil values. This isn't technically needed with the
current code, but it's just safer in general.
2017-04-14 14:56:10 -04:00
Sander van Harmelen 051582d32a Add the close provider and provisioner transformers (#13102) 2017-04-12 23:25:15 +02:00
Martin Atkins 381adca0af release: clean up after v0.9.3 2017-04-12 20:39:57 +00:00
Martin Atkins 1601af7a07
v0.9.3 2017-04-12 20:21:42 +00:00
James Bardin 7d4cceb787 Merge pull request #13502 from hashicorp/jbardin/dedupe-depends_on
Remove duplicate entries from resource Dependencies
2017-04-10 12:06:54 -04:00
Benjamin Lau ba09e7dc5a the invalid variable syntax error message was misleading. changed text a little bit (#11953) 2017-04-10 08:37:12 -05:00
James Bardin 3f49227b72 add state an context tests
Make sure duplicate depends_on entries are pruned from existing states
on read.

Make sure new state built from configs with multiple references to the
same resource only add it once to the Dependencies.
2017-04-08 15:37:15 -04:00
James Bardin bd983f6cba don't forget to test the simple things 2017-04-08 15:37:15 -04:00
James Bardin b45b6a5c20 remove duplicates in Dependencies
duplicate entries could end up in "depends_on" in the state, which could
possible lead to erroneous state comparisons. Remove them when walking
the graph, and remove existing duplicates when pruning the state.
2017-04-08 15:37:15 -04:00
Martin Atkins e4a5d36127 core: EvalVariableBlock to decode maps and slices more carefully
Previously this function was depending on the mapstructure behavior of
failing with an error when trying to decode a map into a list or
vice-versa, but mapstructure's WeakDecode behavior changed so that it
will go to greater lengths to coerce the given value to fit into the
target type, causing us to mis-handle certain ambigous cases.

Here we exert a bit more control over what's going on by using 'reflect'
to first check whether we have a slice or map value and only then try
to decode into one with mapstructure. This allows us to still rely on
mapstructure's ability to decode nested structures but ensure that lists
and maps never get implicitly converted to each other.
2017-04-07 17:05:14 -07:00
Martin Atkins 0e963db2c5 Detect and reject unknown attributes in "connection" blocks
Since the validation of connection blocks is delegated to the communicator
selected by "type", we were not previously doing any validation of the
attribute names in these blocks until running provisioners during apply.

Proper validation here requires us to already have the instance state,
since the final connection info is a merge of values provided in config
with values assigned automatically by the resource. However, we can do
some basic name validation to catch typos during the validation pass, even
though semantic validation and checking for missing attributes will still
wait until the provisioner is instantiated.

This fixes #6582 as much as we reasonably can.
2017-04-06 13:46:43 -07:00
Martin Atkins 28d6d913e4 core: basic test of EvalVariableBlock
This previously lacked tests altogether. This new test verifies the
"happy path", ensuring that both literal and computed values pass through
correctly into the VariableValues map.
2017-04-04 12:16:19 -07:00
Martin Atkins c1c5c9a2f6 core: fix crash when computed nested map given in module block
This crash resulted because the type switch checked for either of two
types but the type assertion within it assumed only one of them.

A straightforward (if inelegant) fix is to simply duplicate the relevant
case block and change the type assertion, thus allowing the types to match
up in all cases.

This fixes #13297.
2017-04-04 12:16:19 -07:00
Martin Atkins dd8af65c82 core: Input walk shouldn't clobber dynamic provider config
During the input walk we stash the values resulting from user input
(if any) in the eval context for use when later walks need to resolve
the provider config.

However, this repository of input results is only able to represent
literal values, since it does not retain the record of which of the keys
have values that are "computed".

Previously we were blindly stashing all of the results, failing to
consider that some of them might be computed. That resulted in the
UnknownValue placeholder being misinterpreted as a literal value when
the data is used later, which ultimately resulted in it clobbering the
actual expression evaluation result and thus causing the provider to
fail to configure itself.

Now we are careful to only retain in this repository the keys whose values
are known statically during the input phase. This eventually gets merged
with the dynamic evaluation results on subsequent walks, with the dynamic
keys left untouched due to their absence from the stored input map.

This fixes #11264.
2017-04-04 10:31:42 -07:00
James Bardin c55a5082f5 delegate BackendState.Rehash to config.Backend 2017-03-29 18:01:03 -04:00
James Bardin ff2d753062 add Rehash to terraform.BackendState
This method mirrors that of config.Backend, so we can compare the
configration of a backend read from a config vs that of a backend read
from a state. This will prevent init from reinitializing when using
`-backend-config` options that match the existing state.
2017-03-29 15:53:42 -04:00
Martin Atkins 21cd5595e2 Update stringer-generated files to new boilerplate
golang/tools commit 23ca8a263 changed the format of the leading comment
to comply with some new standards discussed here:
https://golang.org/issue/13560

This is the result of running generate with the latest version of
stringer. Everyone working on Terraform will need to update stringer
after this is merged, to avoid reverting this:
    go get -u golang.org/x/tools/cmd/stringer
2017-03-29 08:07:06 -07:00
Paul Stack 7479b8d150 release: clean up after v0.9.2 2017-03-28 10:05:25 +00:00
Paul Stack 6365269541
v0.9.2 2017-03-28 09:56:35 +00:00
Mitchell Hashimoto 69759e04ca
terraform: convert empty path to root path in V1 state 2017-03-21 11:37:12 -07:00
Mitchell Hashimoto e7b07e109f
terraform: V1 to V2 upgrade should treat nil path as root path
It appears there are no tests for this as far as I can find.

We change V1 states (very old) to assume a nil path is a root path.
Staet.Validate() later will catch any duplicate paths.
2017-03-21 11:12:44 -07:00
James Bardin b7152c4405 Merge pull request #12897 from hashicorp/jbardin/ignore-changes
ignore_changes causes keys in other flatmapped objects to be lost from diff
2017-03-21 09:25:47 -04:00
James Bardin 0ae0076e3a Correctly filter flatmapped values in diff
When transforming a diff from DestroyCreate to a simple Update,
ignore_changes can cause keys from flatmapped objects to be filtered
form the diff. We need to filter each flatmapped container as a whole to
ensure that unchanged keys aren't lost in the update.
2017-03-21 09:11:54 -04:00
James Bardin 3001f0c1b9 Fix test that relied on empty Old diff 2017-03-20 17:44:38 -04:00
James Bardin 970e7c1923 Add a failing test for missing keys in diff
ignore_changes is causing changes in other flatmapped sets to be
filtered out incorrectly.

This required fixing the testDiffFn to create diffs which include the
old value, breaking one other test.
2017-03-20 17:44:37 -04:00
Benjamin Boudreau 073fa873ac Fix receive typo (#12881) 2017-03-20 13:15:27 -04:00
Mitchell Hashimoto 1d1dc7cf30 release: clean up after v0.9.1 2017-03-17 22:54:23 +00:00
Mitchell Hashimoto 7c25ef851b
v0.9.1 2017-03-17 22:48:44 +00:00
Mitchell Hashimoto e8b3062629
terraform: unknown value for variables not set
Fixes #12836

Realistically, these should be caught during validation anyways. In this
case, this was causing 12386 because refresh with a data source will
attempt to use module variables. I don't see any clear logic to prune
those module variables or not add them so its easier to return unknown
to cause the data to be computed and not run.
2017-03-17 15:33:33 -07:00
James Bardin 9e8ddaed47 Don't interpolate multivariables during walkInput
We don't need these expanded for input, and if the multivar's count is a
variable, it may be known but not available during the input walk.
2017-03-16 13:45:07 -04:00
James Bardin fe5f519817 Add failing test for invalid interpolation
Adding the submodule causes the count variable interpolation to fail.
2017-03-16 10:35:18 -04:00
Mitchell Hashimoto 37b3fe1119 release: clean up after v0.9.0 2017-03-15 16:39:53 +00:00
Mitchell Hashimoto 5bd194faa6
v0.9.0 2017-03-15 16:33:13 +00:00
James Bardin 7c9863ccb0 fix another hot lop in tests
Found another test spinlock.
Slow it down to prevent it from blocking the runtime scheduler.
2017-03-15 12:02:28 -04:00
Mitchell Hashimoto 9900bd752a
terraform: string through the context meta 2017-03-13 16:21:09 -07:00
Mitchell Hashimoto 4e1511c77f
terraform: interpolate "terraform.env" 2017-03-13 16:14:27 -07:00
James Bardin ecb1944c31 Merge pull request #12498 from hashicorp/jbardin/test-reset
Add schema.Provider.TestReset to reset StopContext between tests
2017-03-09 08:34:54 -05:00
James Bardin 5238f51dc7 move TestReset mock from terraform to helper
the terraform package doesn't know about TestProvider, so don't put the
hooks in terraform.MockResourceProvider. Wrap the mock in the test where
we need to check the TestProvider functionality.
2017-03-08 17:48:11 -05:00
James Bardin 38d2a8f6ac Fix logic race with Context.watchStop
Always wait for watchStop to return during context.walk.

Context.walk would often complete immediately after sending the close
signal to watchStop, which would in turn call the deferred releaseRun
cancelling the runContext.

Without any synchronization points after the select statement in
watchStop, that goroutine was not guaranteed to be scheduled
immediately, and in fact it often didn't continue until after the
runContext was canceled. This in turn left the select statement with
multiple successful cases, and half the time it would chose to Stop the
providers.

Stopping the providers after the walk of course didn't cause any
immediate failures, but if there was another walk performed, the
provider StopContext would no longer be valid and could cause
cancellation errors in the provider.
2017-03-08 15:11:10 -05:00
James Bardin 0279d11c8a Add TestReset to terraformMockResourceProvider
Have MockResourceProvider implement TestProvider to check that TestReset
is called by the test harness.
2017-03-07 11:39:12 -05:00
James Bardin 3e0af2abbb Sort Validation warning and errors
Make the UI output consistent
2017-03-03 09:46:08 -05:00
Mitchell Hashimoto a2d78b62aa release: clean up after v0.9.0-beta2 2017-03-02 19:42:41 +00:00
Mitchell Hashimoto dbb920ff54
v0.9.0-beta2 2017-03-02 19:38:11 +00:00
James Bardin e5e37b0025 Merge pull request #12340 from hashicorp/jbardin/GH-12253
return 0 from resourceCountMax with a nil Resource
2017-03-02 11:59:32 -05:00
Mitchell Hashimoto 19a594ba3d
terraform: run Gosched in test so other goroutines run
Starting with Go 1.8 betas, we've periodically received SIGQUITs on our
tests in Travis. The stack trace looks like this:

https://gist.github.com/mitchellh/abf09b0980f8ea01269f8d9d6133884d

The tests are timing out! This is a test that hasn't been touched really
in a very long time and has always passed. I've **reproduced this
locally** by setting `GOMAXPROCS=1` and running the test. By yielding
the scheduler in the hot loop, it now passes almost instantly every
time.

Perhaps the test can be written in a different way, but this gets tests
passing and I think will fix our periodic errors.
2017-03-01 23:12:41 -08:00
James Bardin ff445d3c26 fix test that were relying on non-matching configs
A couple interpolation tests were using invalid state that didn't match
the config. These will still pass but were flushed out by an attempt to
make this an error. The repl however still required interpolation
without a config, and tests there will provide a indication if this
behavior changes.
2017-03-01 15:24:52 -05:00
James Bardin 6fa4a591a0 prevent calling Count() on non-existent resources
It turns out that a few use cases depend on not finding a resource
without an error.

The other code paths had sufficient nil checks for this, but there was
one place where we called Count() that needed to be checked. If the
existence of the resource matters, it would be caught at a higher level
and still return an "unknown resource" error to the user.
2017-03-01 15:24:40 -05:00
James Bardin 1e80c402bf add failing test for GH-12253 2017-03-01 11:48:38 -05:00
James Bardin 41ec5b3bd2 missing defaults in sort
Need to properly catch some sort cases around 0-1 indexing.
This can cause output to shift slightly, resulting in an intermittent
test failure.
2017-02-25 16:50:24 -05:00
James Bardin 82914b5e44 Merge pull request #12219 from hashicorp/jbardin/state-mv-sort
fix sorting of module resources during state mv
2017-02-24 09:49:26 -05:00
James Bardin d6eb7c8989 one test was relying on out-of-order output 2017-02-24 09:36:24 -05:00
James Bardin 43c7bd648c fix sorting of module resources during state mv
Module resource were being sorted lexically by name by the state filter.
If there are 10 or more resources, the order won't match the index
order, and resources will have different indexes in their new location.

Sort the FilterResults by index numerically when the names match.

Clean up the module String output for visual inspection by sorting
Resource name parts numerically when they are an integer value.
2017-02-23 18:27:16 -05:00
Mitchell Hashimoto 41d2c145b2
terraform: State.Equal needs to use reflect for rich types
Due to the change to `interface{}` we need to use `reflect.DeepEqual`
here. With the restriction of primitive types this should always be
safe. We'll never get functions, channels, etc.
2017-02-23 14:00:40 -08:00
Mitchell Hashimoto 3342aa580c
terraform: InstanceState.Meta is value type interface{}
This changes the type of values in Meta for InstanceState to
`interface{}`. They were `string` before.

This will allow richer structures to be persisted to this without
flatmapping them (down with flatmap!). The documentation clearly states
that only primitives/collections are allowed here.

The only thing using this was helper/schema for schema versioning.
Appropriate type checking was added to make this change safe.

The timeout work @catsby is doing will use this for a richer structure.
2017-02-23 10:44:05 -08:00
Mitchell Hashimoto c6d0333dc0
flatmap: mark computed list as a computed value in Expand
Fixes #12183

The fix is in flatmap for this but the entire issue is a bit more
complex. Given a schema with a computed set, if you reference it like
this:

    lookup(attr[0], "field")

And "attr" contains a computed set within it, it would panic even though
"field" is available. There were a couple avenues I could've taken to
fix this:

1.) Any complex value containing any unknown value at any point is
entirely unknown.

2.) Only the specific part of the complex value is unknown.

I took route 2 so that the above works without any computed (since
"name" is not computed but something else is). This may actually have an
effect on other parts of Terraform configs, however those similar
configs would've simply crashed previously so it shouldn't break any
pre-existing configs.
2017-02-23 10:03:59 -08:00
Mitchell Hashimoto a49875067d
terraform: extra logging 2017-02-21 20:35:36 -08:00
Mitchell Hashimoto f6ab0bc5c4
terraform: interpolation failures on a destroy provisioner should error 2017-02-17 14:32:32 -08:00
Mitchell Hashimoto a1ec81964b
terraform: destroy ordering needs to handle destroy provisioner edges
This ensures that things aren't destroyed before their values are used.
2017-02-17 14:29:22 -08:00
Mitchell Hashimoto 757217b91f
terraform: destroy resource should depend on destroy-time prov deps 2017-02-17 13:13:44 -08:00
Mitchell Hashimoto ef546517be
terraform: close transform should not include untargeted providers 2017-02-17 09:27:47 -08:00
Mitchell Hashimoto 9062a1893e
terraform: don't include providers if not targeted
Fixes #12009

This is a simple change similar to #10911 where we need to exclude
providers that aren't targeted.
2017-02-17 09:21:29 -08:00
Mitchell Hashimoto 1607c1187d release: clean up after v0.9.0-beta1 2017-02-15 22:39:57 +00:00
Mitchell Hashimoto 4e96da57ee
v0.9.0-beta1 2017-02-15 22:35:37 +00:00
Mitchell Hashimoto bbae22007d Merge pull request #11921 from hashicorp/b-untarget-output
terraform: outputs should not be included if not targeted
2017-02-15 10:47:14 -08:00
Mitchell Hashimoto c36b6c42ba
terraform: test case for #10982 (passes) 2017-02-13 13:06:22 -08:00
Mitchell Hashimoto 4d6085b46a
terraform: outputs should not be included if not targeted
Fixes #10911

Outputs that aren't targeted shouldn't be included in the graph.

This requires passing targets to the apply graph. This is unfortunate
but long term should be removable since I'd like to move output changes
to the diff as well.
2017-02-13 12:52:45 -08:00
James Bardin 92cea2478d Add test for nil *os.File in ReadState 2017-02-09 16:06:07 -05:00
James Bardin 0c1b138719 Add state locking during backend init
During backend initialization, especially during a migration, there is a
chance that an existing state could be overwritten.

Attempt to get a locks when writing the new state. It would be nice to
always have a lock when reading the states, but the recursive structure
of the Meta.Backend config functions makes that quite complex.
2017-02-09 15:47:27 -05:00
Mitchell Hashimoto 8ed9bdfedc
terraform: node referenceable name from state shuldn't contain path
Fixes #11749

I'm **really** surprised this didn't come up earlier.

When only the state is available for a node, the advertised
referenceable name (the name used for dependency connections) included
the module path. This module path is automatically prepended to the
name. This means that probably every non-root resource for state-only
operations (destroys) didn't order properly.

This fixes that by omitting the path properly.

Multiple tests added to verify both graph correctness as well as a
higher level context test.

Will backport to 0.8.x
2017-02-07 20:14:38 -08:00
Mitchell Hashimoto af61d566c2
terraform: passing test for destroy edge for module only
Just adding passing tests as a sanity check for a bug.
2017-02-07 19:12:03 -08:00
Mitchell Hashimoto ac3d67e40f
terraform: remove old logging line 2017-02-07 16:28:01 -08:00
Mitchell Hashimoto 7192c1a9a1 Merge pull request #11732 from hashicorp/b-diff-map-removal
terraform: ignore RequiresNew for collection removal in diff.Same
2017-02-07 12:58:15 -08:00
Mitchell Hashimoto e7aa1fd48d Merge pull request #11733 from hashicorp/b-disable-shadow
terraform: default shadow to false
2017-02-07 12:57:46 -08:00
Mitchell Hashimoto ac934cf003
terraform: add one more forgotten ordering assertion 2017-02-07 12:01:27 -08:00
Mitchell Hashimoto a765740827
terraform: CBD destroy nodes should not advertise themselves as normal 2017-02-07 11:49:50 -08:00
Mitchell Hashimoto 44233441c2
terraform: CBD edge should ignore "index" 2017-02-07 10:53:12 -08:00
Mitchell Hashimoto 864c79396d
terraform: default shadow to false
To avoid chasing down issues like #11635 I'm proposing we disable the
shadow graph for end users now that we have merged in all the new
graphs. I've kept it around and default-on for tests so that we can use
it to test new features as we build them. I think it'll still have value
going forward but I don't want to hold us for making it work 100% with
all of Terraform at all times.

I propose backporting this to 0-8-stable, too.
2017-02-06 18:02:32 -08:00
Mitchell Hashimoto fe32f7b189
terraform: ignore RequiresNew for collection removal in diff.Same
Fixes #11349

I tracked this bug back to the early 0.7 days so this has been around a
really long time. I wanted to confirm that this wasn't introduced by any
new graph changes and it appears to predate all of that. I couldn't find
a single 0.7.x release where this worked, and I didn't want to go back
to 0.6.x since it was pre-vendoring.

The test case shows the logic the best, but the basic idea is: for
collections that go to zero elements, the "RequiresNew" sameness check
should be ignored, since the new diff can choose to not have that at all
in the diff.
2017-02-06 17:46:48 -08:00
Mitchell Hashimoto ebb129f051
terraform: data source on refresh should just delete from state
This was caught by an acceptance test. We've now added a unit test. When
refreshing, an orphan (no config) data source should just be deleted.
2017-02-03 20:58:03 +01:00
Mitchell Hashimoto 1777f53a4b Merge pull request #11660 from hashicorp/f-graph-deps
terraform: remove ConnectDependents and related interfaces
2017-02-03 14:52:07 +01:00
Mitchell Hashimoto 755cef98b0
terraform: remove ConnectDependents and related interfaces 2017-02-03 14:25:54 +01:00
James Bardin 9acb86a182 Merge pull request #11187 from hashicorp/jbardin/state-locking
State Locking initial implementations
2017-02-01 14:35:55 -05:00
Mitchell Hashimoto 068b2b2dec
terraform: add Meta field to diffs
This adds a Meta field (similar to InstanceState.Meta) to InstanceDiff.

This allows providers to store arbitrary k/v data as part of a diff and
have it persist through to the Apply. This will be used by helper/schema
for timeout storage being done by @catsby.

The type here is `map[string]interface{}`. A couple notes:

  * **Not using `string`**: The Meta field of InstanceState is a string
    value. We've learned that forcing things to strings is bad. Let's
    just allow types.

  * **Primitives only**: Even though it is type `interface{}`, it must
    be able to cleanly pass the go-plugin RPC barrier as well as be
    encoded to a file as Gob. Given these constraints, the value must
    only comprise of primitive types and collections. No structs,
    functions, channels, etc.
2017-01-31 11:50:37 -08:00
James Bardin f20485550a Check for no state from the io.Reader
Read state would assume that having a reader meant there should be a
valid state. Check for an empty file and return ErrNoState to
differentiate a bad file from an empty one.
2017-01-30 17:16:57 -05:00
Mitchell Hashimoto 61881d2795 Merge pull request #10934 from hashicorp/f-provisioner-stop
core: stoppable provisioners, helper/schema for provisioners
2017-01-30 12:53:15 -08:00
Mitchell Hashimoto 3e771a674c
terraform: acquire stopCh outside goroutine to ensure in lock 2017-01-30 08:49:07 -08:00
Mitchell Hashimoto 195d34424e Merge pull request #11482 from hashicorp/f-computed-count
core: allow non-computed data source values in "count"
2017-01-30 08:44:27 -08:00
Mitchell Hashimoto 00232f0994
terraform: acquireRun during test to avoid special case logic 2017-01-30 08:41:38 -08:00
Mitchell Hashimoto 5b42781117
terraform: defer unlock of lock in Stop to enure it always unlocks 2017-01-30 08:35:10 -08:00
Mitchell Hashimoto 9183be4c83
update master version to 0.9.0-dev 2017-01-29 18:46:18 -08:00
Mitchell Hashimoto cf46e1c3e0
terraform: don't validate computed values in validate
This disables the computed value check for `count` during the validation
pass. This enables partial support for #3888 or #1497: as long as the
value is non-computed during the plan, complex values will work in
counts.

**Notably, this allows data source values to be present in counts!**

The "count" value can be disabled during validation safely because we
can treat it as if any field that uses `count.index` is computed for
validation. We then validate a single instance (as if `count = 1`) just
to make sure all required fields are set.
2017-01-27 21:15:43 -08:00
Mitchell Hashimoto 0ba3fcdc63
terraform: test static var being passed into grandchild for count 2017-01-27 20:38:07 -08:00
Mitchell Hashimoto 2162d6cf3d
terraform: test a basic static var count passed into a module 2017-01-27 20:32:55 -08:00
Mitchell Hashimoto dd6d025dbb
terraform: commmit generated file 2017-01-27 20:31:29 -08:00
Mitchell Hashimoto 2beb62c92b
terraform: remove flatten, forever 2017-01-26 21:03:27 -08:00
Mitchell Hashimoto 6d731b3b46
terraform: new provisioner node 2017-01-26 21:02:55 -08:00