Alex Kuzmin
Alex Kuzmin

Reputation: 111

How can I test terraform import in acceptance tests?

I found this article about testing tf import in acceptance tests:

func TestAccExampleThing_basic(t *testing.T) {
  /* ... potentially existing acceptance testing logic ... */

  resource.ParallelTest(t, resource.TestCase{
    /* ... existing TestCase functions ... */
    Steps: []resource.TestStep{
      /* ... existing TestStep ... */
      {
        ResourceName:      "example_thing.test",
        ImportState:       true,
        ImportStateVerify: true,
      },
    },
  })
}

But it's still very confusing to me though. Let's say existing TestCase function will initialize some small config & run tf plan & tf apply so tf state file won't be empty and then what exactly will happen during step (test case) #2? The way I think about it there should be an error or something if we try to import the resource that's already in tf state locally (after step#1), right?

Or what's even more confusing, this combined test where steps #2, and #4 are both imports in terraform-provider-aws (as far as I can see step#3 updated one of the attributes in our state that was created in step#1 but what exactly step#2 and step#4 does)?

Upvotes: 1

Views: 1425

Answers (1)

Artem Yarmoliuk
Artem Yarmoliuk

Reputation: 336

Your setup for testing import is correct. Adding steps with ImportState and ImportStateVerify should be enough.

Testing import is implemented in terraform-provider-sdk testStepNewImportState function. How it works:

  1. Previous step applies terraform config using testcase workdir and state.
  2. If next step sets ImportState to true, use ResourceName to grab resource id from testcase state (or use ImportStateIdFunc or ImportStateId if they are set for this step).
  3. Create empty workdir, initialize new empty state, and import resource given resource name and id from previous step. There would be no conflicts since this is a separate empty state.
  4. If ImportStateVerify is true, compare resource states from previous step and import step, they should be identical.
  5. If ImportStateCheck function is set, use this function for custom state validation. This can be used in case if direct state comparison will be not valid.
  6. Discard temporary workdir.

Upvotes: 6

Related Questions