Skip to content

Commit

Permalink
Update migration path and fix acceptance tests
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 27, 2024
1 parent b5fe8d2 commit c8b3462
Show file tree
Hide file tree
Showing 19 changed files with 358 additions and 36 deletions.
10 changes: 10 additions & 0 deletions docs/resources/package_install.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ resource "tanzu-mission-control_package_install" "create_package_install" {
}
}
```

#### Inline values file

```yaml
test: test
test_nested_key:
test_nested_key1: test_nested_value1
test_nested_key2: test_nested_value2
```
<!-- schema generated by tfplugindocs -->
## Schema
Expand Down
4 changes: 4 additions & 0 deletions examples/resources/packageinstall/inline_values.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
test: test
test_nested_key:
test_nested_key1: test_nested_value1
test_nested_key2: test_nested_value2
2 changes: 1 addition & 1 deletion examples/resources/packageinstall/resource.tf
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ resource "tanzu-mission-control_package_install" "create_package_install" {
}
}

path_to_inline_values = "<inline-values-file-path>"
path_to_inline_values = "./inline_values.yaml" #<inline-values-file-path>

inline_values = { "test" : "test" } # Deprecated
}
Expand Down
43 changes: 43 additions & 0 deletions internal/helper/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"github.com/pkg/errors"
"gopkg.in/yaml.v2"
k8sYaml "sigs.k8s.io/yaml"
)

// ReadYamlFile reads a yaml file from a given path.
Expand Down Expand Up @@ -45,6 +46,48 @@ func ReadYamlFile(filePath string) (string, error) {
return buf.String(), nil
}

// ReadYamlFileAsJSON reads a yaml file from a given path.
func ReadYamlFileAsJSON(filePath string) (string, error) {
bufString, err := ReadYamlFile(filePath)
if err != nil {
return "", err
}

jsonBytes, err := k8sYaml.YAMLToJSON([]byte(bufString))
if err != nil {
return "", err
}

return string(jsonBytes), nil
}

// WriteYamlFile writes a yaml file to a given path.
func WriteYamlFile(filePath string, data interface{}) error {
outputFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("Error opening or creating the %s file.", filePath))
}

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

yamlData, err := yaml.Marshal(data)
if err != nil {
return err
}

_, err = outputFile.Write(yamlData)
if err != nil {
return err
}

return nil
}

// FileExists checks if a file exists in a given path.
func FileExists(filePath string) bool {
fileInfo, err := os.Stat(filePath)
Expand Down
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 @@ -259,7 +259,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 updated.")
diag.FromErr(err)
return diag.FromErr(err)
}

if specCheck {
Expand Down
6 changes: 3 additions & 3 deletions internal/resources/package/package_mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (testConfig *testAcceptanceConfig) setupHTTPMocks(t *testing.T) {
FullName: &tanzupakageclustermodel.VmwareTanzuManageV1alpha1ClusterTanzupackageFullName{
ClusterName: testConfig.ScopeHelperResources.Cluster.Name,
ManagementClusterName: "attached",
ProvisionerName: "attacched",
ProvisionerName: "attached",
OrgID: OrgID,
},
Status: &tanzupakageclustermodel.VmwareTanzuManageV1alpha1ClusterTanzupackageStatus{
Expand All @@ -124,7 +124,7 @@ func (testConfig *testAcceptanceConfig) setupHTTPMocks(t *testing.T) {
FullName: &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataPackageFullName{
ClusterName: testConfig.ScopeHelperResources.Cluster.Name,
ManagementClusterName: "attached",
ProvisionerName: "attacched",
ProvisionerName: "attached",
OrgID: OrgID,
Name: testConfig.PkgName,
NamespaceName: globalRepoNamespace,
Expand All @@ -145,7 +145,7 @@ func (testConfig *testAcceptanceConfig) setupHTTPMocks(t *testing.T) {
Licenses: []string{
"some1",
},
ReleaseNotes: "someReleaseNotes",
ReleaseNotes: "cert-manager 1.1.0 https://github.com/jetstack/cert-manager/1.1.0",
ReleasedAt: strfmt.DateTime{},
RepositoryName: "testRepo",
ValuesSchema: &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataPackageValuesSchema{
Expand Down
15 changes: 12 additions & 3 deletions internal/resources/package/spec/cluster_scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,18 @@ func FlattenSpecForClusterScope(spec *packageclustermodel.VmwareTanzuManageV1alp
flattenSpecData[CapacityRequirementsDescriptionKey] = spec.CapacityRequirementsDescription
releaseNotesValue := strings.Split(spec.ReleaseNotes, seperatorStr)

releaseNotes[metadataNameKey] = releaseNotesValue[0]
releaseNotes[versionKey] = releaseNotesValue[1]
releaseNotes[urlKey] = releaseNotesValue[2]
if len(releaseNotesValue) >= 1 {
releaseNotes[metadataNameKey] = releaseNotesValue[0]
}

if len(releaseNotesValue) >= 2 {
releaseNotes[versionKey] = releaseNotesValue[1]
}

if len(releaseNotesValue) >= 3 {
releaseNotes[urlKey] = releaseNotesValue[2]
}

flattenSpecData[ReleaseNotesKey] = []interface{}{releaseNotes}
flattenSpecData[RepositoryNameKey] = spec.RepositoryName

Expand Down
2 changes: 1 addition & 1 deletion internal/resources/packages/packages_mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func (testConfig *testAcceptanceConfig) setupHTTPMocks(t *testing.T) {
Licenses: []string{
"some1",
},
ReleaseNotes: "someReleaseNotes",
ReleaseNotes: "cert-manager 1.1.0 https://github.com/jetstack/cert-manager/1.1.0",
ReleasedAt: strfmt.DateTime{},
RepositoryName: "testRepo",
ValuesSchema: &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataPackageValuesSchema{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@ package tanzupackageinstall

import (
"context"
"fmt"
"strings"

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

Check failure on line 15 in internal/resources/tanzupackageinstall/package_install_datasource.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/vmware/terraform-provider-tanzu-mission-control/internal/authctx"
clienterrors "github.com/vmware/terraform-provider-tanzu-mission-control/internal/client/errors"
"github.com/vmware/terraform-provider-tanzu-mission-control/internal/resources/common"
"github.com/vmware/terraform-provider-tanzu-mission-control/internal/resources/policy"
"github.com/vmware/terraform-provider-tanzu-mission-control/internal/resources/tanzupackageinstall/scope"
"github.com/vmware/terraform-provider-tanzu-mission-control/internal/resources/tanzupackageinstall/spec"
"github.com/vmware/terraform-provider-tanzu-mission-control/internal/resources/tanzupackageinstall/status"
Expand Down Expand Up @@ -80,7 +81,46 @@ func dataPackageInstallRead(ctx context.Context, d *schema.ResourceData, m inter
return diag.FromErr(err)
}

if err := d.Set(spec.SpecKey, spec.FlattenSpecForClusterScope(repoSpec)); err != nil {
// default path
pathToInlineValues := scopedFullnameData.FullnameCluster.ManagementClusterName + "/" +
scopedFullnameData.FullnameCluster.ProvisionerName + "/" +
scopedFullnameData.FullnameCluster.ClusterName + "/" +
scopedFullnameData.FullnameCluster.NamespaceName + "/" +
scopedFullnameData.FullnameCluster.Name + ".yaml"

existingSpec, ok := d.GetOk(policy.SpecKey)
if !ok {
if ctx.Value(contextMethodKey{}) != DataSourceRead {
return diag.FromErr(fmt.Errorf("spec: %v is not valid: minimum one valid spec block is required", existingSpec))
}
} else {
data, _ := existingSpec.([]interface{})

if len(data) == 0 || data[0] == nil {
return diag.FromErr(fmt.Errorf("spec data: %v is not valid: minimum one valid spec data block is required", existingSpec))
}

specData := data[0].(map[string]interface{})

v, ok := specData[spec.PathToInlineValuesKey]
if ok {
v1, ok := v.(string)
if !ok {
return diag.FromErr(fmt.Errorf("type of path_to_inline_values data: %v is not valid", v1))
}

pathToInlineValues = v1
} else {
pathToInlineValues = ""
}
}

specValue, err := spec.FlattenSpecForClusterScope(repoSpec, pathToInlineValues)
if err != nil {
return diag.FromErr(errors.Wrapf(err, "Unable to write inline values to the file: %s", pathToInlineValues))
}

if err := d.Set(spec.SpecKey, specValue); err != nil {
return diag.FromErr(err)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func ResourcePackageInstall() *schema.Resource {
Schema: getResourceSchema(),
CustomizeDiff: customdiff.All(
schema.CustomizeDiffFunc(commonscope.ValidateScope([]string{commonscope.ClusterKey})),
schema.CustomizeDiffFunc(spec.ValidateInlineValues()),
),
}
}
Expand Down Expand Up @@ -195,7 +196,7 @@ func resourcePackageInstallInPlaceUpdate(ctx context.Context, d *schema.Resource
specCheck, err := updateCheckForSpec(d, installSpec)
if err != nil {
log.Println("[ERROR] Unable to check spec has been updated.")
diag.FromErr(err)
return diag.FromErr(err)
}

if specCheck {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ import (
"os"
"testing"

"github.com/go-openapi/strfmt"
"github.com/go-test/deep"
"github.com/jarcoal/httpmock"

"github.com/vmware/terraform-provider-tanzu-mission-control/internal/helper"
objectmetamodel "github.com/vmware/terraform-provider-tanzu-mission-control/internal/models/objectmeta"
pakageclustermodel "github.com/vmware/terraform-provider-tanzu-mission-control/internal/models/package/cluster"
statusmodel "github.com/vmware/terraform-provider-tanzu-mission-control/internal/models/status"
tanzupakageclustermodel "github.com/vmware/terraform-provider-tanzu-mission-control/internal/models/tanzupackage"
packageinstallmodel "github.com/vmware/terraform-provider-tanzu-mission-control/internal/models/tanzupackageinstall"
)

Expand All @@ -27,6 +30,7 @@ const (
clAPIVersionAndGroup = "v1alpha1/clusters"
apiSubGroup = "namespaces"
apiKind = "tanzupackage/installs"
apiKindMetadata = "tanzupackage/metadatas"
)

// nolint: unparam
Expand Down Expand Up @@ -179,6 +183,82 @@ func (testConfig *testAcceptanceConfig) setupHTTPMocks(t *testing.T) {
referenceArray := make([]*objectmetamodel.VmwareTanzuCoreV1alpha1ObjectReference, 0)
referenceArray = append(referenceArray, &reference)

getTanzuPkgMetadataResponse := func(pkgName string) *pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataGetPackageResponse {
return &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataGetPackageResponse{
Package: &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataPackagePackage{
FullName: &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataPackageFullName{
ClusterName: testConfig.ScopeHelperResources.Cluster.Name,
ManagementClusterName: "attached",
ProvisionerName: "attached",
OrgID: OrgID,
Name: pkgName,
NamespaceName: globalRepoNamespace,
MetadataName: pkgMetadataName,
},
Meta: &objectmetamodel.VmwareTanzuCoreV1alpha1ObjectMeta{
ParentReferences: referenceArray,
Description: "resource with description",
Labels: map[string]string{
"key1": "value1",
"key2": "value2",
},
UID: "package1",
ResourceVersion: "v1",
},
Spec: &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataPackageSpec{
CapacityRequirementsDescription: "someCapacityRequirementsDescription",
Licenses: []string{
"some1",
},
ReleaseNotes: "cert-manager 1.1.0 https://github.com/jetstack/cert-manager/1.1.0",
ReleasedAt: strfmt.DateTime{},
RepositoryName: "testRepo",
ValuesSchema: &pakageclustermodel.VmwareTanzuManageV1alpha1ClusterNamespaceTanzupackageMetadataPackageValuesSchema{
Template: &pakageclustermodel.K8sIoApimachineryPkgRuntimeRawExtension{
Raw: []byte("somevalue"),
},
},
},
},
}
}

getTanzuPkgMetadataEndpoint1 := (helper.ConstructRequestURL(https, endpoint, clAPIVersionAndGroup, testConfig.ScopeHelperResources.Cluster.Name, apiSubGroup, globalRepoNamespace, apiKindMetadata, pkgMetadataName, "packages", testConfig.PkgName1)).String()
getTanzuPkgMetadataEndpoint2 := (helper.ConstructRequestURL(https, endpoint, clAPIVersionAndGroup, testConfig.ScopeHelperResources.Cluster.Name, apiSubGroup, globalRepoNamespace, apiKindMetadata, pkgMetadataName, "packages", testConfig.PkgName2)).String()

httpmock.RegisterResponder("GET", getTanzuPkgMetadataEndpoint1,
bodyInspectingResponder(t, nil, 200, getTanzuPkgMetadataResponse(testConfig.PkgName1)))
httpmock.RegisterResponder("GET", getTanzuPkgMetadataEndpoint2,
bodyInspectingResponder(t, nil, 200, getTanzuPkgMetadataResponse(testConfig.PkgName2)))

// cluster level package resource.

getTanzuPackageResponse := &tanzupakageclustermodel.VmwareTanzuManageV1alpha1ClusterTanzupackageListTanzuPackagesResponse{
TanzuPackages: []*tanzupakageclustermodel.VmwareTanzuManageV1alpha1ClusterTanzupackageTanzuPackage{
{
FullName: &tanzupakageclustermodel.VmwareTanzuManageV1alpha1ClusterTanzupackageFullName{
ClusterName: testConfig.ScopeHelperResources.Cluster.Name,
ManagementClusterName: "attached",
ProvisionerName: "attached",
OrgID: OrgID,
},
Status: &tanzupakageclustermodel.VmwareTanzuManageV1alpha1ClusterTanzupackageStatus{
Conditions: map[string]statusmodel.VmwareTanzuCoreV1alpha1StatusCondition{
"Ready": {
Reason: "made successfully",
},
},
PackageRepositoryGlobalNamespace: globalRepoNamespace,
},
},
},
}

getTanzuPackageEndpoint := (helper.ConstructRequestURL(https, endpoint, clAPIVersionAndGroup, testConfig.ScopeHelperResources.Cluster.Name, "tanzupackage")).String()

httpmock.RegisterResponder("GET", getTanzuPackageEndpoint,
bodyInspectingResponder(t, nil, 200, getTanzuPackageResponse))

// cluster level package install resource.
postRequest, postResponse, getResponse := testConfig.getClRequestResponse(OrgID, referenceArray)

Expand Down
Loading

0 comments on commit c8b3462

Please sign in to comment.