Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(consul): Adds a data source to retrieve kv pairs under a specified path #10353

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
66 changes: 66 additions & 0 deletions builtin/providers/consul/data_source_consul_key_prefix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package consul

import (
consulapi "github.com/hashicorp/consul/api"
"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceConsulKeyPrefix() *schema.Resource {
return &schema.Resource{
Read: dataSourceConsulKeyPrefixRead,

Schema: map[string]*schema.Schema{
"datacenter": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},

"token": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},

"path_prefix": &schema.Schema{
Type: schema.TypeString,
Required: true,
},

"var": &schema.Schema{
Type: schema.TypeMap,
Computed: true,
},
},
}
}

func dataSourceConsulKeyPrefixRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*consulapi.Client)
kv := client.KV()
token := d.Get("token").(string)
dc, err := getDC(d, client)
if err != nil {
return err
}

keyClient := newKeyClient(kv, dc, token)

pathPrefix := d.Get("path_prefix").(string)
vars, err := keyClient.GetUnderPrefix(pathPrefix)
if err != nil {
return err
}

if err := d.Set("var", vars); err != nil {
return err
}

// Store the datacenter on this resource, which can be helpful for reference
// in case it was read from the provider
d.Set("datacenter", dc)

d.SetId("-")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there is no Id, then we should use something like:

d.SetId(time.Now().UTC().String())


return nil
}
114 changes: 114 additions & 0 deletions builtin/providers/consul/data_source_consul_key_prefix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package consul

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccDataConsulKeyPrefix_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccDataConsulKeyPrefixConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckConsulKeyPrefixExists("data.consul_key_prefix.read", "cheese", true),
testAccCheckConsulKeyPrefixExists("data.consul_key_prefix.read", "bread", true),
testAccCheckConsulKeyPrefixValue("data.consul_key_prefix.read", "cheese", "chevre"),
testAccCheckConsulKeyPrefixValue("data.consul_key_prefix.read", "bread", "baguette"),
),
},
resource.TestStep{
Config: testAccDataConsulKeyPrefixConfig_Update,
Check: resource.ComposeTestCheckFunc(
testAccCheckConsulKeyPrefixExists("data.consul_key_prefix.read", "cheese", false),
testAccCheckConsulKeyPrefixExists("data.consul_key_prefix.read", "bread", true),
testAccCheckConsulKeyPrefixExists("data.consul_key_prefix.read", "meat", true),
testAccCheckConsulKeyPrefixValue("data.consul_key_prefix.read", "bread", "batard"),
testAccCheckConsulKeyPrefixValue("data.consul_key_prefix.read", "meat", "ham"),
),
},
},
})
}

const testAccDataConsulKeyPrefixConfig = `
resource "consul_key_prefix" "app" {
datacenter = "dc1"

path_prefix = "prefix_test/"

subkeys = {
cheese = "chevre"
bread = "baguette"
}
}

data "consul_key_prefix" "read" {
datacenter = "${consul_key_prefix.app.datacenter}"
depends_on = ["consul_key_prefix.app"]

path_prefix = "prefix_test/"
}
`

const testAccDataConsulKeyPrefixConfig_Update = `
resource "consul_key_prefix" "app" {
datacenter = "dc1"

path_prefix = "prefix_test/"

subkeys = {
bread = "batard"
meat = "ham"
}
}

data "consul_key_prefix" "read" {
datacenter = "${consul_key_prefix.app.datacenter}"
depends_on = ["consul_key_prefix.app"]

path_prefix = "prefix_test/"
}
`

func testAccCheckConsulKeyPrefixValue(n string, attr string, val string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rn, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Data source not found")
}
out, ok := rn.Primary.Attributes["var."+attr]
if !ok {
return fmt.Errorf("Attribute '%s' not found: %#v", attr, rn.Primary.Attributes)
}
if val != "<any>" && out != val {
return fmt.Errorf("Attribute '%s' value '%s' != '%s'", attr, out, val)
}
if val == "<any>" && out == "" {
return fmt.Errorf("Attribute '%s' value '%s'", attr, out)
}
return nil
}
}

func testAccCheckConsulKeyPrefixExists(n string, attr string, shouldExists bool) resource.TestCheckFunc {
return func(s *terraform.State) error {
rn, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Data source not found")
}
_, ok = rn.Primary.Attributes["var."+attr]
if shouldExists && !ok {
return fmt.Errorf("Attribute '%s' not found: %#v", attr, rn.Primary.Attributes)
}
if !shouldExists && ok {
return fmt.Errorf("Attribute '%s' still present: %#v", attr, rn.Primary.Attributes)
}
return nil
}
}
3 changes: 2 additions & 1 deletion builtin/providers/consul/resource_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ func Provider() terraform.ResourceProvider {
},

DataSourcesMap: map[string]*schema.Resource{
"consul_keys": dataSourceConsulKeys(),
"consul_keys": dataSourceConsulKeys(),
"consul_key_prefix": dataSourceConsulKeyPrefix(),
},

ResourcesMap: map[string]*schema.Resource{
Expand Down
51 changes: 51 additions & 0 deletions website/source/docs/providers/consul/d/key_prefix.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
layout: "consul"
page_title: "Consul: consul_key_prefix"
sidebar_current: "docs-consul-data-source-key-prefix"
description: |-
Reads values from the Consul key/value store.
---

# consul\_key\_prefix

The `consul_key_prefix` resource reads values from the Consul key/value store.
This is a powerful way dynamically set values in templates.

## Example Usage

```
data "consul_key_prefix" "app" {
datacenter = "nyc1"
token = "abcd"

# Read the AMI from Consul
path_prefix = "service/app/"
}

# Start our instance with the dynamic ami value
resource "aws_instance" "app" {
ami = "${data.consul_key_prefix.app.var.ami}"
...
}
```

## Argument Reference

The following arguments are supported:

* `datacenter` - (Optional) The datacenter to use. This overrides the
datacenter in the provider setup and the agent's default datacenter.

* `token` - (Optional) The ACL token to use. This overrides the
token that the agent provides by default.

* `path_prefix` - (Required) Specifies the common prefix shared by all keys
to be retrieved in Consul.

## Attributes Reference

The following attributes are exported:

* `datacenter` - The datacenter the keys are being read from to.
* `var.<name>` - For each name given, the corresponding attribute
has the value of the key.