github.com/opentofu/opentofu@v1.7.1/internal/encryption/keyprovider/static/config_test.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package static_test
     7  
     8  import (
     9  	"fmt"
    10  
    11  	"github.com/hashicorp/hcl/v2/gohcl"
    12  
    13  	config2 "github.com/opentofu/opentofu/internal/encryption/config"
    14  	"github.com/opentofu/opentofu/internal/encryption/keyprovider/static"
    15  )
    16  
    17  var exampleConfig = `key_provider "static" "foo" {
    18    key = "6f6f706830656f67686f6834616872756f3751756165686565796f6f72653169"
    19  }
    20  `
    21  
    22  // This example is a bare-bones configuration for a static key provider.
    23  // It is mainly intended to demonstrate how you can use parse configuration
    24  // and construct a static key provider from in.
    25  // And is not intended to be used as a real-world example.
    26  func ExampleConfig() {
    27  	staticConfig := static.New().ConfigStruct()
    28  
    29  	// Parse the config:
    30  	parsedConfig, diags := config2.LoadConfigFromString("config.hcl", exampleConfig)
    31  	if diags.HasErrors() {
    32  		panic(diags)
    33  	}
    34  
    35  	if len(parsedConfig.KeyProviderConfigs) != 1 {
    36  		panic("Expected 1 key provider")
    37  	}
    38  	// Grab the KeyProvider from the parsed config:
    39  	keyProvider := parsedConfig.KeyProviderConfigs[0]
    40  
    41  	// assert the Type is "static" and the Name is "foo"
    42  	if keyProvider.Type != "static" {
    43  		panic("Expected key provider type to be 'static'")
    44  	}
    45  	if keyProvider.Name != "foo" {
    46  		panic("Expected key provider name to be 'foo'")
    47  	}
    48  
    49  	// Use gohcl to parse the hcl block from parsedConfig into the static configuration struct
    50  	// This is not the intended path, and it should be handled by the implementation of the Encryption
    51  	// interface.
    52  	//
    53  	// This is just an example of how to use the static configuration struct, and this is how testing
    54  	// may be carried out.
    55  	if err := gohcl.DecodeBody(parsedConfig.KeyProviderConfigs[0].Body, nil, staticConfig); err != nil {
    56  		panic(err)
    57  	}
    58  
    59  	// Cast the static configuration struct to a static.Config so that we can assert against the key
    60  	// value
    61  	s := staticConfig.(*static.Config)
    62  
    63  	fmt.Printf("%s\n", s.Key)
    64  	// Output: 6f6f706830656f67686f6834616872756f3751756165686565796f6f72653169
    65  }