Skip to content

Commit

Permalink
Migrate inline_values to path_to_inline_values for package install
Browse files Browse the repository at this point in the history
Signed-off-by: Ishan Gupta <gishan@vmware.com>
  • Loading branch information
ishangupta-ds committed Mar 21, 2024
1 parent 6878b5c commit 5da45c9
Show file tree
Hide file tree
Showing 11 changed files with 139 additions and 64 deletions.
4 changes: 3 additions & 1 deletion docs/resources/package_install.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ resource "tanzu-mission-control_package_install" "create_package_install" {
}
}
inline_values = { "test" : "test" }
path_to_inline_values = "<inline-values-file-path>"
inline_values = { "test" : "test" } # Deprecated
}
}
```
Expand Down
4 changes: 3 additions & 1 deletion examples/resources/packageinstall/resource.tf
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ resource "tanzu-mission-control_package_install" "create_package_install" {
}
}

inline_values = { "test" : "test" }
path_to_inline_values = "<inline-values-file-path>"

inline_values = { "test" : "test" } # Deprecated
}
}
58 changes: 58 additions & 0 deletions internal/helper/yaml.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
Copyright © 2024 VMware, Inc. All Rights Reserved.
SPDX-License-Identifier: MPL-2.0
*/

package helper

import (
"bytes"
"fmt"
"io"
"log"
"os"

"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)

// ReadYamlFile reads a yaml file from a given path.
func ReadYamlFile(filePath string) (string, error) {
inputFile, err := os.Open(filePath)
if err != nil {
return "", errors.WithMessage(err, fmt.Sprintf("Error opening the %s file.", filePath))
}

defer func(inputFile *os.File) {
err := inputFile.Close()
if err != nil {
log.Println("[ERROR] could not close file object.")
}
}(inputFile)

buf := bytes.NewBuffer(nil)
_, err = io.Copy(buf, inputFile)

if err != nil {
return "", err
}

_, err = yaml.Marshal(buf.String())
if err != nil {
return "", err
}

return buf.String(), nil
}

// FileExists checks if a file exists in a given path.
func FileExists(filePath string) bool {
fileInfo, err := os.Stat(filePath)

if os.IsNotExist(err) {
log.Println("[ERROR] file does not exists.")
return false
}

return !fileInfo.IsDir()
}
2 changes: 1 addition & 1 deletion internal/resources/helmrelease/resource_helm_release.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ func resourceHelmReleaseInPlaceUpdate(ctx context.Context, d *schema.ResourceDat

specCheck, err := updateCheckForSpec(d, helmReleaseDataFromServer.atomicSpec, scopedFullnameData.Scope)
if err != nil {
log.Println("[ERROR] Unable to check spec has been updtated.")
log.Println("[ERROR] Unable to check spec has been updated.")
diag.FromErr(err)
}

Expand Down
4 changes: 2 additions & 2 deletions internal/resources/helmrelease/spec/cluster_scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ func ConstructSpecForClusterScope(d *schema.ResourceData) (spec *releaseclusterm

if inlineConfigValueFile, ok := specData[InlineConfigKey]; ok {
if (inlineConfigValueFile.(string)) != "" {
if !(fileExists(inlineConfigValueFile.(string))) {
if !(helper.FileExists(inlineConfigValueFile.(string))) {
return spec, errors.Errorf("File %s does not exists.", inlineConfigValueFile.(string))
}

spec.InlineConfiguration, err = readYamlFile(inlineConfigValueFile.(string))
spec.InlineConfiguration, err = helper.ReadYamlFile(inlineConfigValueFile.(string))
if err != nil {
return spec, err
}
Expand Down
44 changes: 1 addition & 43 deletions internal/resources/helmrelease/spec/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,9 @@ SPDX-License-Identifier: MPL-2.0
package spec

import (
"bytes"
"fmt"
"io"
"log"
"os"
"time"

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

Check failure on line 11 in internal/resources/helmrelease/spec/spec.go

View workflow job for this annotation

GitHub Actions / lint

File is not `goimports`-ed with -local github.com/vmware/terraform-provider-tanzu-mission-control (goimports)
"github.com/pkg/errors"
"gopkg.in/yaml.v2"

"github.com/vmware/terraform-provider-tanzu-mission-control/internal/helper"
releaseclustermodel "github.com/vmware/terraform-provider-tanzu-mission-control/internal/models/helmrelease/cluster"
)
Expand Down Expand Up @@ -48,7 +40,7 @@ var SpecSchema = &schema.Schema{
Description: "File to read inline values from (in yaml format).User need to specify the file path for inline config",
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
newInlineConfig, err := readYamlFile(new)
newInlineConfig, err := helper.ReadYamlFile(new)
if err != nil {
return false
}
Expand Down Expand Up @@ -258,37 +250,3 @@ func HasSpecChanged(d *schema.ResourceData) bool {

return updateRequired
}

func readYamlFile(fileName string) (string, error) {
inputFile, err := os.Open(fileName)
if err != nil {
return "", errors.WithMessage(err, fmt.Sprintf("Error opening the %s file.", fileName))
}

defer inputFile.Close()

buf := bytes.NewBuffer(nil)
_, err = io.Copy(buf, inputFile)

if err != nil {
return "", err
}

_, err = yaml.Marshal(buf.String())
if err != nil {
return "", err
}

return buf.String(), nil
}

func fileExists(filepath string) bool {
fileinfo, err := os.Stat(filepath)

if os.IsNotExist(err) {
log.Println("[ERROR] file does not exists.")
return false
}

return !fileinfo.IsDir()
}
37 changes: 26 additions & 11 deletions internal/resources/tanzupackageinstall/package_install_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,16 @@ func resourcePackageInstallCreate(ctx context.Context, d *schema.ResourceData, m
return diag.Errorf("Unable to create Tanzu Mission Control package install entry; Scope full name is empty")
}

specVal, err := spec.ConstructSpecForClusterScope(d)
if err != nil {
return diag.FromErr(err)
}

packageInstallReq := &pkginstallclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallInstallRequest{
Install: &pkginstallclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallInstall{
FullName: scopedFullnameData.FullnameCluster,
Meta: common.ConstructMeta(d),
Spec: spec.ConstructSpecForClusterScope(d),
Spec: specVal,
},
}

Expand Down Expand Up @@ -187,8 +192,14 @@ func resourcePackageInstallInPlaceUpdate(ctx context.Context, d *schema.Resource
updateAvailable = true
}

if updateCheckForSpec(d, installSpec) {
err := CheckForUpdatedPackage(config, scopedFullnameData, installSpec)
specCheck, err := updateCheckForSpec(d, installSpec)
if err != nil {
log.Println("[ERROR] Unable to check spec has been updated.")
diag.FromErr(err)
}

if specCheck {
err = CheckForUpdatedPackage(config, scopedFullnameData, installSpec)
if err != nil {
return diag.FromErr(err)
}
Expand All @@ -197,6 +208,7 @@ func resourcePackageInstallInPlaceUpdate(ctx context.Context, d *schema.Resource
}

if !updateAvailable {
log.Printf("[INFO] package install update is not required")
return
}

Expand Down Expand Up @@ -283,21 +295,24 @@ func updateCheckForMeta(d *schema.ResourceData, meta *objectmetamodel.VmwareTanz
return true
}

func updateCheckForSpec(d *schema.ResourceData, installSpec *pkginstallclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallSpec) bool {
func updateCheckForSpec(d *schema.ResourceData, installSpec *pkginstallclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallSpec) (bool, error) {
if !spec.HasSpecChanged(d) {
return false
return false, nil
}

updatedInstallSpec := spec.ConstructSpecForClusterScope(d)
specVal, err := spec.ConstructSpecForClusterScope(d)
if err != nil {
return false, err
}

installSpec.PackageRef.PackageMetadataName = updatedInstallSpec.PackageRef.PackageMetadataName
installSpec.PackageRef.VersionSelection.Constraints = updatedInstallSpec.PackageRef.VersionSelection.Constraints
installSpec.RoleBindingScope = updatedInstallSpec.RoleBindingScope
installSpec.InlineValues = updatedInstallSpec.InlineValues
installSpec.PackageRef.PackageMetadataName = specVal.PackageRef.PackageMetadataName
installSpec.PackageRef.VersionSelection.Constraints = specVal.PackageRef.VersionSelection.Constraints
installSpec.RoleBindingScope = specVal.RoleBindingScope
installSpec.InlineValues = specVal.InlineValues

log.Printf("[INFO] updating package install spec")

return true
return true, nil
}

func GetGlobalNamespace(config authctx.TanzuContext, searchscope *tanzupakageclustermodel.VmwareTanzuManageV1alpha1ClusterTanzupackageSearchScope) (string, error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,23 @@ import (

valid "github.com/asaskevich/govalidator"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/pkg/errors"

"github.com/vmware/terraform-provider-tanzu-mission-control/internal/helper"
packageinstallmodel "github.com/vmware/terraform-provider-tanzu-mission-control/internal/models/tanzupackageinstall"
common "github.com/vmware/terraform-provider-tanzu-mission-control/internal/resources/common"
"github.com/vmware/terraform-provider-tanzu-mission-control/internal/resources/common"
)

func ConstructSpecForClusterScope(d *schema.ResourceData) (spec *packageinstallmodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallSpec) {
func ConstructSpecForClusterScope(d *schema.ResourceData) (spec *packageinstallmodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallSpec, err error) {
value, ok := d.GetOk(SpecKey)
if !ok {
return spec
return spec, nil
}

data, _ := value.([]interface{})

if len(data) == 0 || data[0] == nil {
return spec
return spec, nil
}

specData := data[0].(map[string]interface{})
Expand Down Expand Up @@ -65,6 +67,7 @@ func ConstructSpecForClusterScope(d *schema.ResourceData) (spec *packageinstallm

spec.RoleBindingScope = packageinstallmodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallRoleBindingScopeCLUSTER.Pointer()

// To be deprecated in a future release.
if v, ok := specData[InlineValuesKey]; ok {
if v1, ok := v.(map[string]interface{}); ok {
for key, value := range v1 {
Expand Down Expand Up @@ -95,7 +98,20 @@ func ConstructSpecForClusterScope(d *schema.ResourceData) (spec *packageinstallm
}
}

return spec
if inlineValuesFile, ok := specData[PathToInlineValuesKey]; ok {
if (inlineValuesFile.(string)) != "" {
if !(helper.FileExists(inlineValuesFile.(string))) {
return spec, errors.Errorf("File %s does not exists.", inlineValuesFile.(string))
}

spec.InlineValues, err = helper.ReadYamlFile(inlineValuesFile.(string))
if err != nil {
return spec, err
}
}
}

return spec, nil
}

func FlattenSpecForClusterScope(spec *packageinstallmodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageInstallSpec) (data []interface{}) {
Expand All @@ -119,13 +135,16 @@ func FlattenSpecForClusterScope(spec *packageinstallmodel.VmwareTanzuManageV1alp
pkgRefSpec[PackageMetadataNameKey] = pkgMetadataName
pkgRefSpec[VersionSelectionKey] = versionSelectionSpec

// To be deprecated in a future release.
if v1, ok := spec.InlineValues.(map[string]interface{}); ok {
inline := common.GetTypeStringMapData(v1)
flattenSpecData[InlineValuesKey] = inline
} else {
flattenSpecData[InlineValuesKey] = spec.InlineValues
}

flattenSpecData[PathToInlineValuesKey] = spec.InlineValues

flattenSpecData[RoleBindingScopeKey] = string(*spec.RoleBindingScope)

flattenSpecData[PackageRefKey] = []interface{}{pkgRefSpec}
Expand Down
1 change: 1 addition & 0 deletions internal/resources/tanzupackageinstall/spec/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const (
PackageRefKey = "package_ref"
RoleBindingScopeKey = "role_binding_scope"
InlineValuesKey = "inline_values"
PathToInlineValuesKey = "path_to_inline_values"
PackageMetadataNameKey = "package_metadata_name"
VersionSelectionKey = "version_selection"
ConstraintsKey = "constraints"
Expand Down
16 changes: 16 additions & 0 deletions internal/resources/tanzupackageinstall/spec/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,25 @@ var (
Description: "Role binding scope for service account which will be used by Package Install.",
Computed: true,
},
PathToInlineValuesKey: {
Type: schema.TypeString,
Description: "File to read inline values from (in yaml format). User needs to specify the file path for inline values.",
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
newInlineValues, err := helper.ReadYamlFile(new)
if err != nil {
return false
}

return old == newInlineValues
},
},
InlineValuesKey: {
Type: schema.TypeMap,
Description: "Inline values to configure the Package Install.",
Optional: true,
Sensitive: true,
Deprecated: "This field is deprecated. For providing the inline values, use the new field: path_to_inline_values",
},
},
},
Expand Down Expand Up @@ -81,6 +95,8 @@ func HasSpecChanged(d *schema.ResourceData) bool {
fallthrough
case d.HasChange(helper.GetFirstElementOf(SpecKey, RoleBindingScopeKey)):
fallthrough
case d.HasChange(helper.GetFirstElementOf(SpecKey, PathToInlineValuesKey)):
fallthrough
case d.HasChange(helper.GetFirstElementOf(SpecKey, InlineValuesKey)):
updateRequired = true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ func TestFlattenSpecForClusterScope(t *testing.T) {
"namespace": "cert-manager",
"some": "91",
},
PathToInlineValuesKey: map[string]interface{}{
"namespace": "cert-manager",
"some": 91,
},
},
},
},
Expand Down

0 comments on commit 5da45c9

Please sign in to comment.