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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add vault_namespaces data source #1769

Closed
wants to merge 2 commits into from
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions vault/data_source_namespaces.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package vault

import (
"context"
"log"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/vault/api"

"github.com/hashicorp/terraform-provider-vault/internal/consts"
"github.com/hashicorp/terraform-provider-vault/internal/provider"
"github.com/hashicorp/terraform-provider-vault/util"
)

func namespacesDataSource() *schema.Resource {
return &schema.Resource{
ReadContext: ReadContextWrapper(namespacesDataSourceRead),

Schema: map[string]*schema.Schema{
consts.FieldPaths: {
Type: schema.TypeSet,
Computed: true,
Description: "Namespace paths.",
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}

func namespacesDataSourceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client, e := provider.GetClient(d, meta)
if e != nil {
return diag.FromErr(e)
}

log.Printf("[DEBUG] Reading namespaces from Vault")

resp, err := client.Logical().List(SysNamespaceRoot)
if err != nil {
return diag.Errorf("error reading namespaces from Vault: %s", err)
}
if err := d.Set(consts.FieldPaths, flattenPaths(resp)); err != nil {
return diag.Errorf("error setting %q to state: %s", consts.FieldPaths, err)
}

id := util.NormalizeMountPath(client.Namespace())
d.SetId(id)

return nil
}

func flattenPaths(resp *api.Secret) []interface{} {
if resp == nil {
return nil
}

paths := []interface{}{}
if keys, ok := resp.Data["keys"]; ok {
for _, key := range keys.([]interface{}) {
paths = append(paths, util.TrimSlashes(key.(string)))
}
}
return paths
}
69 changes: 69 additions & 0 deletions vault/data_source_namespaces_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package vault

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"

"github.com/hashicorp/terraform-provider-vault/internal/consts"
"github.com/hashicorp/terraform-provider-vault/testutil"
)

func TestAccDataSourceNamespaces(t *testing.T) {
testutil.SkipTestAccEnt(t)

ns := acctest.RandomWithPrefix("tf-ns")

resource.Test(t, resource.TestCase{
Providers: testProviders,
PreCheck: func() { testutil.TestAccPreCheck(t) },
Steps: []resource.TestStep{
{
Config: testAccDataSourceNamespacesConfig(ns, 3),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("data.vault_namespaces.test", consts.FieldPaths+".#", "3"),
resource.TestCheckTypeSetElemAttr("data.vault_namespaces.test", consts.FieldPaths+".*", "test-0"),
resource.TestCheckTypeSetElemAttr("data.vault_namespaces.test", consts.FieldPaths+".*", "test-1"),
resource.TestCheckTypeSetElemAttr("data.vault_namespaces.test", consts.FieldPaths+".*", "test-2"),

resource.TestCheckResourceAttr("data.vault_namespaces.nested", consts.FieldPaths+".#", "0"),
),
},
},
})
}

func testAccDataSourceNamespacesConfig(ns string, count int) string {
config := fmt.Sprintf(`
resource "vault_namespace" "parent" {
path = %q
}

resource "vault_namespace" "test" {
count = %d
namespace = vault_namespace.parent.path
path = "test-${count.index}"
}

resource "vault_namespace" "nested" {
namespace = vault_namespace.test[0].path_fq
path = "nested"
}

data "vault_namespaces" "test" {
namespace = vault_namespace.parent.path
depends_on = [vault_namespace.test]
}

data "vault_namespaces" "nested" {
namespace = vault_namespace.nested.path_fq
}
`, ns, count)

return config
}
5 changes: 5 additions & 0 deletions vault/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ var (
Resource: UpdateSchemaResource(adAccessCredentialsDataSource()),
PathInventory: []string{"/ad/creds/{role}"},
},
"vault_namespaces": {
Resource: UpdateSchemaResource(namespacesDataSource()),
PathInventory: []string{"/sys/namespaces"},
EnterpriseOnly: true,
},
"vault_nomad_access_token": {
Resource: UpdateSchemaResource(nomadAccessCredentialsDataSource()),
PathInventory: []string{"/nomad/creds/{role}"},
Expand Down
52 changes: 52 additions & 0 deletions website/docs/d/namespaces.html.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
layout: "vault"
page_title: "Vault: vault_namespaces data souece"
sidebar_current: "docs-vault-datasource-namespaces"
description: |-
Fetches a list of all namespaces in Vault
---

# vault\_namespace

Lists all direct child [Namespaces](https://www.vaultproject.io/docs/enterprise/namespaces/index.html) in Vault.

**Note** this feature is available only with Vault Enterprise.

## Example Usage

### Child namespaces

```hcl
data "vault_namespaces" "children" {}
```

### Nested namespace

To fetch the details of nested namespaces:

```hcl
data "vault_namespaces" "children" {
namespace = "parent"
}

data "vault_namespace" "child" {
for_each = data.vault_namespaces.children.paths
namespace = data.vault_namespaces.children.namespace
path = each.key
}
Comment on lines +31 to +36
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This example bit depends on #1768

```

## Argument Reference

The following arguments are supported:

* `namespace` - (Optional) The namespace to provision the resource in.
The value should not contain leading or trailing forward slashes.
The `namespace` is always relative to the provider's configured [namespace](/docs/providers/vault#namespace).
*Available only for Vault Enterprise*.

## Attributes Reference

In addition to the above arguments, the following attributes are exported:

* `paths` - Set of the paths of direct child namespaces.
4 changes: 4 additions & 0 deletions website/vault.erb
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@
<a href="/docs/providers/vault/d/pki_secret_backend_keys.html">pki_secret_backend_keys</a>
</li>

<li<%= sidebar_current("docs-vault-datasource-namespaces") %>>
<a href="/docs/providers/vault/d/namespaces.html">vault_namespaces</a>
</li>

</ul>
</li>

Expand Down
Loading