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(fastly_secretstore): implement resource and documentation #707

Merged
merged 6 commits into from
Aug 18, 2023
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
29 changes: 29 additions & 0 deletions docs/data-sources/secretstores.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "fastly_secretstores Data Source - terraform-provider-fastly"
subcategory: ""
description: |-

---

# fastly_secretstores (Data Source)





<!-- schema generated by tfplugindocs -->
## Schema

### Read-Only

- `id` (String) The ID of this resource.
- `stores` (Set of Object) List of all Secrets Stores. (see [below for nested schema](#nestedatt--stores))

<a id="nestedatt--stores"></a>
### Nested Schema for `stores`

Read-Only:

- `id` (String)
- `name` (String)
73 changes: 73 additions & 0 deletions docs/resources/secretstore.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
layout: "fastly"
page_title: "Fastly: secretstore"
sidebar_current: "docs-fastly-resource-secretstore"
description: |-
A secret store is a persistent, globally distributed store for secrets accessible to Compute@Edge services during request processing.
---

# fastly_secretstore

A secret store is a persistent, globally distributed store for secrets accessible to Compute@Edge services during request processing.

In order for a Secret Store (`fastly_secretstore`) to be accessible to a [Compute@Edge](https://developer.fastly.com/learning/compute/) service you'll first need to define a Compute service (`fastly_service_compute`) in your configuration, and then create a link to the Secret Store from within the service using the `resource_link` block (shown in the below examples).

~> **Warning:** Unlike other stores (Config Store, KV Store etc) deleting a Secret Store will automatically delete all the secrets it contains. There is no need to manually delete the secrets first.

~> **Note:** The Fastly Terraform provider does not provide a means to seed the Secret Store with secrets (this is because the values are persisted into the Terraform state file as plaintext). To populate the Secret Store with secrets please use the [Fastly API](https://developer.fastly.com/reference/api/services/resources/secret-store-secret/) directly or the [Fastly CLI](https://developer.fastly.com/reference/cli/secret-store-entry/).

## Example Usage

Basic usage:

```terraform
# IMPORTANT: Deleting a Secret Store requires first deleting its resource_link.
# This requires a two-step `terraform apply` as we can't guarantee deletion order.
# e.g. resource_link deletion within fastly_service_compute might not finish first.
resource "fastly_secretstore" "example" {
name = "my_secret_store"
}

resource "fastly_service_compute" "example" {
name = "my_compute_service"

domain {
name = "demo.example.com"
}

package {
filename = "package.tar.gz"
source_code_hash = data.fastly_package_hash.example.hash
}

resource_link {
name = "my_resource_link"
resource_id = fastly_secretstore.example.id
}

force_destroy = true
}

data "fastly_package_hash" "example" {
filename = "package.tar.gz"
}
```

## Import

Fastly Secret Stores can be imported using their Store ID, e.g.

```sh
$ terraform import fastly_secretstore.example xxxxxxxxxxxxxxxxxxxx
```

<!-- schema generated by tfplugindocs -->
## Schema

### Required

- `name` (String) A human-readable name for the Secret Store. The value must contain only letters, numbers, dashes (-), underscores (_), or periods (.). It is important to note that changing this attribute will delete and recreate the Secret Store, and discard the current entries. You MUST first delete the associated resource_link block from your service before modifying this field.

### Read-Only

- `id` (String) The ID of this resource.
1 change: 1 addition & 0 deletions examples/resources/components/secretstore_import_cmd.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
$ terraform import fastly_secretstore.example xxxxxxxxxxxxxxxxxxxx
30 changes: 30 additions & 0 deletions examples/resources/secretstore_basic_usage.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# IMPORTANT: Deleting a Secret Store requires first deleting its resource_link.
# This requires a two-step `terraform apply` as we can't guarantee deletion order.
# e.g. resource_link deletion within fastly_service_compute might not finish first.
resource "fastly_secretstore" "example" {
name = "my_secret_store"
}

resource "fastly_service_compute" "example" {
name = "my_compute_service"

domain {
name = "demo.example.com"
}

package {
filename = "package.tar.gz"
source_code_hash = data.fastly_package_hash.example.hash
}

resource_link {
name = "my_resource_link"
resource_id = fastly_secretstore.example.id
}

force_destroy = true
}

data "fastly_package_hash" "example" {
filename = "package.tar.gz"
}
98 changes: 98 additions & 0 deletions fastly/data_source_secretstores.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package fastly

import (
"context"
"encoding/json"
"log"
"strconv"

gofastly "github.com/fastly/go-fastly/v8/fastly"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

"github.com/fastly/terraform-provider-fastly/fastly/hashcode"
)

func dataSourceFastlySecretStores() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceFastlySecretStoresRead,
Schema: map[string]*schema.Schema{
"stores": {
Type: schema.TypeSet,
Computed: true,
Description: "List of all Secrets Stores.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
Description: "Alphanumeric string identifying the Secrets Store.",
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: "Name for the Secrets Store.",
},
},
},
},
},
}
}

func dataSourceFastlySecretStoresRead(_ context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
conn := meta.(*APIClient).conn

log.Printf("[DEBUG] Reading Secrets Stores")

var (
cursor string
stores []gofastly.SecretStore
)

for {
remoteState, err := conn.ListSecretStores(&gofastly.ListSecretStoresInput{
Cursor: cursor,
})
if err != nil {
return diag.Errorf("error fetching Secrets Stores: %s", err)
}

if remoteState != nil {
stores = append(stores, remoteState.Data...)
c := remoteState.Meta.NextCursor
if c == "" || c == cursor {
break
}
cursor = c
}
}

hashBase, _ := json.Marshal(stores)
hashString := strconv.Itoa(hashcode.String(string(hashBase)))
d.SetId(hashString)

if err := d.Set("stores", flattenDataSourceSecretStores(stores)); err != nil {
return diag.Errorf("error setting stores: %s", err)
}

return nil
}

// flattenDataSourceSecretStores models data into format suitable for saving to
// Terraform state.
func flattenDataSourceSecretStores(remoteState []gofastly.SecretStore) []map[string]any {
result := make([]map[string]any, len(remoteState))
if len(remoteState) == 0 {
return result
}

for i, resource := range remoteState {
result[i] = map[string]any{
"id": resource.ID,
"name": resource.Name,
}
}

return result
}
83 changes: 83 additions & 0 deletions fastly/data_source_secretstores_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package fastly

import (
"fmt"
"strings"
"testing"

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

func TestAccFastlyDataSourceSecretsStores_Config(t *testing.T) {
h := generateHex()

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
ProviderFactories: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccFastlyDataSourceSecretsStoresConfig(h),
Check: resource.ComposeTestCheckFunc(
func(s *terraform.State) error {
r := s.RootModule().Resources["data.fastly_secretstores.example"]
a := r.Primary.Attributes

want := generateNames(h, 3)
var (
found int
got []string
)

// NOTE: API doesn't guarantee Secrets Store order.
for k, v := range a {
// Example of keys we're looking for:
// "stores.0.name":"tf_677f63804c9351ac31fd0cb1db697b95_1",
// "stores.1.name":"tf_677f63804c9351ac31fd0cb1db697b95_2",
// "stores.2.name":"tf_677f63804c9351ac31fd0cb1db697b95_3",
if strings.HasSuffix(k, ".name") {
got = append(got, v)
for _, name := range want {
if v == name {
found++
break
}
}
}
}

if found != len(want) {
return fmt.Errorf("want: %v, got: %v", want, got)
}

return nil
},
),
},
},
})
}

func testAccFastlyDataSourceSecretsStoresConfig(h string) string {
tf := `
resource "fastly_secretstore" "example_1" {
name = "tf_%s_1"
}

resource "fastly_secretstore" "example_2" {
name = "tf_%s_2"
}

resource "fastly_secretstore" "example_3" {
name = "tf_%s_3"
}

data "fastly_secretstores" "example" {
depends_on = [fastly_secretstore.example_1, fastly_secretstore.example_2, fastly_secretstore.example_3]
}
`

return fmt.Sprintf(tf, h, h, h)
}
2 changes: 2 additions & 0 deletions fastly/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func Provider() *schema.Provider {
"fastly_ip_ranges": dataSourceFastlyIPRanges(),
"fastly_kvstores": dataSourceFastlyKVStores(),
"fastly_package_hash": dataSourceFastlyPackageHash(),
"fastly_secretstores": dataSourceFastlySecretStores(),
"fastly_services": dataSourceFastlyServices(),
"fastly_tls_activation": dataSourceFastlyTLSActivation(),
"fastly_tls_activation_ids": dataSourceFastlyTLSActivationIds(),
Expand All @@ -70,6 +71,7 @@ func Provider() *schema.Provider {
"fastly_configstore": resourceFastlyConfigStore(),
"fastly_configstore_entries": resourceFastlyConfigStoreEntries(),
"fastly_kvstore": resourceFastlyKVStore(),
"fastly_secretstore": resourceFastlySecretStore(),
"fastly_service_acl_entries": resourceServiceACLEntries(),
"fastly_service_authorization": resourceServiceAuthorization(),
"fastly_service_compute": resourceServiceCompute(),
Expand Down
2 changes: 1 addition & 1 deletion fastly/resource_fastly_configstore_entries_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TestResourceFastlyFlattenConfigStoreEntries(t *testing.T) {
}
}

func TestAccFastlyServiceConfigStoreEntries_validate(t *testing.T) {
func TestAccFastlyConfigStoreEntries_validate(t *testing.T) {
storeName := fmt.Sprintf("store_%s", acctest.RandString(10))

want1 := map[string]string{
Expand Down
2 changes: 1 addition & 1 deletion fastly/resource_fastly_configstore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ data "fastly_package_hash" "example" {
}

// Step 1 deleted the resource_link first.
// Step 2 will now delete the fastly_kvstore.
// Step 2 will now delete the fastly_configstore.
func testAccConfigStoreConfigDeleteStep2(serviceName, domainName string) string {
return fmt.Sprintf(`
resource "fastly_service_compute" "example" {
Expand Down
Loading