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

Make generic secrets importable. #17

Merged
merged 3 commits into from
Nov 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions vault/import_generic_secret_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package vault

import (
"testing"

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

func TestAccGenericSecret_importBasic(t *testing.T) {
path := acctest.RandomWithPrefix("secret/test-")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testProviders,
Steps: []resource.TestStep{
{
Config: testResourceGenericSecret_initialConfig(path),
Check: testResourceGenericSecret_initialCheck(path),
},
{
ResourceName: "vault_generic_secret.test",
ImportState: true,
ImportStateVerify: true,
},
},
})
}
39 changes: 30 additions & 9 deletions vault/resource_generic_secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,16 @@ import (

func genericSecretResource() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,

Create: genericSecretResourceWrite,
Update: genericSecretResourceWrite,
Delete: genericSecretResourceDelete,
Read: genericSecretResourceRead,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
MigrateState: resourceGenericSecretMigrateState,

Schema: map[string]*schema.Schema{
"path": &schema.Schema{
Expand All @@ -34,16 +40,23 @@ func genericSecretResource() *schema.Resource {
// We rebuild the attached JSON string to a simple singleline
// string. This makes terraform not want to change when an extra
// space is included in the JSON string. It is also necesarry
// when allow_read is true for comparing values.
// when disable_read is false for comparing values.
StateFunc: NormalizeDataJSON,
ValidateFunc: ValidateDataJSON,
},

"allow_read": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Description: "Attempt to read the token from Vault if true; if false, drift won't be detected.",
Deprecated: "Please use disable_read instead.",
},

"disable_read": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "True if the provided token is allowed to read the secret from vault",
Description: "Don't attempt to read the token from Vault if true; drift won't be detected.",
},
},
}
Expand Down Expand Up @@ -99,7 +112,7 @@ func genericSecretResourceWrite(d *schema.ResourceData, meta interface{}) error

d.SetId(path)

return nil
return genericSecretResourceRead(d, meta)
}

func genericSecretResourceDelete(d *schema.ResourceData, meta interface{}) error {
Expand All @@ -117,10 +130,16 @@ func genericSecretResourceDelete(d *schema.ResourceData, meta interface{}) error
}

func genericSecretResourceRead(d *schema.ResourceData, meta interface{}) error {
allowed_to_read := d.Get("allow_read").(bool)
path := d.Get("path").(string)
shouldRead := !d.Get("disable_read").(bool)
if !shouldRead {
// if disable_read is set to false or unset (we can't know which)
// and allow_read is set to true, go with allow_read.
shouldRead = d.Get("allow_read").(bool)
}

path := d.Id()

if allowed_to_read {
if shouldRead {
client := meta.(*api.Client)

log.Printf("[DEBUG] Reading %s from Vault", path)
Expand All @@ -129,15 +148,17 @@ func genericSecretResourceRead(d *schema.ResourceData, meta interface{}) error {
return fmt.Errorf("error reading from Vault: %s", err)
}

log.Printf("[DEBUG] secret: %#v", secret)

jsonDataBytes, err := json.Marshal(secret.Data)
if err != nil {
return fmt.Errorf("Error marshaling JSON for %q: %s", path, err)
}
d.Set("data_json", string(jsonDataBytes))
d.Set("path", path)
} else {
log.Printf("[WARN] vault_generic_secret does not automatically refresh if allow_read is set to false")
log.Printf("[WARN] vault_generic_secret does not refresh when disable_read is set to true")
}

d.SetId(path)
d.Set("disable_read", !shouldRead)
return nil
}
36 changes: 36 additions & 0 deletions vault/resource_generic_secret_migrate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package vault

import (
"fmt"
"log"

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

func resourceGenericSecretMigrateState(v int, s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
if s.Empty() {
log.Println("[DEBUG] Empty InstanceState; nothing to migrate.")
return s, nil
}

switch v {
case 0:
log.Println("[INFO] Found Vault Generic Secret state v0; migrating to v1")
s, err := migrateGenericSecretStateV0toV1(s)
return s, err
default:
return s, fmt.Errorf("Unexpected schema version: %d", v)
}
}

func migrateGenericSecretStateV0toV1(s *terraform.InstanceState) (*terraform.InstanceState, error) {
log.Printf("[DEBUG] Attributes before migration: %#v", s.Attributes)

disabledRead := s.Attributes["allow_read"] != "true"
if disabledRead {
s.Attributes["disable_read"] = "true"
}

log.Printf("[DEBUG] Attributes after migration: %#v:", s.Attributes)
return s, nil
}
70 changes: 70 additions & 0 deletions vault/resource_generic_secret_migrate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package vault

import (
"testing"

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

func TestGenericSecretMigrateState(t *testing.T) {
cases := map[string]struct {
StateVersion int
Attributes map[string]string
Expected map[string]string
}{
"unset allow_read to disable_read": {
StateVersion: 0,
Attributes: map[string]string{
"data_json": `{"hello": "world"}`,
"path": "secret/test-123",
},
Expected: map[string]string{
"data_json": `{"hello": "world"}`,
"path": "secret/test-123",
},
},
"allow_read false to disable_read": {
StateVersion: 0,
Attributes: map[string]string{
"data_json": `{"hello": "world"}`,
"path": "secret/test-123",
"allow_read": "false",
},
Expected: map[string]string{
"data_json": `{"hello": "world"}`,
"path": "secret/test-123",
"disable_read": "true",
},
},
"allow_read true to disable_read": {
StateVersion: 0,
Attributes: map[string]string{
"data_json": `{"hello": "world"}`,
"path": "secret/test-123",
"allow_read": "true",
},
Expected: map[string]string{
"data_json": `{"hello": "world"}`,
"path": "secret/test-123",
},
},
}

for tn, tc := range cases {
is, err := resourceGenericSecretMigrateState(
tc.StateVersion, &terraform.InstanceState{
ID: tc.Attributes["path"],
Attributes: tc.Attributes,
}, nil)

if err != nil {
t.Fatalf("Unexpected error for migration %q: %+v", tn, err)
}

for k, v := range tc.Expected {
if is.Attributes[k] != v {
t.Fatalf("Expected %q to be %v for %q, got %v", k, v, tn, is.Attributes[k])
}
}
}
}
90 changes: 46 additions & 44 deletions vault/resource_generic_secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,81 +4,83 @@ import (
"fmt"
"testing"

r "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"

"github.com/hashicorp/vault/api"
)

func TestResourceGenericSecret(t *testing.T) {
r.Test(t, r.TestCase{
path := acctest.RandomWithPrefix("secret/test")
resource.Test(t, resource.TestCase{
Providers: testProviders,
PreCheck: func() { testAccPreCheck(t) },
Steps: []r.TestStep{
r.TestStep{
Config: testResourceGenericSecret_initialConfig,
Check: testResourceGenericSecret_initialCheck,
Steps: []resource.TestStep{
resource.TestStep{
Config: testResourceGenericSecret_initialConfig(path),
Check: testResourceGenericSecret_initialCheck(path),
},
r.TestStep{
resource.TestStep{
Config: testResourceGenericSecret_updateConfig,
Check: testResourceGenericSecret_updateCheck,
},
},
})
}

var testResourceGenericSecret_initialConfig = `
func testResourceGenericSecret_initialConfig(path string) string {
return fmt.Sprintf(`
resource "vault_generic_secret" "test" {
path = "secret/foo"
allow_read = true
path = "%s"
data_json = <<EOT
{
"zip": "zap"
}
EOT
}`, path)
}

`

func testResourceGenericSecret_initialCheck(s *terraform.State) error {
resourceState := s.Modules[0].Resources["vault_generic_secret.test"]
if resourceState == nil {
return fmt.Errorf("resource not found in state")
}

instanceState := resourceState.Primary
if instanceState == nil {
return fmt.Errorf("resource has no primary instance")
}

path := instanceState.ID

if path != instanceState.Attributes["path"] {
return fmt.Errorf("id doesn't match path")
func testResourceGenericSecret_initialCheck(expectedPath string) resource.TestCheckFunc {
return func(s *terraform.State) error {
resourceState := s.Modules[0].Resources["vault_generic_secret.test"]
if resourceState == nil {
return fmt.Errorf("resource not found in state")
}

instanceState := resourceState.Primary
if instanceState == nil {
return fmt.Errorf("resource has no primary instance")
}

path := instanceState.ID

if path != instanceState.Attributes["path"] {
return fmt.Errorf("id doesn't match path")
}
if path != expectedPath {
return fmt.Errorf("unexpected secret path")
}

client := testProvider.Meta().(*api.Client)
secret, err := client.Logical().Read(path)
if err != nil {
return fmt.Errorf("error reading back secret: %s", err)
}

if got, want := secret.Data["zip"], "zap"; got != want {
return fmt.Errorf("'zip' data is %q; want %q", got, want)
}

return nil
}
if path != "secret/foo" {
return fmt.Errorf("unexpected secret path")
}

client := testProvider.Meta().(*api.Client)
secret, err := client.Logical().Read(path)
if err != nil {
return fmt.Errorf("error reading back secret: %s", err)
}

if got, want := secret.Data["zip"], "zap"; got != want {
return fmt.Errorf("'zip' data is %q; want %q", got, want)
}

return nil
}

var testResourceGenericSecret_updateConfig = `
resource "vault_generic_secret" "test" {
path = "secret/foo"
allow_read = true
disable_read = false
data_json = <<EOT
{
"zip": "zoop"
Expand Down
28 changes: 16 additions & 12 deletions website/docs/r/generic_secret.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,22 @@ EOT

The following arguments are supported:

* `path` - (Required) The full logical path at which to write the given
data. To write data into the "generic" secret backend mounted in Vault by
default, this should be prefixed with `secret/`. Writing to other backends
with this resource is possible; consult each backend's documentation to
see which endpoints support the `PUT` and `DELETE` methods.

* `data_json` - (Required) String containing a JSON-encoded object that
will be written as the secret data at the given path.

* `allow_read` - (Optional) True/false. Set this to true if your vault
authentication is able to read the data, this allows the resource to be
compared and updated. Defaults to false.
* `path` - (Required) The full logical path at which to write the given data.
To write data into the "generic" secret backend mounted in Vault by default,
this should be prefixed with `secret/`. Writing to other backends with this
resource is possible; consult each backend's documentation to see which
endpoints support the `PUT` and `DELETE` methods.

* `data_json` - (Required) String containing a JSON-encoded object that will be
written as the secret data at the given path.

* `allow_read` - (Optional, Deprecated) True/false. Set this to true if your
vault authentication is able to read the data, this allows the resource to be
compared and updated. Defaults to false.

* `disable_read` - (Optional) True/false. Set this to true if your vault
authentication is not able to read the data. Setting this to `true` will
break drift detection. Defaults to false.

## Required Vault Capabilities

Expand Down