Skip to content

Commit

Permalink
Merge pull request #36 from fujiwara/fix/mixed-each-resouces
Browse files Browse the repository at this point in the history
multiple resources may have same name (for_each or not).
  • Loading branch information
fujiwara committed Dec 14, 2021
2 parents 5addbd9 + ce034e6 commit bf71b1a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
31 changes: 22 additions & 9 deletions tfstate/lookup.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,29 @@ func ReadURL(loc string) (*TFState, error) {
// Lookup lookups attributes of the specified key in tfstate
func (s *TFState) Lookup(key string) (*Object, error) {
s.once.Do(s.scan)
var found instance
var foundName string
for name, ins := range s.scanned {
if strings.HasPrefix(key, name) {
query := strings.TrimPrefix(key, name)
if strings.HasPrefix(query, "[") { // e.g. output.foo[0]
query = "." + query
}
if strings.HasPrefix(query, ".") || query == "" {
attr := &Object{noneNil(ins.data, ins.Attributes, ins.AttributesFlat)}
return attr.Query(quoteJQQuery(query))
// logest match
if len(foundName) < len(name) {
found = ins
foundName = name
}
}
}
if foundName == "" {
return &Object{}, nil
}

query := strings.TrimPrefix(key, foundName)
if strings.HasPrefix(query, "[") { // e.g. output.foo[0]
query = "." + query
}
if strings.HasPrefix(query, ".") || query == "" {
attr := &Object{noneNil(found.data, found.Attributes, found.AttributesFlat)}
return attr.Query(quoteJQQuery(query))
}

return &Object{}, nil
}
Expand Down Expand Up @@ -289,10 +300,12 @@ func (s *TFState) scan() {
} else if len(r.Instances) > 0 && r.Instances.hasIndexKey() {
for _, i := range r.Instances {
ins := i
var key string
if len(ins.IndexKey) == 0 {
continue // may be a garbage...
key = module + fmt.Sprintf("%s%s.%s", prefix, r.Type, r.Name)
} else {
key = module + fmt.Sprintf("%s%s.%s[%s]", prefix, r.Type, r.Name, string(i.IndexKey))
}
key := module + fmt.Sprintf("%s%s.%s[%s]", prefix, r.Type, r.Name, string(i.IndexKey))
s.scanned[key] = ins
}
} else {
Expand Down
7 changes: 6 additions & 1 deletion tfstate/lookup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ var TestNames = []string{
`output.foo`,
`data.aws_caller_identity.current`,
`aws_acm_certificate.main`,
`module.logs.aws_cloudwatch_log_group.main`,
`module.logs.aws_cloudwatch_log_group.main["app"]`,
`module.logs.aws_cloudwatch_log_group.main["web"]`,
`aws_iam_role_policy_attachment.ec2[0]`,
Expand Down Expand Up @@ -97,7 +98,11 @@ var TestSuitesOK = []TestSuite{
Result: nil,
},
{
Key: `module.logs.aws_cloudwatch_log_group.main`,
Key: `module.logs.aws_cloudwatch_log_group.main.name`,
Result: "/main/vanish",
},
{
Key: `module.logs.aws_cloudwatch_log_group.ma`,
Result: nil,
},
{
Expand Down

0 comments on commit bf71b1a

Please sign in to comment.