Skip to content

Commit

Permalink
Terraform 0.12+ index can be string or number
Browse files Browse the repository at this point in the history
In the case of when mixing resources into the statefile in terraform, it's now
possible to have indexes that are not always int. In the example below using the
new 0.12 syntax `foreach` will result in the index being mapped to the
`each.key` name instead of the integer indexes.

```
variable "test" {
  default = {"testa" = "1.1.1.1", "testb" = "2.2.2.2"}
}

resource "aws_route53_record" "this" {
  for_each = var.test
  zone_id = "abc"
  name    = "${each.key}.tv."
  type    = "A"
  ttl     = "300"
  records = [each.value]
}
```
  • Loading branch information
Bao Nguyen authored and Anna Tikhonova committed Feb 5, 2020
1 parent a408e89 commit 41cd001
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
14 changes: 12 additions & 2 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ type moduleStateTerraform0dot12 struct {
}
type resourceStateTerraform0dot12 struct {
Address string `json:"address"`
Index *int `json:"index"` // only set by Terraform for counted resources
Index *interface{} `json:"index"` // only set by Terraform for counted resources
Name string `json:"name"`
RawValues map[string]interface{} `json:"values"`
Type string `json:"type"`
Expand Down Expand Up @@ -324,7 +324,17 @@ func (s *stateTerraform0dot12) resources() []*Resource {
}
resourceKeyName := rs.Type + "." + modulePrefix + rs.Name
if rs.Index != nil {
resourceKeyName += "." + strconv.Itoa(*rs.Index)
i := *rs.Index
switch v := i.(type) {
case int:
resourceKeyName += "." + strconv.Itoa(v)
case float64:
resourceKeyName += "." + strconv.Itoa(int(v))
case string:
resourceKeyName += "." + v
default:
fmt.Fprintf(os.Stderr, "Warning: unknown index type %v\n", v)
}
}

// Terraform stores resources in a name->map map, but we need the name to
Expand Down
29 changes: 29 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,35 @@ const exampleStateFileTerraform0dot12 = `
}
}
},
{
"address": "aws_route53_record.this",
"mode": "managed",
"type": "aws_route53_record",
"name": "this",
"index": "testb",
"provider_name": "aws",
"schema_version": 2,
"values": {
"alias": [],
"allow_overwrite": null,
"failover_routing_policy": [],
"fqdn": "testb.tv",
"geolocation_routing_policy": [],
"health_check_id": null,
"id": "abc.tv._A",
"latency_routing_policy": [],
"multivalue_answer_routing_policy": null,
"name": "testb.tv",
"records": [
"2.2.2.2"
],
"set_identifier": null,
"ttl": 300,
"type": "A",
"weighted_routing_policy": [],
"zone_id": "abc"
}
},
{
"address": "vsphere_tag.bar",
"mode": "managed",
Expand Down

0 comments on commit 41cd001

Please sign in to comment.