Skip to content

Commit

Permalink
[CCE] Add possibility to import addons (#1066)
Browse files Browse the repository at this point in the history
[CCE] Add possibility to import addons

Summary of the Pull Request
Add possibility to import resource/opentelekomcloud_cce_addon_v3
PR Checklist

 Refers to: #1056
 Tests added/passed.
 Documentation updated.
 Schema updated.

Acceptance Steps Performed
Import
=== RUN   TestAccCCEAddonV3ImportBasic
--- PASS: TestAccCCEAddonV3ImportBasic (403.78s)
PASS

Process finished with the exit code 0

Basic
=== RUN   TestAccCCEAddonV3Basic
--- PASS: TestAccCCEAddonV3Basic (353.78s)
=== RUN   TestAccCCEAddonV3ForceNewCCE
--- PASS: TestAccCCEAddonV3ForceNewCCE (683.28s)
PASS

Process finished with the exit code 0

Reviewed-by: None <None>
Reviewed-by: Anton Kachurin <katchuring@gmail.com>
Reviewed-by: Rodion Gyrbu <fpsoff@outlook.com>
  • Loading branch information
lego963 committed May 24, 2021
1 parent 02e5b60 commit ece1e60
Show file tree
Hide file tree
Showing 6 changed files with 133 additions and 50 deletions.
9 changes: 9 additions & 0 deletions docs/resources/cce_addon_v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,12 @@ All above argument parameters can be exported as attribute parameters along with
* `name` - Installed add-on name.

* `description` - Installed add-on description


## Import

CCE addons can be imported using the `cluster_id/addon_id`, e.g.

```sh
terraform import opentelekomcloud_cce_addon_v3.autoscaler c1881895-cdcb-4d23-96cb-032e6a3ee667/ea257959-eeb1-4c10-8d33-26f0409a755d
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package acceptance

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/opentelekomcloud/terraform-provider-opentelekomcloud/opentelekomcloud/acceptance/common"
)

func TestAccCCEAddonV3ImportBasic(t *testing.T) {
resourceName := "opentelekomcloud_cce_addon_v3.autoscaler"

resource.Test(t, resource.TestCase{
PreCheck: func() { common.TestAccPreCheck(t) },
Providers: common.TestAccProviders,
CheckDestroy: testAccCheckCCEAddonV3Destroy,
Steps: []resource.TestStep{
{
Config: testAccCCEAddonV3Basic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateIdFunc: testAccCCEAddonV3ImportStateIdFunc(),
ImportStateVerifyIgnore: []string{
"values",
},
},
},
})
}

func testAccCCEAddonV3ImportStateIdFunc() resource.ImportStateIdFunc {
return func(s *terraform.State) (string, error) {
var clusterID string
var addonID string
for _, rs := range s.RootModule().Resources {
if rs.Type == "opentelekomcloud_cce_cluster_v3" {
clusterID = rs.Primary.ID
} else if rs.Type == "opentelekomcloud_cce_addon_v3" {
addonID = rs.Primary.ID
}
}
if clusterID == "" || addonID == "" {
return "", fmt.Errorf("resource not found: %s/%s", clusterID, addonID)
}
return fmt.Sprintf("%s/%s", clusterID, addonID), nil
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,6 @@ func TestAccCCEAddonV3ForceNewCCE(t *testing.T) {
})
}

func TestAccCCEAddonV3EmptyBasic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { common.TestAccPreCheck(t) },
Providers: common.TestAccProviders,
CheckDestroy: testAccCheckCCEAddonV3Destroy,
Steps: []resource.TestStep{
{
Config: testAccCCEAddonV3EmptyBasic,
},
},
})
}

func testAccCheckCCEAddonV3Destroy(s *terraform.State) error {
config := common.TestAccProvider.Meta().(*cfg.Config)
cceClient, err := config.CceV3Client(env.OS_REGION_NAME)
Expand Down Expand Up @@ -192,28 +179,6 @@ resource "opentelekomcloud_cce_addon_v3" "autoscaler" {
}
`, clusterName, env.OS_VPC_ID, env.OS_NETWORK_ID, env.OS_TENANT_ID)

testAccCCEAddonV3EmptyBasic = fmt.Sprintf(`
resource opentelekomcloud_cce_cluster_v3 cluster {
name = "%s"
cluster_type = "VirtualMachine"
flavor_id = "cce.s1.small"
vpc_id = "%s"
subnet_id = "%s"
container_network_type = "overlay_l2"
kubernetes_svc_ip_range = "10.247.0.0/16"
}
resource "opentelekomcloud_cce_addon_v3" "cluster_autoscaler" {
template_name = "autoscaler"
template_version = "1.19.1"
cluster_id = opentelekomcloud_cce_cluster_v3.cluster.id
values {
basic = {}
custom = {}
}
}
`, clusterName, env.OS_VPC_ID, env.OS_NETWORK_ID)

testAccCCEAddonV3ForceNew = fmt.Sprintf(`
resource opentelekomcloud_cce_cluster_v3 cluster_1 {
name = "%s"
Expand Down
19 changes: 10 additions & 9 deletions opentelekomcloud/common/diff_suppress_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,23 @@ func SuppressEquivalentAwsPolicyDiffs(_, old, new string, _ *schema.ResourceData
return equivalent
}

// Suppress all changes?
// SuppressDiffAll suppress all changes?
func SuppressDiffAll(_, _, _ string, _ *schema.ResourceData) bool {
return true
}

// Suppress changes if we get a computed min_disk_gb if value is unspecified (default 0)
// SuppressMinDisk suppress changes if we get a computed min_disk_gb if value is unspecified (default 0)
func SuppressMinDisk(_, old, new string, _ *schema.ResourceData) bool {
return new == "0" || old == new
}

// Suppress changes if we don't specify an external gateway, but one is specified for us
// SuppressExternalGateway suppress changes if we don't specify an external gateway, but one is specified for us
func SuppressExternalGateway(_, old, new string, _ *schema.ResourceData) bool {
return new == "" || old == new
}

// Suppress changes if we get a fixed ip when not expecting one, if we have a floating ip (generates fixed ip).
// SuppressComputedFixedWhenFloatingIp suppress changes if we get a fixed ip when not expecting one,
// if we have a floating ip (generates fixed ip).
func SuppressComputedFixedWhenFloatingIp(_, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("floating_ip"); ok && v != "" {
return new == "" || old == new
Expand All @@ -53,12 +54,12 @@ func SuppressLBWhitelistDiffs(_, old, new string, _ *schema.ResourceData) bool {
if len(old) != len(new) {
return false
}
old_array := strings.Split(old, ",")
new_array := strings.Split(new, ",")
sort.Strings(old_array)
sort.Strings(new_array)
oldArray := strings.Split(old, ",")
newArray := strings.Split(new, ",")
sort.Strings(oldArray)
sort.Strings(newArray)

return reflect.DeepEqual(old_array, new_array)
return reflect.DeepEqual(oldArray, newArray)
}

func SuppressSmartVersionDiff(_, old, new string, _ *schema.ResourceData) bool {
Expand Down
4 changes: 4 additions & 0 deletions opentelekomcloud/common/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,7 @@ func StringInSlice(str string, slice []string) bool {
}
return false
}

func BuildComponentID(parts ...string) string {
return strings.Join(parts, "/")
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
golangsdk "github.com/opentelekomcloud/gophertelekomcloud"
"github.com/opentelekomcloud/gophertelekomcloud"
"github.com/opentelekomcloud/gophertelekomcloud/openstack/cce/v3/addons"

"github.com/opentelekomcloud/terraform-provider-opentelekomcloud/opentelekomcloud/common/cfg"
)

Expand All @@ -25,6 +25,10 @@ func ResourceCCEAddonV3() *schema.Resource {
Delete: schema.DefaultTimeout(5 * time.Minute),
},

Importer: &schema.ResourceImporter{
State: resourceCCEAddonV3Import,
},

Schema: map[string]*schema.Schema{
"template_version": {
Type: schema.TypeString,
Expand Down Expand Up @@ -115,24 +119,30 @@ func resourceCCEAddonV3Create(d *schema.ResourceData, meta interface{}) error {
if aErr == nil {
errMsg = fmt.Errorf("\nAddon template spec: %s\n%s", addonSpec, errMsg)
}
return fmt.Errorf("error creating CCE addon instance: %s", errMsg)
return fmt.Errorf("error creating CCE addon instance: %w", errMsg)
}

d.SetId(addon.Metadata.Id)

return resourceCCEAddonV3Read(d, meta)
}

func resourceCCEAddonV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*cfg.Config)
client, err := config.CceV3AddonClient(config.GetRegion(d))
if err != nil {
return fmt.Errorf("error creating CCE client: %s", logHttpError(err))
return fmt.Errorf("error creating CCE client: %w", logHttpError(err))
}

clusterID := d.Get("cluster_id").(string)
addon, err := addons.Get(client, d.Id(), clusterID).Extract()
if err != nil {
return fmt.Errorf("error reading CCE addon instance: %s", logHttpError(err))
if _, ok := err.(golangsdk.ErrDefault404); ok {
d.SetId("")
return nil
}

return fmt.Errorf("error reading CCE addon instance: %w", logHttpError(err))
}

mErr := multierror.Append(nil,
Expand All @@ -142,8 +152,9 @@ func resourceCCEAddonV3Read(d *schema.ResourceData, meta interface{}) error {
d.Set("template_name", addon.Spec.AddonTemplateName),
d.Set("description", addon.Spec.Description),
)

if err := mErr.ErrorOrNil(); err != nil {
return fmt.Errorf("error setting addon attributes: %s", err)
return fmt.Errorf("error setting addon attributes: %w", err)
}

return nil
Expand Down Expand Up @@ -241,3 +252,44 @@ func waitForCCEAddonDelete(client *golangsdk.ServiceClient, addonID, clusterID s
return addon, "available", nil
}
}

func resourceCCEAddonV3Import(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
parts := strings.SplitN(d.Id(), "/", 2)
if len(parts) != 2 {
err := fmt.Errorf("invalid format specified for CCE Addon. Format must be <cluster id>/<addon id>")
return nil, err
}
clusterID := parts[0]
addonID := parts[1]
d.SetId(addonID)

config := meta.(*cfg.Config)
client, err := config.CceV3AddonClient(config.GetRegion(d))
if err != nil {
return nil, fmt.Errorf("error creating CCE client: %w", logHttpError(err))
}

addon, err := addons.Get(client, d.Id(), clusterID).Extract()
if err != nil {
if _, ok := err.(golangsdk.ErrDefault404); ok {
d.SetId("")
return nil, fmt.Errorf("addon wasn't found")
}

return nil, fmt.Errorf("error reading CCE addon instance: %w", logHttpError(err))
}

mErr := multierror.Append(nil,
d.Set("name", addon.Metadata.Name),
d.Set("cluster_id", addon.Spec.ClusterID),
d.Set("template_version", addon.Spec.Version),
d.Set("template_name", addon.Spec.AddonTemplateName),
d.Set("description", addon.Spec.Description),
)

if err := mErr.ErrorOrNil(); err != nil {
return nil, fmt.Errorf("error setting addon attributes: %w", err)
}

return []*schema.ResourceData{d}, nil
}

0 comments on commit ece1e60

Please sign in to comment.