'Are state migrations in Terraform supported for both resources and data sources?

I found Resources - State Migration tutorial that describes the process of implementing a state migration for resources and it worked perfectly for me when I implemented it for foo resource.

However when I tried to implement the same thing for foo data source where I literally reused the same upgrader methods (since the migration is the same for both resource and data source):

SchemaVersion: 1,
StateUpgraders: []schema.StateUpgrader{
    {
        Type:    resourceExampleInstanceResourceV0().CoreConfigSchema().ImpliedType(),
        Upgrade: resourceExampleInstanceStateUpgradeV0,
        Version: 0,
    },
},

I'm running into a .bar: missing expected [ error when trying to run terraform plan for an existing TF state with a data source (version 0) and updated main.tf that contain an updated definition of foo data source that matches its updated schema.

Here's

func resourceExampleInstanceStateUpgradeV0(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) {
    barString := rawState["bar"].(string)
    rawState["bar"] = []interface{}{map[string]interface{}{
        "name": barString,
    }}
    return rawState, nil
}

I might be able to come up with a fully reproducible example that will include more code but I figured it might be useful to ask about it more generally since the tutorial named "Resources - State Migration" and not "Data Sources - State Migration".

On the other hand,

  "resources": [
    {
      "mode": "data",
      "type": "bar",
      "name": "example",
      ...
      "instances": [
        {
          "schema_version": 0,

contain schema_version still so it might be supported.



Solution 1:[1]

Data resources do not require state migrations. They are read-only resources, so the action of reading them updates the state to the latest version. For this reason, Terraform does not call the UpgradeResourceState method for data sources.

I’m not sure what is going on the legacy SDK when using StateUpgraders on a data source, the error looks like it might be from json decoding? That may be something they can prevent in the schema validation.

The reference

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Kuzminov