Terraform 中的状态迁移是否同时支持资源和数据源?

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

我找到了 Resources - State Migration 教程,它描述了实现资源状态迁移的过程,当我为 foo 实现它时,它对我来说非常有用资源.

然而,当我试图为 foo 数据源 实现同样的事情时,我实际上是 重用相同的升级方法(因为资源和数据源的迁移相同):

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

我 运行在尝试 运行 terraform plan 具有数据源(版本 0)的现有 TF 状态并更新时遇到 .bar: missing expected [ 错误main.tf 包含 foo 数据源的更新定义,与其更新的架构相匹配。

这是

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
}

我可能能够想出一个完全可重现的示例,其中将包含更多代码,但我认为更笼统地询问它可能会有用,因为教程名为“资源 - 状态迁移”而不是“数据源” - 状态迁移。

另一方面,

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

仍然包含 schema_version,因此可能会得到支持。

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