Skip to content

Commit

Permalink
provider: filter on tags and tag
Browse files Browse the repository at this point in the history
Some resources doesn't have tags attribute but tag.
Tag can't be verified with the same logic.

Implement the Tag attribut check logic

linked to #223
  • Loading branch information
talset committed Aug 24, 2021
1 parent c537be3 commit 7572c77
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
13 changes: 11 additions & 2 deletions provider/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,18 @@ func (r *resource) Read(f *filter.Filter) error {
// so we have to do it manually
// it's not all of them though
for _, t := range f.Tags {
if v, ok := r.data.GetOk(fmt.Sprintf("%s.%s", r.Provider().TagKey(), t.Name)); !ok || v.(string) != t.Value {
return errors.WithStack(errcode.ErrProviderResourceDoNotMatchTag)
// Default match key
if v, ok := r.data.GetOk(fmt.Sprintf("%s.%s", r.Provider().TagKey(), t.Name)); ok && v.(string) == t.Value {
continue
}

// Check if the filter tag match any other tags found
// https://github.com/cycloidio/terracognita/issues/223
if v, ok := tag.GetOtherTags(r.Provider().String(), r.data, t); ok && v == t.Value {
continue
}

return errors.WithStack(errcode.ErrProviderResourceDoNotMatchTag)
}

// Filter out autogenerated resources from AWS
Expand Down
30 changes: 30 additions & 0 deletions tag/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,33 @@ func isValidResourceName(name string) bool {
func forceResourceName(name string) string {
return invalidNameRegexp.ReplaceAllString(name, "_")
}

func GetOtherTags(provider string, srd *schema.ResourceData, filterTag Tag) (string, bool) {
// keep the same logic as r.data.GetOk
otherTagsMap := make(map[string]string)

// Special Tag attribute
if provider == "aws" {
// Some resource like aws_autoscaling_group do not have tags map but tag schema.Set
// https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/autoscaling_group#tag
v, _ := srd.GetOk("tag")
// Get Set to List tag
tag, okset := v.(*schema.Set)
if okset {
// convert list to map
for _, i := range tag.List() {
// Cast to get tag key and value
m, okmap := i.(map[string]interface{})
if okmap {
otherTagsMap[m["key"].(string)] = m["value"].(string)
}
}
}
}

if val, ok := otherTagsMap[filterTag.Name]; ok {
return val, true
}

return "", false
}

0 comments on commit 7572c77

Please sign in to comment.