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

new ephemeral resources: aws_secretsmanager_secret_version and aws_kms_secrets #40009

Merged
merged 20 commits into from
Nov 20, 2024
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
11 changes: 11 additions & 0 deletions .changelog/40009.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
```release-note:new-ephemeral
aws_secretsmanager_secret_version
```

```release-note:new-ephemeral
aws_kms_secrets
```

```release-note:note
New [ephemeral resources](https://developer.hashicorp.com/terraform/language/v1.10.x/resources/ephemeral) `aws_kms_secrets`, `aws_lambda_invocation`, and `aws_secretsmanager_secret_version` now support [ephemeral values](https://developer.hashicorp.com/terraform/language/v1.10.x/values/variables#exclude-values-from-state).
```
147 changes: 147 additions & 0 deletions internal/service/kms/secrets_ephemeral.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package kms

import (
"context"

"github.com/aws/aws-sdk-go-v2/service/kms"
awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types"
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/ephemeral"
"github.com/hashicorp/terraform-plugin-framework/ephemeral/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-provider-aws/internal/framework"
fwflex "github.com/hashicorp/terraform-provider-aws/internal/framework/flex"
fwtypes "github.com/hashicorp/terraform-provider-aws/internal/framework/types"
itypes "github.com/hashicorp/terraform-provider-aws/internal/types"
"github.com/hashicorp/terraform-provider-aws/names"
)

// @EphemeralResource(aws_kms_secrets, name="Secrets")
func newEphemeralSecrets(_ context.Context) (ephemeral.EphemeralResourceWithConfigure, error) {
return &ephemeralSecrets{}, nil
}

type ephemeralSecrets struct {
framework.EphemeralResourceWithConfigure
}

func (e *ephemeralSecrets) Metadata(_ context.Context, _ ephemeral.MetadataRequest, response *ephemeral.MetadataResponse) {
response.TypeName = "aws_kms_secrets"
}

func (e *ephemeralSecrets) Schema(ctx context.Context, _ ephemeral.SchemaRequest, response *ephemeral.SchemaResponse) {
response.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"plaintext": schema.MapAttribute{
CustomType: fwtypes.MapOfStringType,
Computed: true,
Sensitive: true,
},
},
Blocks: map[string]schema.Block{
"secret": schema.SetNestedBlock{
CustomType: fwtypes.NewSetNestedObjectTypeOf[epSecrets](ctx),
Validators: []validator.Set{
setvalidator.IsRequired(),
},
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"context": schema.MapAttribute{
CustomType: fwtypes.MapOfStringType,
Optional: true,
},
"encryption_algorithm": schema.StringAttribute{
CustomType: fwtypes.StringEnumType[awstypes.EncryptionAlgorithmSpec](),
Optional: true,
},
"grant_tokens": schema.ListAttribute{
CustomType: fwtypes.ListOfStringType,
Optional: true,
},
names.AttrKeyID: schema.StringAttribute{
Optional: true,
},
names.AttrName: schema.StringAttribute{
Required: true,
},
"payload": schema.StringAttribute{
Required: true,
},
},
},
},
},
}
}

func (e *ephemeralSecrets) Open(ctx context.Context, request ephemeral.OpenRequest, response *ephemeral.OpenResponse) {
var data epSecretData
conn := e.Meta().KMSClient(ctx)

response.Diagnostics.Append(request.Config.Get(ctx, &data)...)
if response.Diagnostics.HasError() {
return
}

secrets, diags := data.Secrets.ToSlice(ctx)
response.Diagnostics.Append(diags...)
if response.Diagnostics.HasError() {
return
}

plaintext := make(map[string]attr.Value)

for _, v := range secrets {
input := kms.DecryptInput{}
response.Diagnostics.Append(fwflex.Expand(ctx, v, &input)...)
if response.Diagnostics.HasError() {
return
}
input.EncryptionContext = fwflex.ExpandFrameworkStringValueMap(ctx, v.Context)

payload, err := itypes.Base64Decode(v.Payload.ValueString())
if err != nil {
response.Diagnostics.AddError(
"invalid base64 value for secret",
err.Error(),
)
return
}

input.CiphertextBlob = payload

output, err := conn.Decrypt(ctx, &input)
if err != nil {
response.Diagnostics.AddError(
"failed to decrypt secret",
err.Error(),
)
return
}

plaintext[v.Name.ValueString()] = fwflex.StringValueToFramework(ctx, string(output.Plaintext))
}

data.Plaintext = fwtypes.NewMapValueOfMust[types.String](ctx, plaintext)

response.Diagnostics.Append(response.Result.Set(ctx, &data)...)
}

type epSecretData struct {
Plaintext fwtypes.MapValueOf[types.String] `tfsdk:"plaintext"`
Secrets fwtypes.SetNestedObjectValueOf[epSecrets] `tfsdk:"secret"`
}

type epSecrets struct {
Context fwtypes.MapValueOf[types.String] `tfsdk:"context"`
EncryptionAlgorithm fwtypes.StringEnum[awstypes.EncryptionAlgorithmSpec] `tfsdk:"encryption_algorithm"`
GrantTokens fwtypes.ListValueOf[types.String] `tfsdk:"grant_tokens"`
KeyID types.String `tfsdk:"key_id"`
Name types.String `tfsdk:"name"`
Payload types.String `tfsdk:"payload"`
}
76 changes: 76 additions & 0 deletions internal/service/kms/secrets_ephemeral_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package kms_test

import (
"fmt"
"testing"

sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/knownvalue"
"github.com/hashicorp/terraform-plugin-testing/statecheck"
"github.com/hashicorp/terraform-plugin-testing/tfjsonpath"
"github.com/hashicorp/terraform-plugin-testing/tfversion"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/names"
)

func TestAccKMSSecretsEphemeral_basic(t *testing.T) {
ctx := acctest.Context(t)
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)
echoResourceName := "echo.test"
dataPath := tfjsonpath.New("data")
plaintext := "my-plaintext-string"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(ctx, t) },
ErrorCheck: acctest.ErrorCheck(t, names.KMSServiceID),
TerraformVersionChecks: []tfversion.TerraformVersionCheck{
tfversion.SkipBelow(tfversion.Version1_10_0),
},
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
ProtoV6ProviderFactories: acctest.ProtoV6ProviderFactories(ctx, acctest.ProviderNameEcho),
CheckDestroy: acctest.CheckDestroyNoop,
Steps: []resource.TestStep{
{
Config: testAccSecretsEphemeralResourceConfig_basic(rName, plaintext),
ConfigStateChecks: []statecheck.StateCheck{
statecheck.ExpectKnownValue(echoResourceName, dataPath.AtMapKey("plaintext").AtMapKey(rName), knownvalue.StringExact(plaintext)),
},
},
},
})
}

func testAccSecretsEphemeralResourceConfig_basic(rName, secretString string) string {
return acctest.ConfigCompose(
acctest.ConfigWithEchoProvider("ephemeral.aws_kms_secrets.test"),
fmt.Sprintf(`
resource "aws_kms_key" "test" {
description = %[1]q
is_enabled = true
}

resource "aws_kms_ciphertext" "test" {
key_id = aws_kms_key.test.key_id

context = {
foo = "bar"
}

plaintext = %[2]q
}

ephemeral "aws_kms_secrets" "test" {
secret {
name = %[1]q
payload = aws_kms_ciphertext.test.ciphertext_blob
context = aws_kms_ciphertext.test.context
}

depends_on = [aws_kms_key.test]
}
`, rName, secretString))
}
9 changes: 9 additions & 0 deletions internal/service/kms/service_package_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

112 changes: 112 additions & 0 deletions internal/service/secretsmanager/secret_version_ephemeral.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package secretsmanager

import (
"context"

"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes"
"github.com/hashicorp/terraform-plugin-framework/ephemeral"
"github.com/hashicorp/terraform-plugin-framework/ephemeral/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-provider-aws/internal/create"
"github.com/hashicorp/terraform-provider-aws/internal/framework"
fwflex "github.com/hashicorp/terraform-provider-aws/internal/framework/flex"
fwtypes "github.com/hashicorp/terraform-provider-aws/internal/framework/types"
"github.com/hashicorp/terraform-provider-aws/names"
)

// @EphemeralResource(aws_secretsmanager_secret_version, name="Secret Version")
func newEphemeralSecretVersion(_ context.Context) (ephemeral.EphemeralResourceWithConfigure, error) {
return &ephemeralSecrets{}, nil
}

type ephemeralSecrets struct {
framework.EphemeralResourceWithConfigure
}

func (e *ephemeralSecrets) Metadata(_ context.Context, _ ephemeral.MetadataRequest, response *ephemeral.MetadataResponse) {
response.TypeName = "aws_secretsmanager_secret_version"
}

func (e *ephemeralSecrets) Schema(ctx context.Context, _ ephemeral.SchemaRequest, response *ephemeral.SchemaResponse) {
response.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
names.AttrARN: framework.ARNAttributeComputedOnly(),
names.AttrCreatedDate: schema.StringAttribute{
CustomType: timetypes.RFC3339Type{},
Computed: true,
},
"secret_id": schema.StringAttribute{
Required: true,
},
"secret_binary": schema.StringAttribute{
Computed: true,
Sensitive: true,
},
"secret_string": schema.StringAttribute{
Computed: true,
Sensitive: true,
},
"version_id": schema.StringAttribute{
Optional: true,
Computed: true,
},
"version_stage": schema.StringAttribute{
Optional: true,
Computed: true,
},
"version_stages": schema.ListAttribute{
CustomType: fwtypes.ListOfStringType,
Computed: true,
},
},
}
}

func (e *ephemeralSecrets) Open(ctx context.Context, request ephemeral.OpenRequest, response *ephemeral.OpenResponse) {
var data epSecretVersionData
conn := e.Meta().SecretsManagerClient(ctx)

response.Diagnostics.Append(request.Config.Get(ctx, &data)...)
if response.Diagnostics.HasError() {
return
}

input := secretsmanager.GetSecretValueInput{}
response.Diagnostics.Append(fwflex.Expand(ctx, data, &input)...)
if response.Diagnostics.HasError() {
return
}

output, err := findSecretVersion(ctx, conn, &input)
if err != nil {
response.Diagnostics.AddError(
create.ProblemStandardMessage(names.SecretsManager, create.ErrActionReading, DSNameSecretVersions, data.ARN.String(), err),
err.Error(),
)
return
}

response.Diagnostics.Append(fwflex.Flatten(ctx, output, &data, fwflex.WithIgnoredFieldNamesAppend("SecretBinary"))...)
if response.Diagnostics.HasError() {
return
}

data.SecretBinary = fwflex.StringValueToFramework(ctx, string(output.SecretBinary))

response.Diagnostics.Append(response.Result.Set(ctx, &data)...)
}

type epSecretVersionData struct {
ARN types.String `tfsdk:"arn"`
CreatedDate timetypes.RFC3339 `tfsdk:"created_date"`
SecretID types.String `tfsdk:"secret_id"`
SecretBinary types.String `tfsdk:"secret_binary"`
SecretString types.String `tfsdk:"secret_string"`
VersionID types.String `tfsdk:"version_id"`
VersionStage types.String `tfsdk:"version_stage"`
VersionStages fwtypes.ListValueOf[types.String] `tfsdk:"version_stages"`
}
Loading
Loading