From b8a9261d0516b3f7a2642cfd9951c7050c892d8f Mon Sep 17 00:00:00 2001 From: Adam Mckaig Date: Tue, 15 Dec 2015 00:01:17 -0500 Subject: [PATCH] Add group by AWS tags --- parser_test.go | 12 +++++++++--- resource.go | 31 ++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/parser_test.go b/parser_test.go index f9b7302..68e8203 100644 --- a/parser_test.go +++ b/parser_test.go @@ -26,7 +26,9 @@ const exampleStateFile = ` "id": "i-aaaaaaaa", "attributes": { "id": "i-aaaaaaaa", - "private_ip": "10.0.0.1" + "private_ip": "10.0.0.1", + "tags.#": "1", + "tags.Role": "Web" } } }, @@ -139,14 +141,18 @@ const expectedListOutput = ` "digitalocean_droplet": ["192.168.0.3"], "cloudstack_instance": ["10.2.1.5"], "vsphere_virtual_machine": ["10.20.30.40"], - "openstack_compute_instance_v2": ["10.120.0.226"] + "openstack_compute_instance_v2": ["10.120.0.226"], + + "role_web": ["10.0.0.1"] } ` const expectedHostOneOutput = ` { "id":"i-aaaaaaaa", - "private_ip":"10.0.0.1" + "private_ip":"10.0.0.1", + "tags.#": "1", + "tags.Role": "Web" } ` diff --git a/resource.go b/resource.go index 77c62a1..9086847 100644 --- a/resource.go +++ b/resource.go @@ -4,6 +4,7 @@ import ( "fmt" "regexp" "strconv" + "strings" ) // keyNames contains the names of the keys to check for in each resource in the @@ -81,11 +82,39 @@ func (r Resource) IsSupported() bool { // Groups returns the list of Ansible groups which this resource should be // included in. func (r Resource) Groups() []string { - return []string{ + groups := []string{ r.baseName, r.NameWithCounter(), r.resourceType, } + + for k, v := range r.Tags() { + g := fmt.Sprintf("%s_%s", k, v) + groups = append(groups, g) + } + + return groups +} + +// Tags returns a map of arbitrary key/value pairs explicitly associated with +// the resource. Different providers have different mechanisms for attaching +// these. +func (r Resource) Tags() map[string]string { + t := map[string]string{} + + switch r.resourceType { + case "aws_instance": + for k, v := range r.Attributes() { + parts := strings.SplitN(k, ".", 2) + if len(parts) == 2 && parts[0] == "tags" && parts[1] != "#" { + kk := strings.ToLower(parts[1]) + vv := strings.ToLower(v) + t[kk] = vv + } + } + } + + return t } // Attributes returns a map containing everything we know about this resource.