Terraform Refactoring State File

https://www.terraform.io/docs/cli/commands/state/mv.html
On windows :

terraform state mv nsxt_policy_security_policy.policy1 nsxt_policy_security_policy.policies[\“policy1\“]
It move resources from a construct like this

locals {
  policy1= {
      rule1 = {
        source = ["src1","src2"]
      }
  }
  policy2 = {
      rule1 = {
        source = ["src3","src4"]
      }
  }
}

To a structure like this

locals {
  policies = {
    policy1 = {
      rule1 = {
        source = ["src1","src2"]
      }
    }
    policy2 = {
      rule2 = {
        source = ["src3","src4"]
      }
    }
  }
}

The main moving from

resource "nsxt_policy_security_policy" "policy1"{
  display_name = "policy1"
  category     = "Environment"
  dynamic "rule" {
    for_each = local.policy1
    content {
      source_groups = rule.value["sources"]
    }
  }
}
resource "nsxt_policy_security_policy" "policy2"{
  display_name = "policy2"
  category     = "Environment"
  dynamic "rule" {
    for_each = local.policy2
    content {
      source_groups = rule.value["sources"]
    }
  }
}

to

resource "nsxt_policy_security_policy" "policies" {
for_each = local.policies
  display_name = each.key
  category     = "Environment"
  dynamic "rule" {
    for_each = each.value
    content {
      source_groups = rule.value["sources"]
    }
  }
}

The terraform state moving fromfrom 2 resources to 1 resource with 2 instances
From

{
  "type": "nsxt_policy_security_policy",
  "name": "policy1"
  "instances" : [
    {
      ...
    }
  ]
},
{
  "type": "nsxt_policy_security_policy",
  "name": "policy2"
  "instances" : [
    {
      ...
    }
  ]
}

To

{
  "type": "nsxt_policy_security_policy",
  "name": "policies"
  "instances" : [
    {
      "index_key": "policy1"
    },
    {
      "index_key": "policy2"
    }
  ]
}

Related