From 0516e038132e09f210d343753b8710c51510472e Mon Sep 17 00:00:00 2001 From: squarti Date: Wed, 24 Jan 2024 20:45:42 -0500 Subject: [PATCH 01/34] Terraform support for ICD isolated compute and multitenant cores (#4628) * Terraform support for isolated compute * Support provisioning with host flavor * Add host flavor validation * Update to latest scaling API * Allow cpu/memory scaling with host_flavor=multitenant * Update cloud-databases-SDK * update data source * Update acceptance tests for host flavor scaling * Fix error printing * Enterprise DBs should be on IC https://github.ibm.com/compose/compose/issues/35374 --- .secrets.baseline | 90 +++++++------ go.mod | 2 +- go.sum | 4 +- ibm/flex/structures.go | 39 ++++-- .../database/data_source_ibm_database.go | 35 ++++- ibm/service/database/resource_ibm_database.go | 101 ++++++++++++-- .../resource_ibm_database_edb_test.go | 21 ++- ...bm_database_elasticsearch_platinum_test.go | 126 ++++++------------ ...esource_ibm_database_elasticsearch_test.go | 61 ++++++++- .../resource_ibm_database_etcd_test.go | 12 +- ...ce_ibm_database_mongodb_enterprise_test.go | 52 +++++--- ...urce_ibm_database_mongodb_sharding_test.go | 33 +++-- .../resource_ibm_database_mongodb_test.go | 15 ++- .../resource_ibm_database_mysql_test.go | 6 + .../resource_ibm_database_postgresql_test.go | 42 ++++-- .../resource_ibm_database_rabbitmq_test.go | 15 ++- .../resource_ibm_database_redis_test.go | 37 ++++- website/docs/r/database.html.markdown | 57 ++++++++ 18 files changed, 509 insertions(+), 239 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index 55ab01d30a..403ad68ee7 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "go.mod|go.sum|.*.map|^.secrets.baseline$", "lines": null }, - "generated_at": "2024-01-17T13:22:37Z", + "generated_at": "2024-01-22T15:02:07Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -680,7 +680,7 @@ "hashed_secret": "34f3e72c9e8f331c6c12a39b4ca27d46880ab2cd", "is_secret": false, "is_verified": false, - "line_number": 85, + "line_number": 61, "type": "Secret Keyword", "verified_result": null }, @@ -688,7 +688,7 @@ "hashed_secret": "f4aa5360c26e2a4e2d45e095bd597e84c497fbcd", "is_secret": false, "is_verified": false, - "line_number": 130, + "line_number": 106, "type": "Secret Keyword", "verified_result": null }, @@ -696,7 +696,7 @@ "hashed_secret": "912accc17209bb36cb22d76d430ef9e9ec99dd4c", "is_secret": false, "is_verified": false, - "line_number": 188, + "line_number": 164, "type": "Secret Keyword", "verified_result": null }, @@ -704,7 +704,7 @@ "hashed_secret": "514edd121688f936809a62aecd24419c7eaa772b", "is_secret": false, "is_verified": false, - "line_number": 275, + "line_number": 251, "type": "Secret Keyword", "verified_result": null }, @@ -712,7 +712,7 @@ "hashed_secret": "fa33d07da58b52eee9f13b88e9cda8b98f1c19b6", "is_secret": false, "is_verified": false, - "line_number": 286, + "line_number": 262, "type": "Secret Keyword", "verified_result": null }, @@ -720,7 +720,7 @@ "hashed_secret": "5926151b9a84e25fbc262e88ef6c1d58f0c95548", "is_secret": false, "is_verified": false, - "line_number": 298, + "line_number": 274, "type": "Secret Keyword", "verified_result": null } @@ -760,7 +760,7 @@ "hashed_secret": "731438016c5ab94431f61820f35e3ae5f8ad6004", "is_secret": false, "is_verified": false, - "line_number": 432, + "line_number": 438, "type": "Secret Keyword", "verified_result": null }, @@ -768,7 +768,7 @@ "hashed_secret": "12da2e35d6b50c902c014f1ab9e3032650368df7", "is_secret": false, "is_verified": false, - "line_number": 438, + "line_number": 444, "type": "Secret Keyword", "verified_result": null }, @@ -776,7 +776,7 @@ "hashed_secret": "813274ccae5b6b509379ab56982d862f7b5969b6", "is_secret": false, "is_verified": false, - "line_number": 1161, + "line_number": 1179, "type": "Base64 High Entropy String", "verified_result": null } @@ -846,7 +846,7 @@ "hashed_secret": "da8cae6284528565678de15e03d461e23fe22538", "is_secret": false, "is_verified": false, - "line_number": 1884, + "line_number": 1895, "type": "Secret Keyword", "verified_result": null }, @@ -854,7 +854,7 @@ "hashed_secret": "1a0334cfa65f4be58b9d914b8e96e9d9478bfbac", "is_secret": false, "is_verified": false, - "line_number": 3265, + "line_number": 3276, "type": "Secret Keyword", "verified_result": null } @@ -864,7 +864,7 @@ "hashed_secret": "c8b6f5ef11b9223ac35a5663975a466ebe7ebba9", "is_secret": false, "is_verified": false, - "line_number": 1840, + "line_number": 1842, "type": "Secret Keyword", "verified_result": null }, @@ -872,7 +872,7 @@ "hashed_secret": "8abf4899c01104241510ba87685ad4de76b0c437", "is_secret": false, "is_verified": false, - "line_number": 1846, + "line_number": 1848, "type": "Secret Keyword", "verified_result": null } @@ -2056,7 +2056,7 @@ "hashed_secret": "deab23f996709b4e3d14e5499d1cc2de677bfaa8", "is_secret": false, "is_verified": false, - "line_number": 1372, + "line_number": 1421, "type": "Secret Keyword", "verified_result": null }, @@ -2064,7 +2064,7 @@ "hashed_secret": "20a25bac21219ffff1904bde871ded4027eca2f8", "is_secret": false, "is_verified": false, - "line_number": 1962, + "line_number": 2017, "type": "Secret Keyword", "verified_result": null }, @@ -2072,7 +2072,7 @@ "hashed_secret": "b732fb611fd46a38e8667f9972e0cde777fbe37f", "is_secret": false, "is_verified": false, - "line_number": 1981, + "line_number": 2036, "type": "Secret Keyword", "verified_result": null }, @@ -2080,7 +2080,7 @@ "hashed_secret": "1f5e25be9b575e9f5d39c82dfd1d9f4d73f1975c", "is_secret": false, "is_verified": false, - "line_number": 2194, + "line_number": 2249, "type": "Secret Keyword", "verified_result": null } @@ -2100,7 +2100,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 205, + "line_number": 202, "type": "Secret Keyword", "verified_result": null } @@ -2110,7 +2110,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 823, + "line_number": 784, "type": "Secret Keyword", "verified_result": null } @@ -2120,7 +2120,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 778, + "line_number": 832, "type": "Secret Keyword", "verified_result": null } @@ -2130,7 +2130,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 213, + "line_number": 216, "type": "Secret Keyword", "verified_result": null } @@ -2140,7 +2140,7 @@ "hashed_secret": "8cbbbfad0206e5953901f679b0d26d583c4f5ffe", "is_secret": false, "is_verified": false, - "line_number": 271, + "line_number": 268, "type": "Secret Keyword", "verified_result": null }, @@ -2148,7 +2148,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 336, + "line_number": 333, "type": "Secret Keyword", "verified_result": null } @@ -2158,7 +2158,7 @@ "hashed_secret": "5667b8489a17faa9ef54941db31ed762be280bec", "is_secret": false, "is_verified": false, - "line_number": 157, + "line_number": 154, "type": "Secret Keyword", "verified_result": null }, @@ -2166,7 +2166,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 189, + "line_number": 186, "type": "Secret Keyword", "verified_result": null } @@ -2176,7 +2176,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 214, + "line_number": 220, "type": "Secret Keyword", "verified_result": null } @@ -2186,7 +2186,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 150, + "line_number": 156, "type": "Secret Keyword", "verified_result": null } @@ -2196,7 +2196,7 @@ "hashed_secret": "728e83f156932be9b1dc48a5c3f7a3bfbeeb08ce", "is_secret": false, "is_verified": false, - "line_number": 490, + "line_number": 496, "type": "Secret Keyword", "verified_result": null }, @@ -2204,7 +2204,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 658, + "line_number": 673, "type": "Secret Keyword", "verified_result": null } @@ -2214,7 +2214,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 223, + "line_number": 229, "type": "Secret Keyword", "verified_result": null } @@ -2224,7 +2224,7 @@ "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 273, + "line_number": 282, "type": "Secret Keyword", "verified_result": null }, @@ -2232,7 +2232,7 @@ "hashed_secret": "44cdfc3615970ada14420caaaa5c5745fca06002", "is_secret": false, "is_verified": false, - "line_number": 277, + "line_number": 300, "type": "Secret Keyword", "verified_result": null } @@ -2840,7 +2840,7 @@ "hashed_secret": "b732fb611fd46a38e8667f9972e0cde777fbe37f", "is_secret": false, "is_verified": false, - "line_number": 1326, + "line_number": 1154, "type": "Secret Keyword", "verified_result": null } @@ -2964,7 +2964,7 @@ "hashed_secret": "92f08f2d9a0dc3f0d4cb3796435a48508cf59ecd", "is_secret": false, "is_verified": false, - "line_number": 1115, + "line_number": 1107, "type": "Secret Keyword", "verified_result": null } @@ -2992,7 +2992,7 @@ "hashed_secret": "92f08f2d9a0dc3f0d4cb3796435a48508cf59ecd", "is_secret": false, "is_verified": false, - "line_number": 513, + "line_number": 509, "type": "Secret Keyword", "verified_result": null } @@ -3138,7 +3138,7 @@ "hashed_secret": "09c0dfbba1f2b2576cfbac116e13b0258bc26bfa", "is_secret": false, "is_verified": false, - "line_number": 468, + "line_number": 470, "type": "Secret Keyword", "verified_result": null }, @@ -3146,7 +3146,7 @@ "hashed_secret": "d282ab8a33d987146dda0381b4effdf2d91c0d65", "is_secret": false, "is_verified": false, - "line_number": 474, + "line_number": 476, "type": "Secret Keyword", "verified_result": null } @@ -4364,11 +4364,19 @@ } ], "website/docs/r/database.html.markdown": [ + { + "hashed_secret": "10c28f9cf0668595d45c1090a7b4a2ae98edfa58", + "is_secret": false, + "is_verified": false, + "line_number": 153, + "type": "Secret Keyword", + "verified_result": null + }, { "hashed_secret": "2317aa72dafa0a07f05af47baa2e388f95dcf6f3", "is_secret": false, "is_verified": false, - "line_number": 494, + "line_number": 541, "type": "Secret Keyword", "verified_result": null }, @@ -4376,7 +4384,7 @@ "hashed_secret": "ddf75a48487b387b1dc328ac0a942377b377c556", "is_secret": false, "is_verified": false, - "line_number": 559, + "line_number": 606, "type": "Secret Keyword", "verified_result": null }, @@ -4384,7 +4392,7 @@ "hashed_secret": "91199272d5d6a574a51722ca6f3d1148edb1a0e7", "is_secret": false, "is_verified": false, - "line_number": 583, + "line_number": 630, "type": "Secret Keyword", "verified_result": null } diff --git a/go.mod b/go.mod index d02322cdc7..8089e8fc48 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/IBM/apigateway-go-sdk v0.0.0-20210714141226-a5d5d49caaca github.com/IBM/appconfiguration-go-admin-sdk v0.3.0 github.com/IBM/appid-management-go-sdk v0.0.0-20210908164609-dd0e0eaf732f - github.com/IBM/cloud-databases-go-sdk v0.4.0 + github.com/IBM/cloud-databases-go-sdk v0.5.0 github.com/IBM/cloudant-go-sdk v0.0.43 github.com/IBM/code-engine-go-sdk v0.0.0-20231106200405-99e81b3ee752 github.com/IBM/container-registry-go-sdk v1.1.0 diff --git a/go.sum b/go.sum index 9b6a3445fb..879f6f18a0 100644 --- a/go.sum +++ b/go.sum @@ -116,8 +116,8 @@ github.com/IBM/appconfiguration-go-admin-sdk v0.3.0 h1:OqFxnDxro0JiRwHBKytCcseY2 github.com/IBM/appconfiguration-go-admin-sdk v0.3.0/go.mod h1:xPxAYhr/uywUIDEo/JqWbkUdTryPdzRdYBfUpA5IjoE= github.com/IBM/appid-management-go-sdk v0.0.0-20210908164609-dd0e0eaf732f h1:4c1kqY4GqmkQ+tO03rneDb74Tv7BhTj8jDiDB1p8mdM= github.com/IBM/appid-management-go-sdk v0.0.0-20210908164609-dd0e0eaf732f/go.mod h1:d22kTYY7RYBWcQlZpqrSdshpB/lJ16viWS5Sbjtlc8s= -github.com/IBM/cloud-databases-go-sdk v0.4.0 h1:pmmMbJb/axolBEpCqq85idcZiimAOTacCyLUfAhXCqI= -github.com/IBM/cloud-databases-go-sdk v0.4.0/go.mod h1:nCIVfeZnhBYIiwByT959dFP4VWUeNLxomDYy63tTC6M= +github.com/IBM/cloud-databases-go-sdk v0.5.0 h1:Bie6MnT1jLchQmtKVA20HHETTPdlOR+i11P2kJ55viM= +github.com/IBM/cloud-databases-go-sdk v0.5.0/go.mod h1:nCIVfeZnhBYIiwByT959dFP4VWUeNLxomDYy63tTC6M= github.com/IBM/cloudant-go-sdk v0.0.43 h1:YxTy4RpAEezX32YIWnds76hrBREmO4u6IkBz1WylNuQ= github.com/IBM/cloudant-go-sdk v0.0.43/go.mod h1:WeYrJPaHTw19943ndWnVfwMIlZ5z0XUM2uEXNBrwZ1M= github.com/IBM/code-engine-go-sdk v0.0.0-20231106200405-99e81b3ee752 h1:S5NT0aKKUqd9hnIrPN/qUijKx9cZjJi3kfFpog0ByDA= diff --git a/ibm/flex/structures.go b/ibm/flex/structures.go index 50dc935f2f..3429894e39 100644 --- a/ibm/flex/structures.go +++ b/ibm/flex/structures.go @@ -561,9 +561,9 @@ func FlattenVlans(list []containerv1.Vlan) []map[string]interface{} { return vlans } -func FlattenIcdGroups(grouplist icdv4.GroupList) []map[string]interface{} { - groups := make([]map[string]interface{}, len(grouplist.Groups)) - for i, group := range grouplist.Groups { +func FlattenIcdGroups(groupResponse *clouddatabasesv5.ListDeploymentScalingGroupsResponse) []map[string]interface{} { + groups := make([]map[string]interface{}, len(groupResponse.Groups)) + for i, group := range groupResponse.Groups { memorys := make([]map[string]interface{}, 1) memory := make(map[string]interface{}) memory["units"] = group.Memory.Units @@ -576,12 +576,12 @@ func FlattenIcdGroups(grouplist icdv4.GroupList) []map[string]interface{} { cpus := make([]map[string]interface{}, 1) cpu := make(map[string]interface{}) - cpu["units"] = group.Cpu.Units - cpu["allocation_count"] = group.Cpu.AllocationCount - cpu["minimum_count"] = group.Cpu.MinimumCount - cpu["step_size_count"] = group.Cpu.StepSizeCount - cpu["is_adjustable"] = group.Cpu.IsAdjustable - cpu["can_scale_down"] = group.Cpu.CanScaleDown + cpu["units"] = group.CPU.Units + cpu["allocation_count"] = group.CPU.AllocationCount + cpu["minimum_count"] = group.CPU.MinimumCount + cpu["step_size_count"] = group.CPU.StepSizeCount + cpu["is_adjustable"] = group.CPU.IsAdjustable + cpu["can_scale_down"] = group.CPU.CanScaleDown cpus[0] = cpu disks := make([]map[string]interface{}, 1) @@ -594,12 +594,23 @@ func FlattenIcdGroups(grouplist icdv4.GroupList) []map[string]interface{} { disk["can_scale_down"] = group.Disk.CanScaleDown disks[0] = disk + hostflavors := make([]map[string]interface{}, 0) + if group.HostFlavor != nil { + hostflavors = make([]map[string]interface{}, 1) + hostflavor := make(map[string]interface{}) + hostflavor["id"] = group.HostFlavor.ID + hostflavor["name"] = group.HostFlavor.Name + hostflavor["hosting_size"] = group.HostFlavor.HostingSize + hostflavors[0] = hostflavor + } + l := map[string]interface{}{ - "group_id": group.Id, - "count": group.Count, - "memory": memorys, - "cpu": cpus, - "disk": disks, + "group_id": group.ID, + "count": group.Count, + "memory": memorys, + "cpu": cpus, + "disk": disks, + "host_flavor": hostflavors, } groups[i] = l } diff --git a/ibm/service/database/data_source_ibm_database.go b/ibm/service/database/data_source_ibm_database.go index be79a83bf2..2ab901252f 100644 --- a/ibm/service/database/data_source_ibm_database.go +++ b/ibm/service/database/data_source_ibm_database.go @@ -280,6 +280,29 @@ func DataSourceIBMDatabaseInstance() *schema.Resource { }, }, }, + "host_flavor": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + Description: "The host flavor id", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "The host flavor name", + }, + "hosting_size": { + Type: schema.TypeString, + Computed: true, + Description: "The host flavor size", + }, + }, + }, + }, }, }, }, @@ -624,12 +647,6 @@ func dataSourceIBMDatabaseInstanceRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("[ERROR] Error getting database client settings: %s", err) } - icdClient, err := meta.(conns.ClientSession).ICDAPI() - if err != nil { - return fmt.Errorf("[ERROR] Error getting database client settings: %s", err) - } - - icdId := flex.EscapeUrlParm(instance.ID) getDeploymentInfoOptions := &clouddatabasesv5.GetDeploymentInfoOptions{ ID: core.StringPtr(instance.ID), } @@ -651,7 +668,11 @@ func dataSourceIBMDatabaseInstanceRead(d *schema.ResourceData, meta interface{}) d.Set("platform_options", flex.ExpandPlatformOptions(*deployment)) } - groupList, err := icdClient.Groups().GetGroups(icdId) + listDeploymentScalingGroupsOptions := &clouddatabasesv5.ListDeploymentScalingGroupsOptions{ + ID: core.StringPtr(instance.ID), + } + + groupList, _, err := cloudDatabasesClient.ListDeploymentScalingGroups(listDeploymentScalingGroupsOptions) if err != nil { return fmt.Errorf("[ERROR] Error getting database groups: %s", err) } diff --git a/ibm/service/database/resource_ibm_database.go b/ibm/service/database/resource_ibm_database.go index e554580a2a..180823b07f 100644 --- a/ibm/service/database/resource_ibm_database.go +++ b/ibm/service/database/resource_ibm_database.go @@ -530,6 +530,19 @@ func ResourceIBMDatabaseInstance() *schema.Resource { }, }, }, + "host_flavor": { + Optional: true, + Type: schema.TypeSet, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, }, }, }, @@ -662,6 +675,29 @@ func ResourceIBMDatabaseInstance() *schema.Resource { }, }, }, + "host_flavor": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + Description: "The host flavor id", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "The host flavor name", + }, + "hosting_size": { + Type: schema.TypeString, + Computed: true, + Description: "The host flavor size", + }, + }, + }, + }, }, }, }, @@ -931,6 +967,7 @@ type Params struct { Memory int `json:"members_memory_allocation_mb,omitempty"` Disk int `json:"members_disk_allocation_mb,omitempty"` CPU int `json:"members_cpu_allocation_count,omitempty"` + HostFlavor string `json:"members_host_flavor,omitempty"` KeyProtectInstance string `json:"disk_encryption_instance_crn,omitempty"` ServiceEndpoints string `json:"service-endpoints,omitempty"` BackupID string `json:"backup-id,omitempty"` @@ -941,11 +978,12 @@ type Params struct { } type Group struct { - ID string - Members *GroupResource - Memory *GroupResource - Disk *GroupResource - CPU *GroupResource + ID string + Members *GroupResource + Memory *GroupResource + Disk *GroupResource + CPU *GroupResource + HostFlavor *HostFlavorGroupResource } type GroupResource struct { @@ -959,6 +997,10 @@ type GroupResource struct { CanScaleDown bool } +type HostFlavorGroupResource struct { + ID string +} + func getDefaultScalingGroups(_service string, _plan string, meta interface{}) (groups []clouddatabasesv5.Group, err error) { cloudDatabasesClient, err := meta.(conns.ClientSession).CloudDatabasesV5() if err != nil { @@ -1212,6 +1254,10 @@ func resourceIBMDatabaseInstanceCreate(context context.Context, d *schema.Resour if memberGroup.CPU != nil { params.CPU = memberGroup.CPU.Allocation * initialNodeCount } + + if memberGroup.HostFlavor != nil { + params.HostFlavor = memberGroup.HostFlavor.ID + } } } if version, ok := d.GetOk("version"); ok { @@ -1316,8 +1362,11 @@ func resourceIBMDatabaseInstanceCreate(context context.Context, d *schema.Resour if g.CPU != nil && g.CPU.Allocation*nodeCount != currentGroup.CPU.Allocation { groupScaling.CPU = &clouddatabasesv5.GroupScalingCPU{AllocationCount: core.Int64Ptr(int64(g.CPU.Allocation * nodeCount))} } + if g.HostFlavor != nil && g.HostFlavor.ID != currentGroup.HostFlavor.ID { + groupScaling.HostFlavor = &clouddatabasesv5.GroupScalingHostFlavor{ID: core.StringPtr(g.HostFlavor.ID)} + } - if groupScaling.Members != nil || groupScaling.Memory != nil || groupScaling.Disk != nil || groupScaling.CPU != nil { + if groupScaling.Members != nil || groupScaling.Memory != nil || groupScaling.Disk != nil || groupScaling.CPU != nil || groupScaling.HostFlavor != nil { setDeploymentScalingGroupOptions := &clouddatabasesv5.SetDeploymentScalingGroupOptions{ ID: instance.ID, GroupID: &g.ID, @@ -1669,11 +1718,14 @@ func resourceIBMDatabaseInstanceRead(context context.Context, d *schema.Resource d.Set("adminuser", deployment.AdminUsernames["database"]) d.Set("version", deployment.Version) - groupList, err := icdClient.Groups().GetGroups(icdId) + listDeploymentScalingGroupsOptions := &clouddatabasesv5.ListDeploymentScalingGroupsOptions{ + ID: core.StringPtr(instanceID), + } + groupList, _, err := cloudDatabasesClient.ListDeploymentScalingGroups(listDeploymentScalingGroupsOptions) if err != nil { return diag.FromErr(fmt.Errorf("[ERROR] Error getting database groups: %s", err)) } - if groupList.Groups[0].Members.AllocationCount == 0 { + if len(groupList.Groups) == 0 || groupList.Groups[0].Members == nil || groupList.Groups[0].Members.AllocationCount == nil || *groupList.Groups[0].Members.AllocationCount == 0 { return diag.FromErr(fmt.Errorf("[ERROR] This database appears to have have 0 members. Unable to proceed")) } @@ -1882,8 +1934,11 @@ func resourceIBMDatabaseInstanceUpdate(context context.Context, d *schema.Resour if group.CPU != nil && group.CPU.Allocation*nodeCount != currentGroup.CPU.Allocation { groupScaling.CPU = &clouddatabasesv5.GroupScalingCPU{AllocationCount: core.Int64Ptr(int64(group.CPU.Allocation * nodeCount))} } + if group.HostFlavor != nil && group.HostFlavor.ID != currentGroup.HostFlavor.ID { + groupScaling.HostFlavor = &clouddatabasesv5.GroupScalingHostFlavor{ID: core.StringPtr(group.HostFlavor.ID)} + } - if groupScaling.Members != nil || groupScaling.Memory != nil || groupScaling.Disk != nil || groupScaling.CPU != nil { + if groupScaling.Members != nil || groupScaling.Memory != nil || groupScaling.Disk != nil || groupScaling.CPU != nil || groupScaling.HostFlavor != nil { setDeploymentScalingGroupOptions := &clouddatabasesv5.SetDeploymentScalingGroupOptions{ ID: &instanceID, GroupID: &group.ID, @@ -2295,7 +2350,7 @@ func waitForICDReady(meta interface{}, instanceID string) error { if apiErr, ok := err.(bmxerror.RequestFailure); ok && apiErr.StatusCode() == 404 { return fmt.Errorf("[ERROR] The database instance was not found in the region set for the Provider, or the default of us-south. Specify the correct region in the provider definition, or create a provider alias for the correct region. %v", err) } - return fmt.Errorf("[ERROR] Error getting database config for: %s with error %s\n", icdId, err) + return fmt.Errorf("[ERROR] Error getting database config for: %s with error %s\n", icdId, cdbErr) } return nil }) @@ -2679,6 +2734,11 @@ func normalizeGroups(_groups []clouddatabasesv5.Group) (groups []Group) { CanScaleDown: *g.CPU.CanScaleDown, } + group.HostFlavor = &HostFlavorGroupResource{} + if g.HostFlavor != nil { + group.HostFlavor.ID = *g.HostFlavor.ID + } + groups = append(groups, group) } @@ -2724,6 +2784,13 @@ func expandGroups(_groups []interface{}) []*Group { } } + if hostflavorSet, ok := tfGroup["host_flavor"].(*schema.Set); ok { + hostflavor := hostflavorSet.List() + if len(hostflavor) != 0 { + group.HostFlavor = &HostFlavorGroupResource{ID: hostflavor[0].(map[string]interface{})["id"].(string)} + } + } + groups = append(groups, &group) } } @@ -2763,6 +2830,13 @@ func validateGroupScaling(groupId string, resourceName string, value int, resour return nil } +func validateGroupHostFlavor(groupId string, resourceName string, group *Group) error { + if group.CPU != nil || group.Memory != nil { + return fmt.Errorf("%s must not be set with cpu and memory", resourceName) + } + return nil +} + func validateGroupsDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) (err error) { instanceID := diff.Id() service := diff.Get("service").(string) @@ -2825,6 +2899,13 @@ func validateGroupsDiff(_ context.Context, diff *schema.ResourceDiff, meta inter } } + if group.HostFlavor != nil && group.HostFlavor.ID != "" && group.HostFlavor.ID != "multitenant" { + err = validateGroupHostFlavor(groupId, "host_flavor", group) + if err != nil { + return err + } + } + if group.Memory != nil { err = validateGroupScaling(groupId, "memory", group.Memory.Allocation, groupDefaults.Memory, nodeCount) if err != nil { diff --git a/ibm/service/database/resource_ibm_database_edb_test.go b/ibm/service/database/resource_ibm_database_edb_test.go index f4ec044be2..b4a7d149d9 100644 --- a/ibm/service/database/resource_ibm_database_edb_test.go +++ b/ibm/service/database/resource_ibm_database_edb_test.go @@ -36,7 +36,7 @@ func TestAccIBMEDBDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "adminuser", "admin"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "61440"), resource.TestCheckResourceAttr(name, "service_endpoints", "public"), resource.TestCheckResourceAttr(name, "allowlist.#", "1"), @@ -56,7 +56,7 @@ func TestAccIBMEDBDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-enterprisedb"), resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "6144"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "98304"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "92160"), resource.TestCheckResourceAttr(name, "service_endpoints", "public-and-private"), resource.TestCheckResourceAttr(name, "allowlist.#", "2"), @@ -79,7 +79,7 @@ func TestAccIBMEDBDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-enterprisedb"), resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "92160"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), @@ -113,8 +113,8 @@ func testAccCheckIBMDatabaseInstanceEDBBasic(databaseResourceGroup string, name adminpassword = "password12345678" group { group_id = "member" - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 20480 @@ -153,15 +153,12 @@ func testAccCheckIBMDatabaseInstanceEDBFullyspecified(databaseResourceGroup stri adminpassword = "password12345678" group { group_id = "member" - memory { - allocation_mb = 2048 + host_flavor { + id = "b3c.8x32.encrypted" } disk { allocation_mb = 30720 } - cpu { - allocation_count = 4 - } } service_endpoints = "public-and-private" tags = ["one:two"] @@ -205,8 +202,8 @@ func testAccCheckIBMDatabaseInstanceEDBReduced(databaseResourceGroup string, nam adminpassword = "password12345678" group { group_id = "member" - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 30720 diff --git a/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go b/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go index 114400145f..14c18b201d 100644 --- a/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go +++ b/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go @@ -65,7 +65,7 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Basic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "18432"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), @@ -80,7 +80,7 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Basic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "18432"), resource.TestCheckResourceAttr(name, "whitelist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), @@ -118,10 +118,6 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Node(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "adminuser", "admin"), - resource.TestCheckResourceAttr(name, "node_count", "3"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "5120"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "allowlist.#", "1"), resource.TestCheckResourceAttr(name, "users.#", "1"), @@ -139,10 +135,6 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Node(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "node_count", "3"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "6144"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "allowlist.#", "2"), resource.TestCheckResourceAttr(name, "users.#", "2"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "3"), @@ -157,10 +149,6 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Node(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "node_count", "3"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "6144"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), @@ -174,10 +162,6 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Node(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "node_count", "4"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "6144"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), @@ -214,10 +198,6 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Group(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "adminuser", "admin"), - resource.TestCheckResourceAttr(name, "node_count", "3"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "5120"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "allowlist.#", "1"), resource.TestCheckResourceAttr(name, "users.#", "1"), @@ -235,14 +215,10 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Group(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "node_count", "3"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "6144"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "groups.0.count", "3"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "18432"), - resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "9"), + resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "12"), resource.TestCheckResourceAttr(name, "allowlist.#", "2"), resource.TestCheckResourceAttr(name, "users.#", "2"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "3"), @@ -257,14 +233,10 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Group(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "node_count", "3"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "6144"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "groups.0.count", "3"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "18432"), - resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "9"), + resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "12"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), @@ -278,14 +250,10 @@ func TestAccIBMDatabaseInstance_ElasticsearchPlatinum_Group(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "platinum"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "node_count", "4"), - resource.TestCheckResourceAttr(name, "node_memory_allocation_mb", "1024"), - resource.TestCheckResourceAttr(name, "node_disk_allocation_mb", "6144"), - resource.TestCheckResourceAttr(name, "node_cpu_allocation_count", "3"), resource.TestCheckResourceAttr(name, "groups.0.count", "4"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "4096"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "65536"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "24576"), - resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "12"), + resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "16"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), @@ -355,8 +323,8 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumBasic(databaseResourceG group { group_id = "member" - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 @@ -394,6 +362,13 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumFullyspecified(database plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + group { + group_id = "member" + + host_flavor { + id = "b3c.4x16.encrypted" + } + } users { name = "user123" password = "password12345678" @@ -435,6 +410,13 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumReduced(databaseResourc plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + group { + group_id = "member" + + host_flavor { + id = "b3c.4x16.encrypted" + } + } timeouts { create = "120m" @@ -463,8 +445,8 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupMigration(database group { group_id = "member" - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 @@ -499,15 +481,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeBasic(databaseResou members { allocation_count = 3 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 5120 } - cpu { - allocation_count = 3 - } } users { @@ -547,15 +526,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeFullyspecified(data members { allocation_count = 3 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 } - cpu { - allocation_count = 3 - } } users { name = "user123" @@ -602,15 +578,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeReduced(databaseRes members { allocation_count = 3 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 } - cpu { - allocation_count = 3 - } } timeouts { @@ -641,15 +614,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeScaleOut(databaseRe members { allocation_count = 4 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 } - cpu { - allocation_count = 3 - } } timeouts { @@ -681,15 +651,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupBasic(databaseReso members { allocation_count = 3 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 5120 } - cpu { - allocation_count = 3 - } } users { @@ -730,15 +697,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupFullyspecified(dat members { allocation_count = 3 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 } - cpu { - allocation_count = 3 - } } users { name = "user123" @@ -787,15 +751,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupReduced(databaseRe members { allocation_count = 3 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 } - cpu { - allocation_count = 3 - } } timeouts { @@ -827,15 +788,12 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupScaleOut(databaseR members { allocation_count = 4 } - memory { - allocation_mb = 1024 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 6144 } - cpu { - allocation_count = 3 - } } timeouts { create = "120m" diff --git a/ibm/service/database/resource_ibm_database_elasticsearch_test.go b/ibm/service/database/resource_ibm_database_elasticsearch_test.go index 2a6059f36a..213463b0ee 100644 --- a/ibm/service/database/resource_ibm_database_elasticsearch_test.go +++ b/ibm/service/database/resource_ibm_database_elasticsearch_test.go @@ -78,7 +78,7 @@ func TestAccIBMDatabaseInstance_Elasticsearch_Basic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-elasticsearch"), resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "6144"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "18432"), resource.TestCheckResourceAttr(name, "users.#", "0"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), @@ -326,6 +326,16 @@ func testAccCheckIBMDatabaseInstanceElasticsearchBasic(databaseResourceGroup str description = "desc1" } + group { + group_id = "member" + memory { + allocation_mb = 2048 + } + host_flavor { + id = "multitenant" + } + } + timeouts { create = "120m" update = "120m" @@ -366,6 +376,16 @@ func testAccCheckIBMDatabaseInstanceElasticsearchFullyspecified(databaseResource description = "desc" } + group { + group_id = "member" + memory { + allocation_mb = 2048 + } + host_flavor { + id = "multitenant" + } + } + timeouts { create = "120m" update = "120m" @@ -391,6 +411,16 @@ func testAccCheckIBMDatabaseInstanceElasticsearchReduced(databaseResourceGroup s location = "%[3]s" adminpassword = "password12345678" + group { + group_id = "member" + memory { + allocation_mb = 2048 + } + host_flavor { + id = "multitenant" + } + } + timeouts { create = "120m" update = "120m" @@ -419,7 +449,10 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupMigration(databaseResource group_id = "member" memory { - allocation_mb = 1024 + allocation_mb = 2048 + } + host_flavor { + id = "multitenant" } disk { allocation_mb = 6144 @@ -464,6 +497,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeBasic(databaseResourceGroup cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } users { name = "user123" @@ -511,6 +547,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeFullyspecified(databaseReso cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } users { name = "user123" @@ -566,6 +605,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeReduced(databaseResourceGro cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } timeouts { @@ -605,6 +647,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeScaleOut(databaseResourceGr cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } timeouts { @@ -645,6 +690,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupBasic(databaseResourceGrou cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } users { @@ -694,6 +742,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupFullyspecified(databaseRes cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } users { name = "user123" @@ -751,6 +802,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupReduced(databaseResourceGr cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } timeouts { @@ -791,6 +845,9 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupScaleOut(databaseResourceG cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } timeouts { create = "120m" diff --git a/ibm/service/database/resource_ibm_database_etcd_test.go b/ibm/service/database/resource_ibm_database_etcd_test.go index 07e2eea5e6..b289705b93 100644 --- a/ibm/service/database/resource_ibm_database_etcd_test.go +++ b/ibm/service/database/resource_ibm_database_etcd_test.go @@ -55,7 +55,7 @@ func TestAccIBMDatabaseInstance_Etcd_Basic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-etcd"), resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "18432"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "193536"), resource.TestCheckResourceAttr(name, "allowlist.#", "2"), resource.TestCheckResourceAttr(name, "users.#", "2"), @@ -137,6 +137,9 @@ func testAccCheckIBMDatabaseInstanceEtcdBasic(databaseResourceGroup string, name memory { allocation_mb = 3072 } + host_flavor { + id = "multitenant" + } disk { allocation_mb = 61440 } @@ -169,8 +172,8 @@ func testAccCheckIBMDatabaseInstanceEtcdFullyspecified(databaseResourceGroup str adminpassword = "password12345678" group { group_id = "member" - memory { - allocation_mb = 6144 + host_flavor { + id = "b3c.4x16.encrypted" } disk { allocation_mb = 64512 @@ -216,6 +219,9 @@ func testAccCheckIBMDatabaseInstanceEtcdReduced(databaseResourceGroup string, na memory { allocation_mb = 3072 } + host_flavor { + id = "multitenant" + } disk { allocation_mb = 64512 } diff --git a/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go b/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go index d3ed077681..b9642cb1b1 100644 --- a/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go +++ b/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go @@ -37,7 +37,7 @@ func TestAccIBMMongoDBEnterpriseDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "adminuser", "admin"), resource.TestCheckResourceAttr(name, "service_endpoints", "public"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "43008"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "61440"), resource.TestCheckResourceAttr(name, "allowlist.#", "1"), resource.TestCheckResourceAttr(name, "users.#", "1"), @@ -57,7 +57,7 @@ func TestAccIBMMongoDBEnterpriseDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "enterprise"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "service_endpoints", "public"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "86016"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "98304"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "122880"), resource.TestCheckResourceAttr(name, "allowlist.#", "2"), resource.TestCheckResourceAttr(name, "users.#", "2"), @@ -81,7 +81,7 @@ func TestAccIBMMongoDBEnterpriseDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "enterprise"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "43008"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "122880"), resource.TestCheckResourceAttr(name, "users.#", "0"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), @@ -122,7 +122,7 @@ func TestAccIBMMongoDBEnterpriseDatabaseInstanceGroupBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "adminuser", "admin"), resource.TestCheckResourceAttr(name, "service_endpoints", "public"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "43008"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "49152"), resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "61440"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), resource.TestCheckResourceAttr(name, "connectionstrings.0.name", "admin"), @@ -210,10 +210,10 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseBasic(databaseResourceGroup tags = ["one:two"] group { group_id = "member" - memory { - allocation_mb = 14336 + host_flavor { + id = "b3c.4x16.encrypted" } - disk { + disk { allocation_mb = 20480 } } @@ -251,15 +251,12 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseFullyspecified(databaseReso tags = ["one:two"] group { group_id = "member" - memory { - allocation_mb = 28672 + host_flavor { + id = "b3c.8x32.encrypted" } - disk { + disk { allocation_mb = 40960 } - cpu { - allocation_count = 9 - } } users { name = "user123" @@ -305,10 +302,10 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseReduced(databaseResourceGro tags = ["one:two"] group { group_id = "member" - memory { - allocation_mb = 14336 + host_flavor { + id = "b3c.4x16.encrypted" } - disk { + disk { allocation_mb = 40960 } } @@ -339,10 +336,10 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseGroupBasic(databaseResource group { group_id = "member" - memory { - allocation_mb = 14336 + host_flavor { + id = "b3c.4x16.encrypted" } - disk { + disk { allocation_mb = 20480 } } @@ -385,6 +382,13 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseMinimal(databaseResourceGro plan = "enterprise" location = "%[3]s" + group { + group_id = "member" + + host_flavor { + id = "b3c.4x16.encrypted" + } + } timeouts { create = "4h" update = "4h" @@ -412,7 +416,15 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseMinimal_PITR(databaseResour location = "%[3]s" point_in_time_recovery_deployment_id = ibm_database.%[2]s.id point_in_time_recovery_time = "" - offline_restore = true + offline_restore = true + + group { + group_id = "member" + + host_flavor { + id = "b3c.4x16.encrypted" + } + } timeouts { create = "4h" diff --git a/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go b/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go index 1cce4bc9a4..20b90c13a5 100644 --- a/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go +++ b/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go @@ -36,8 +36,8 @@ func TestAccIBMMongoDBShardingDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "enterprise-sharding"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "adminuser", "admin"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "43008"), - resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "61440"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "98304"), + resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "122880"), resource.TestCheckResourceAttr(name, "allowlist.#", "1"), resource.TestCheckResourceAttr(name, "users.#", "1"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "2"), @@ -54,8 +54,8 @@ func TestAccIBMMongoDBShardingDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-mongodb"), resource.TestCheckResourceAttr(name, "plan", "enterprise-sharding"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "86016"), - resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "122880"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "196608"), + resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "245760"), resource.TestCheckResourceAttr(name, "allowlist.#", "2"), resource.TestCheckResourceAttr(name, "users.#", "2"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "3"), @@ -71,8 +71,8 @@ func TestAccIBMMongoDBShardingDatabaseInstanceBasic(t *testing.T) { resource.TestCheckResourceAttr(name, "service", "databases-for-mongodb"), resource.TestCheckResourceAttr(name, "plan", "enterprise-sharding"), resource.TestCheckResourceAttr(name, "location", acc.Region()), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "43008"), - resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "122880"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "98304"), + resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "245760"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), resource.TestCheckResourceAttr(name, "connectionstrings.#", "1"), @@ -97,10 +97,10 @@ func testAccCheckIBMDatabaseInstanceMongoDBShardingBasic(databaseResourceGroup s adminpassword = "password12345678" group { group_id = "member" - memory { - allocation_mb = 14336 + host_flavor { + id = "b3c.4x16.encrypted" } - disk { + disk { allocation_mb = 20480 } } @@ -137,15 +137,12 @@ func testAccCheckIBMDatabaseInstanceMongoDBShardingFullyspecified(databaseResour adminpassword = "password12345678" group { group_id = "member" - memory { - allocation_mb = 28672 + host_flavor { + id = "b3c.8x32.encrypted" } - disk { + disk { allocation_mb = 40960 } - cpu { - allocation_count = 9 - } } users { name = "user123" @@ -189,10 +186,10 @@ func testAccCheckIBMDatabaseInstanceMongoDBShardingReduced(databaseResourceGroup adminpassword = "password12345678" group { group_id = "member" - memory { - allocation_mb = 14336 + host_flavor { + id = "b3c.4x16.encrypted" } - disk { + disk { allocation_mb = 40960 } } diff --git a/ibm/service/database/resource_ibm_database_mongodb_test.go b/ibm/service/database/resource_ibm_database_mongodb_test.go index 81fd0cd1f7..83e6e2266d 100644 --- a/ibm/service/database/resource_ibm_database_mongodb_test.go +++ b/ibm/service/database/resource_ibm_database_mongodb_test.go @@ -141,7 +141,10 @@ func testAccCheckIBMDatabaseInstanceMongodbBasic(databaseResourceGroup string, n memory { allocation_mb = 1024 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 10240 } } @@ -175,7 +178,10 @@ func testAccCheckIBMDatabaseInstanceMongodbFullyspecified(databaseResourceGroup memory { allocation_mb = 2048 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 10240 } } @@ -217,7 +223,10 @@ func testAccCheckIBMDatabaseInstanceMongodbReduced(databaseResourceGroup string, memory { allocation_mb = 1024 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 10240 } } diff --git a/ibm/service/database/resource_ibm_database_mysql_test.go b/ibm/service/database/resource_ibm_database_mysql_test.go index ddb33d5ffe..eb5030098b 100644 --- a/ibm/service/database/resource_ibm_database_mysql_test.go +++ b/ibm/service/database/resource_ibm_database_mysql_test.go @@ -92,6 +92,9 @@ func testAccCheckIBMDatabaseInstanceMysqlBasic(databaseResourceGroup string, nam memory { allocation_mb = 1024 } + host_flavor { + id = "multitenant" + } disk { allocation_mb = 20480 } @@ -138,6 +141,9 @@ func testAccCheckIBMDatabaseInstanceMysqlFullyspecified(databaseResourceGroup st cpu { allocation_count = 4 } + host_flavor { + id = "multitenant" + } } service_endpoints = "public-and-private" tags = ["one:two"] diff --git a/ibm/service/database/resource_ibm_database_postgresql_test.go b/ibm/service/database/resource_ibm_database_postgresql_test.go index dc34b287c4..a75ee7fa40 100644 --- a/ibm/service/database/resource_ibm_database_postgresql_test.go +++ b/ibm/service/database/resource_ibm_database_postgresql_test.go @@ -127,8 +127,8 @@ func TestAccIBMDatabaseInstancePostgresGroup(t *testing.T) { resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "adminuser", "admin"), resource.TestCheckResourceAttr(name, "groups.0.count", "2"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "4096"), - resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "20480"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "2048"), + resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "10240"), resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "6"), resource.TestCheckResourceAttr(name, "service_endpoints", "public"), resource.TestCheckResourceAttr(name, "allowlist.#", "1"), @@ -149,8 +149,8 @@ func TestAccIBMDatabaseInstancePostgresGroup(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "groups.0.count", "2"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "4608"), - resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "28672"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "2304"), + resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "14336"), resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "6"), resource.TestCheckResourceAttr(name, "service_endpoints", "public-and-private"), resource.TestCheckResourceAttr(name, "allowlist.#", "2"), @@ -174,8 +174,8 @@ func TestAccIBMDatabaseInstancePostgresGroup(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "groups.0.count", "2"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "4096"), - resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "28672"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "2048"), + resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "14336"), resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "6"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), @@ -192,8 +192,8 @@ func TestAccIBMDatabaseInstancePostgresGroup(t *testing.T) { resource.TestCheckResourceAttr(name, "plan", "standard"), resource.TestCheckResourceAttr(name, "location", acc.Region()), resource.TestCheckResourceAttr(name, "groups.0.count", "3"), - resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "6144"), - resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "43008"), + resource.TestCheckResourceAttr(name, "groups.0.memory.0.allocation_mb", "3072"), + resource.TestCheckResourceAttr(name, "groups.0.disk.0.allocation_mb", "21504"), resource.TestCheckResourceAttr(name, "groups.0.cpu.0.allocation_count", "9"), resource.TestCheckResourceAttr(name, "allowlist.#", "0"), resource.TestCheckResourceAttr(name, "users.#", "0"), @@ -421,6 +421,9 @@ func testAccCheckIBMDatabaseInstancePostgresBasic(databaseResourceGroup string, memory { allocation_mb = 2048 } + host_flavor { + id = "multitenant" + } disk { allocation_mb = 10240 } @@ -474,6 +477,9 @@ func testAccCheckIBMDatabaseInstancePostgresFullyspecified(databaseResourceGroup cpu { allocation_count = 6 } + host_flavor { + id = "multitenant" + } } service_endpoints = "public-and-private" tags = ["one:two"] @@ -540,12 +546,15 @@ func testAccCheckIBMDatabaseInstancePostgresGroupBasic(databaseResourceGroup str memory { allocation_mb = 1024 } - disk { + disk { allocation_mb = 5120 } cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } users { name = "user123" @@ -582,12 +591,15 @@ func testAccCheckIBMDatabaseInstancePostgresGroupFullyspecified(databaseResource memory { allocation_mb = 1152 } - disk { + disk { allocation_mb = 7168 } cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } users { name = "user123" @@ -632,12 +644,15 @@ func testAccCheckIBMDatabaseInstancePostgresGroupReduced(databaseResourceGroup s memory { allocation_mb = 1024 } - disk { + disk { allocation_mb = 7168 } cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } } `, databaseResourceGroup, name, acc.Region()) @@ -664,12 +679,15 @@ func testAccCheckIBMDatabaseInstancePostgresGroupScaleOut(databaseResourceGroup memory { allocation_mb = 1024 } - disk { + disk { allocation_mb = 7168 } cpu { allocation_count = 3 } + host_flavor { + id = "multitenant" + } } service_endpoints = "public" tags = ["one:two"] diff --git a/ibm/service/database/resource_ibm_database_rabbitmq_test.go b/ibm/service/database/resource_ibm_database_rabbitmq_test.go index 6c58da2763..abc7c94ad2 100644 --- a/ibm/service/database/resource_ibm_database_rabbitmq_test.go +++ b/ibm/service/database/resource_ibm_database_rabbitmq_test.go @@ -142,7 +142,10 @@ func testAccCheckIBMDatabaseInstanceRabbitmqBasic(databaseResourceGroup string, memory { allocation_mb = 1024 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 1024 } } @@ -182,7 +185,10 @@ func testAccCheckIBMDatabaseInstanceRabbitmqFullyspecified(databaseResourceGroup memory { allocation_mb = 2048 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 2048 } } @@ -226,7 +232,10 @@ func testAccCheckIBMDatabaseInstanceRabbitmqReduced(databaseResourceGroup string memory { allocation_mb = 1024 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 2048 } } diff --git a/ibm/service/database/resource_ibm_database_redis_test.go b/ibm/service/database/resource_ibm_database_redis_test.go index 22366d31fe..06749e1121 100644 --- a/ibm/service/database/resource_ibm_database_redis_test.go +++ b/ibm/service/database/resource_ibm_database_redis_test.go @@ -175,7 +175,10 @@ func testAccCheckIBMDatabaseInstanceRedisBasic(databaseResourceGroup string, nam memory { allocation_mb = 1024 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 1024 } } @@ -215,7 +218,10 @@ func testAccCheckIBMDatabaseInstanceRedisFullyspecified(databaseResourceGroup st memory { allocation_mb = 1152 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 2048 } } @@ -250,7 +256,10 @@ func testAccCheckIBMDatabaseInstanceRedisReduced(databaseResourceGroup string, n memory { allocation_mb = 1024 } - disk { + host_flavor { + id = "multitenant" + } + disk { allocation_mb = 2048 } } @@ -272,12 +281,26 @@ func testAccCheckIBMDatabaseInstanceRedisUserRole(databaseResourceGroup string, location = "%[3]s" adminpassword = "password12345678" + group { + group_id = "member" + + memory { + allocation_mb = 1024 + } + host_flavor { + id = "multitenant" + } + disk { + allocation_mb = 2048 + } + } + users { name = "coolguy" - password = "securepassword123" - role = "-@all +@read" - } - } + password = "securepassword123" + role = "-@all +@read" + } + } `, databaseResourceGroup, name, acc.Region()) } diff --git a/website/docs/r/database.html.markdown b/website/docs/r/database.html.markdown index cfa9e61d86..6e8815f1d3 100644 --- a/website/docs/r/database.html.markdown +++ b/website/docs/r/database.html.markdown @@ -118,6 +118,53 @@ output "ICD Etcd database connection string" { ``` +### Sample database instance by using `host_flavor` attribute +An example to configure and deploy database by using `host_flavor` attribute. + +```terraform +data "ibm_resource_group" "group" { + name = "" +} + +resource "ibm_database" "" { + name = "" + plan = "standard" + location = "eu-gb" + service = "databases-for-etcd" + resource_group_id = data.ibm_resource_group.group.id + tags = ["tag1", "tag2"] + + adminpassword = "password12" + + group { + group_id = "member" + + host_flavor { + id = "b3c.8x32.encrypted" + } + + disk { + allocation_mb = 256000 + } + } + + users { + name = "user123" + password = "password12" + } + + allowlist { + address = "172.168.1.1/32" + description = "desc" + } +} + +output "ICD Etcd database connection string" { + value = "http://${ibm_database.test_acc.ibm_database_connection.icd_conn}" +} + +``` + ### Sample database instance by using `point_in_time_recovery` An example for configuring `point_in_time_recovery` time by using `ibm_database` resource. @@ -667,6 +714,16 @@ Review the argument reference that you can specify for your resource. - Nested scheme for `cpu`: - `allocation_count` - (Optional, Integer) Allocated dedicated CPU per-member. + - `host_flavor` (Set, Optional) + - Nested scheme for `host_flavor`: + - `id` - (Optional, String) **Beta feature:** The hosting infrastructure identifier. Selecting `multitenant` places your database on a logically separated, multi-tenant machine. With this identifier, minimum resource configurations apply. Alternatively, setting the identifier to any of the following host sizes places your database on the specified host size with no other tenants. + - `b3c.4x16.encrypted` + - `b3c.8x32.encrypted` + - `m3c.8x64.encrypted` + - `b3c.16x64.encrypted` + - `b3c.32x128.encrypted` + - `m3c.30x240.encrypted` + - `name` - (Required, String) A descriptive name that is used to identify the database instance. The name must not include spaces. - `offline_restore` - (Optional, Boolean) Enable or disable the Offline Restore option while performing a Point-in-time Recovery for MongoDB EE in a disaster recovery scenario when the source region is unavailable, see [Point-in-time Recovery](https://cloud.ibm.com/docs/databases-for-mongodb?topic=databases-for-mongodb-pitr&interface=api#pitr-offline-restore) - `plan` - (Required, Forces new resource, String) The name of the service plan that you choose for your instance. All databases use `standard`. `enterprise` is supported only for elasticsearch (`databases-for-elasticsearch`), cassandra (`databases-for-cassandra`), and mongodb(`databases-for-mongodb`). `platinum` is supported for elasticsearch (`databases-for-elasticsearch`). From 3d4f36226ec95a395eff995bba9458342efc51cf Mon Sep 17 00:00:00 2001 From: rangelil Date: Sat, 27 Jan 2024 07:57:17 +0100 Subject: [PATCH 02/34] regenerate code --- .secrets.baseline | 14 +- examples/ibm-project/main.tf | 4 +- go.mod | 2 +- go.sum | 4 +- .../project/data_source_ibm_project.go | 50 +- .../project/data_source_ibm_project_config.go | 168 +++--- .../data_source_ibm_project_config_test.go | 3 +- .../data_source_ibm_project_environment.go | 12 +- ...ata_source_ibm_project_environment_test.go | 2 +- .../project/data_source_ibm_project_test.go | 5 +- ibm/service/project/resource_ibm_project.go | 284 ++++------ .../project/resource_ibm_project_config.go | 516 ++++++++---------- .../resource_ibm_project_config_test.go | 2 +- .../resource_ibm_project_environment.go | 48 +- .../resource_ibm_project_environment_test.go | 2 +- .../project/resource_ibm_project_test.go | 2 +- website/docs/d/project.html.markdown | 6 +- website/docs/d/project_config.html.markdown | 2 +- .../docs/d/project_environment.html.markdown | 2 +- website/docs/r/project.html.markdown | 8 +- website/docs/r/project_config.html.markdown | 2 +- .../docs/r/project_environment.html.markdown | 2 +- 22 files changed, 501 insertions(+), 639 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index 403ad68ee7..aabe3b44ef 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "go.mod|go.sum|.*.map|^.secrets.baseline$", "lines": null }, - "generated_at": "2024-01-22T15:02:07Z", + "generated_at": "2024-01-27T06:56:14Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -2900,7 +2900,7 @@ "hashed_secret": "3046d9f6cfaaeea6eed9bb7a4ab010fe49b0cfd4", "is_secret": false, "is_verified": false, - "line_number": 341, + "line_number": 380, "type": "Secret Keyword", "verified_result": null }, @@ -2908,7 +2908,7 @@ "hashed_secret": "92f08f2d9a0dc3f0d4cb3796435a48508cf59ecd", "is_secret": false, "is_verified": false, - "line_number": 687, + "line_number": 707, "type": "Secret Keyword", "verified_result": null } @@ -2918,7 +2918,7 @@ "hashed_secret": "347cd9c53ff77d41a7b22aa56c7b4efaf54658e3", "is_secret": false, "is_verified": false, - "line_number": 58, + "line_number": 59, "type": "Secret Keyword", "verified_result": null } @@ -2956,7 +2956,7 @@ "hashed_secret": "3046d9f6cfaaeea6eed9bb7a4ab010fe49b0cfd4", "is_secret": false, "is_verified": false, - "line_number": 236, + "line_number": 277, "type": "Secret Keyword", "verified_result": null }, @@ -2964,7 +2964,7 @@ "hashed_secret": "92f08f2d9a0dc3f0d4cb3796435a48508cf59ecd", "is_secret": false, "is_verified": false, - "line_number": 1107, + "line_number": 1059, "type": "Secret Keyword", "verified_result": null } @@ -2992,7 +2992,7 @@ "hashed_secret": "92f08f2d9a0dc3f0d4cb3796435a48508cf59ecd", "is_secret": false, "is_verified": false, - "line_number": 509, + "line_number": 497, "type": "Secret Keyword", "verified_result": null } diff --git a/examples/ibm-project/main.tf b/examples/ibm-project/main.tf index 99f42bbc15..b31c75f863 100644 --- a/examples/ibm-project/main.tf +++ b/examples/ibm-project/main.tf @@ -4,7 +4,7 @@ provider "ibm" { // Provision project_config resource instance resource "ibm_project_config" "project_config_instance" { - project_id = ibm_project.project_instance.project_id + project_id = ibm_project.project_instance.id definition { name = "static-website-dev" description = "Website - development" @@ -32,7 +32,7 @@ resource "ibm_project" "project_instance" { // Provision project_environment resource instance resource "ibm_project_environment" "project_environment_instance" { - project_id = ibm_project.project_instance.project_id + project_id = ibm_project.project_instance.id definition { name = "environment-stage" description = "environment for stage project" diff --git a/go.mod b/go.mod index 8089e8fc48..6d61f8d701 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/IBM/keyprotect-go-client v0.12.2 github.com/IBM/networking-go-sdk v0.44.0 github.com/IBM/platform-services-go-sdk v0.55.0 - github.com/IBM/project-go-sdk v0.1.6 + github.com/IBM/project-go-sdk v0.2.0 github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 github.com/IBM/scc-go-sdk/v5 v5.1.4 github.com/IBM/schematics-go-sdk v0.2.3 diff --git a/go.sum b/go.sum index 879f6f18a0..a2527c8d95 100644 --- a/go.sum +++ b/go.sum @@ -160,8 +160,8 @@ github.com/IBM/networking-go-sdk v0.44.0 h1:6acyMd6hwxcjK3bJ2suiUBTjzg8mRFAvYD76 github.com/IBM/networking-go-sdk v0.44.0/go.mod h1:XtqYRInR5NHmFUXhOL6RovpDdv6PnJfZ1lPFvssA8MA= github.com/IBM/platform-services-go-sdk v0.55.0 h1:W598xZanL61bwd8O2DQexr4qjIr+/tP0Y845zoms5yA= github.com/IBM/platform-services-go-sdk v0.55.0/go.mod h1:CWSprvsCsXWvujmBzbtoJSmbRZS9FVV3O594b0t/GiM= -github.com/IBM/project-go-sdk v0.1.6 h1:sGrR0ej5wgBDhR2Xvf8Tgi5NmgMAJ77yep/CPGhvOx8= -github.com/IBM/project-go-sdk v0.1.6/go.mod h1:lqe0M4cKvABI1iHR1b+KfasVcxQL6nl2VJ8eOyQs8Ig= +github.com/IBM/project-go-sdk v0.2.0 h1:DMv0HQfS3GQHkkagZ4E2vt1H1paN5Gh357K9izeaGj8= +github.com/IBM/project-go-sdk v0.2.0/go.mod h1:lqe0M4cKvABI1iHR1b+KfasVcxQL6nl2VJ8eOyQs8Ig= github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 h1:NPUhkoOCRuv3OFWt19PmwjXGGTKlvmbuPg9fUrBUNe4= github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5/go.mod h1:b07XHUVh0XYnQE9s2mqgjYST1h9buaQNqN4EcKhOsX0= github.com/IBM/sarama v1.41.2 h1:ZDBZfGPHAD4uuAtSv4U22fRZBgst0eEwGFzLj0fb85c= diff --git a/ibm/service/project/data_source_ibm_project.go b/ibm/service/project/data_source_ibm_project.go index 2f662c1745..0d2fd70942 100644 --- a/ibm/service/project/data_source_ibm_project.go +++ b/ibm/service/project/data_source_ibm_project.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project @@ -142,15 +142,15 @@ func DataSourceIbmProject() *schema.Resource { Description: "The name and description of a project configuration.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "description": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The configuration name. It is unique within the account across projects and regions.", + Description: "A project configuration description.", }, - "description": &schema.Schema{ + "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "A project configuration description.", + Description: "The configuration name. It is unique within the account across projects and regions.", }, }, }, @@ -266,15 +266,15 @@ func DataSourceIbmProject() *schema.Resource { Description: "The environment definition used in the project collection.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "description": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The name of the environment. It is unique within the account across projects and regions.", + Description: "The description of the environment.", }, - "description": &schema.Schema{ + "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The description of the environment.", + Description: "The name of the environment. It is unique within the account across projects and regions.", }, }, }, @@ -293,16 +293,16 @@ func DataSourceIbmProject() *schema.Resource { Computed: true, Description: "The name of the project. It is unique within the account across regions.", }, - "description": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "A brief explanation of the project's use in the configuration of a deployable architecture. It is possible to create a project without providing a description.", - }, "destroy_on_delete": &schema.Schema{ Type: schema.TypeBool, Computed: true, Description: "The policy that indicates whether the resources are destroyed or not when a project is deleted.", }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "A brief explanation of the project's use in the configuration of a deployable architecture. It is possible to create a project without providing a description.", + }, }, }, }, @@ -460,7 +460,7 @@ func dataSourceIbmProjectProjectConfigSummaryToMap(model *projectv1.ProjectConfi modelMap["created_at"] = model.CreatedAt.String() modelMap["modified_at"] = model.ModifiedAt.String() modelMap["href"] = model.Href - definitionMap, err := dataSourceIbmProjectProjectConfigDefinitionNameDescriptionToMap(model.Definition) + definitionMap, err := dataSourceIbmProjectProjectConfigSummaryDefinitionToMap(model.Definition) if err != nil { return modelMap, err } @@ -484,14 +484,14 @@ func dataSourceIbmProjectProjectConfigVersionSummaryToMap(model *projectv1.Proje return modelMap, nil } -func dataSourceIbmProjectProjectConfigDefinitionNameDescriptionToMap(model *projectv1.ProjectConfigDefinitionNameDescription) (map[string]interface{}, error) { +func dataSourceIbmProjectProjectConfigSummaryDefinitionToMap(model *projectv1.ProjectConfigSummaryDefinition) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name - } if model.Description != nil { modelMap["description"] = model.Description } + if model.Name != nil { + modelMap["name"] = model.Name + } return modelMap, nil } @@ -524,7 +524,7 @@ func dataSourceIbmProjectProjectEnvironmentSummaryToMap(model *projectv1.Project modelMap["project"] = []map[string]interface{}{projectMap} modelMap["created_at"] = model.CreatedAt.String() modelMap["href"] = model.Href - definitionMap, err := dataSourceIbmProjectEnvironmentDefinitionNameDescriptionToMap(model.Definition) + definitionMap, err := dataSourceIbmProjectProjectEnvironmentSummaryDefinitionToMap(model.Definition) if err != nil { return modelMap, err } @@ -532,23 +532,19 @@ func dataSourceIbmProjectProjectEnvironmentSummaryToMap(model *projectv1.Project return modelMap, nil } -func dataSourceIbmProjectEnvironmentDefinitionNameDescriptionToMap(model *projectv1.EnvironmentDefinitionNameDescription) (map[string]interface{}, error) { +func dataSourceIbmProjectProjectEnvironmentSummaryDefinitionToMap(model *projectv1.ProjectEnvironmentSummaryDefinition) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name - } if model.Description != nil { modelMap["description"] = model.Description } + modelMap["name"] = model.Name return modelMap, nil } func dataSourceIbmProjectProjectDefinitionPropertiesToMap(model *projectv1.ProjectDefinitionProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["name"] = model.Name - if model.Description != nil { - modelMap["description"] = model.Description - } modelMap["destroy_on_delete"] = model.DestroyOnDelete + modelMap["description"] = model.Description return modelMap, nil } diff --git a/ibm/service/project/data_source_ibm_project_config.go b/ibm/service/project/data_source_ibm_project_config.go index 04ac065b5e..98ac04280c 100644 --- a/ibm/service/project/data_source_ibm_project_config.go +++ b/ibm/service/project/data_source_ibm_project_config.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project @@ -307,16 +307,55 @@ func DataSourceIbmProjectConfig() *schema.Resource { Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "compliance_profile": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The profile required for compliance.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The unique ID for that compliance profile.", + }, + "instance_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "A unique ID for an instance of a compliance profile.", + }, + "instance_location": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The location of the compliance instance.", + }, + "attachment_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "A unique ID for the attachment to a compliance profile.", + }, + "profile_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The name of the compliance profile.", + }, + }, + }, + }, + "locator_id": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The configuration name. It is unique within the account across projects and regions.", + Description: "A unique concatenation of catalogID.versionID that identifies the DA in the catalog. Either schematics.workspace_crn, definition.locator_id, or both must be specified.", }, "description": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "A project configuration description.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The configuration name. It is unique within the account across projects and regions.", + }, "environment_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -363,45 +402,6 @@ func DataSourceIbmProjectConfig() *schema.Resource { Type: schema.TypeString, }, }, - "compliance_profile": &schema.Schema{ - Type: schema.TypeList, - Computed: true, - Description: "The profile required for compliance.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The unique ID for that compliance profile.", - }, - "instance_id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "A unique ID for an instance of a compliance profile.", - }, - "instance_location": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The location of the compliance instance.", - }, - "attachment_id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "A unique ID for the attachment to a compliance profile.", - }, - "profile_name": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The name of the compliance profile.", - }, - }, - }, - }, - "locator_id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "A unique concatenation of catalogID.versionID that identifies the DA in the catalog. Either schematics.workspace_crn, definition.locator_id, or both must be specified.", - }, "resource_crns": &schema.Schema{ Type: schema.TypeList, Computed: true, @@ -628,10 +628,20 @@ func dataSourceIbmProjectConfigProjectConfigResponseDefinitionToMap(model projec } else if _, ok := model.(*projectv1.ProjectConfigResponseDefinition); ok { modelMap := make(map[string]interface{}) model := model.(*projectv1.ProjectConfigResponseDefinition) - modelMap["name"] = model.Name + if model.ComplianceProfile != nil { + complianceProfileMap, err := dataSourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) + if err != nil { + return modelMap, err + } + modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} + } + if model.LocatorID != nil { + modelMap["locator_id"] = model.LocatorID + } if model.Description != nil { modelMap["description"] = model.Description } + modelMap["name"] = model.Name if model.EnvironmentID != nil { modelMap["environment_id"] = model.EnvironmentID } @@ -656,16 +666,6 @@ func dataSourceIbmProjectConfigProjectConfigResponseDefinitionToMap(model projec } modelMap["settings"] = settings } - if model.ComplianceProfile != nil { - complianceProfileMap, err := dataSourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) - if err != nil { - return modelMap, err - } - modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} - } - if model.LocatorID != nil { - modelMap["locator_id"] = model.LocatorID - } if model.ResourceCrns != nil { modelMap["resource_crns"] = model.ResourceCrns } @@ -675,20 +675,6 @@ func dataSourceIbmProjectConfigProjectConfigResponseDefinitionToMap(model projec } } -func dataSourceIbmProjectConfigProjectConfigAuthToMap(model *projectv1.ProjectConfigAuth) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - if model.TrustedProfileID != nil { - modelMap["trusted_profile_id"] = model.TrustedProfileID - } - if model.Method != nil { - modelMap["method"] = model.Method - } - if model.ApiKey != nil { - modelMap["api_key"] = model.ApiKey - } - return modelMap, nil -} - func dataSourceIbmProjectConfigProjectComplianceProfileToMap(model *projectv1.ProjectComplianceProfile) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.ID != nil { @@ -709,14 +695,38 @@ func dataSourceIbmProjectConfigProjectComplianceProfileToMap(model *projectv1.Pr return modelMap, nil } +func dataSourceIbmProjectConfigProjectConfigAuthToMap(model *projectv1.ProjectConfigAuth) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.TrustedProfileID != nil { + modelMap["trusted_profile_id"] = model.TrustedProfileID + } + if model.Method != nil { + modelMap["method"] = model.Method + } + if model.ApiKey != nil { + modelMap["api_key"] = model.ApiKey + } + return modelMap, nil +} + func dataSourceIbmProjectConfigProjectConfigResponseDefinitionDAConfigDefinitionPropertiesToMap(model *projectv1.ProjectConfigResponseDefinitionDAConfigDefinitionProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name + if model.ComplianceProfile != nil { + complianceProfileMap, err := dataSourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) + if err != nil { + return modelMap, err + } + modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} + } + if model.LocatorID != nil { + modelMap["locator_id"] = model.LocatorID } if model.Description != nil { modelMap["description"] = model.Description } + if model.Name != nil { + modelMap["name"] = model.Name + } if model.EnvironmentID != nil { modelMap["environment_id"] = model.EnvironmentID } @@ -741,27 +751,20 @@ func dataSourceIbmProjectConfigProjectConfigResponseDefinitionDAConfigDefinition } modelMap["settings"] = settings } - if model.ComplianceProfile != nil { - complianceProfileMap, err := dataSourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) - if err != nil { - return modelMap, err - } - modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} - } - if model.LocatorID != nil { - modelMap["locator_id"] = model.LocatorID - } return modelMap, nil } func dataSourceIbmProjectConfigProjectConfigResponseDefinitionResourceConfigDefinitionPropertiesToMap(model *projectv1.ProjectConfigResponseDefinitionResourceConfigDefinitionProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name + if model.ResourceCrns != nil { + modelMap["resource_crns"] = model.ResourceCrns } if model.Description != nil { modelMap["description"] = model.Description } + if model.Name != nil { + modelMap["name"] = model.Name + } if model.EnvironmentID != nil { modelMap["environment_id"] = model.EnvironmentID } @@ -786,8 +789,5 @@ func dataSourceIbmProjectConfigProjectConfigResponseDefinitionResourceConfigDefi } modelMap["settings"] = settings } - if model.ResourceCrns != nil { - modelMap["resource_crns"] = model.ResourceCrns - } return modelMap, nil } diff --git a/ibm/service/project/data_source_ibm_project_config_test.go b/ibm/service/project/data_source_ibm_project_config_test.go index 0b78bca324..3218341c74 100644 --- a/ibm/service/project/data_source_ibm_project_config_test.go +++ b/ibm/service/project/data_source_ibm_project_config_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project_test @@ -27,6 +27,7 @@ func TestAccIbmProjectConfigDataSourceBasic(t *testing.T) { resource.TestCheckResourceAttrSet("data.ibm_project_config.project_config_instance", "is_draft"), resource.TestCheckResourceAttrSet("data.ibm_project_config.project_config_instance", "created_at"), resource.TestCheckResourceAttrSet("data.ibm_project_config.project_config_instance", "modified_at"), + resource.TestCheckResourceAttrSet("data.ibm_project_config.project_config_instance", "outputs.#"), resource.TestCheckResourceAttrSet("data.ibm_project_config.project_config_instance", "project.#"), resource.TestCheckResourceAttrSet("data.ibm_project_config.project_config_instance", "state"), resource.TestCheckResourceAttrSet("data.ibm_project_config.project_config_instance", "href"), diff --git a/ibm/service/project/data_source_ibm_project_environment.go b/ibm/service/project/data_source_ibm_project_environment.go index 514e19f289..e3d317edb6 100644 --- a/ibm/service/project/data_source_ibm_project_environment.go +++ b/ibm/service/project/data_source_ibm_project_environment.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project @@ -95,15 +95,15 @@ func DataSourceIbmProjectEnvironment() *schema.Resource { Description: "The environment definition.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "description": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The name of the environment. It is unique within the account across projects and regions.", + Description: "The description of the environment.", }, - "description": &schema.Schema{ + "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The description of the environment.", + Description: "The name of the environment. It is unique within the account across projects and regions.", }, "authorizations": &schema.Schema{ Type: schema.TypeList, @@ -262,10 +262,10 @@ func dataSourceIbmProjectEnvironmentProjectDefinitionReferenceToMap(model *proje func dataSourceIbmProjectEnvironmentEnvironmentDefinitionRequiredPropertiesToMap(model *projectv1.EnvironmentDefinitionRequiredProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - modelMap["name"] = model.Name if model.Description != nil { modelMap["description"] = model.Description } + modelMap["name"] = model.Name if model.Authorizations != nil { authorizationsMap, err := dataSourceIbmProjectEnvironmentProjectConfigAuthToMap(model.Authorizations) if err != nil { diff --git a/ibm/service/project/data_source_ibm_project_environment_test.go b/ibm/service/project/data_source_ibm_project_environment_test.go index 2f2d111aba..b8226f3ee3 100644 --- a/ibm/service/project/data_source_ibm_project_environment_test.go +++ b/ibm/service/project/data_source_ibm_project_environment_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project_test diff --git a/ibm/service/project/data_source_ibm_project_test.go b/ibm/service/project/data_source_ibm_project_test.go index 6ac9472a3c..f0eec67569 100644 --- a/ibm/service/project/data_source_ibm_project_test.go +++ b/ibm/service/project/data_source_ibm_project_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project_test @@ -27,11 +27,14 @@ func TestAccIbmProjectDataSourceBasic(t *testing.T) { resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "project_id"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "crn"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "created_at"), + resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "cumulative_needs_attention_view.#"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "location"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "resource_group_id"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "state"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "href"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "resource_group"), + resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "configs.#"), + resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "environments.#"), resource.TestCheckResourceAttrSet("data.ibm_project.project_instance", "definition.#"), ), }, diff --git a/ibm/service/project/resource_ibm_project.go b/ibm/service/project/resource_ibm_project.go index d428f33c91..dfd7610586 100644 --- a/ibm/service/project/resource_ibm_project.go +++ b/ibm/service/project/resource_ibm_project.go @@ -1,11 +1,10 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project import ( "context" - "encoding/json" "fmt" "log" @@ -39,7 +38,7 @@ func ResourceIbmProject() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - Description: "The resource group where the project's data and tools are created.", + Description: "The resource group name where the project's data and tools are created.", }, "definition": &schema.Schema{ Type: schema.TypeList, @@ -54,16 +53,16 @@ func ResourceIbmProject() *schema.Resource { Required: true, Description: "The name of the project. It is unique within the account across regions.", }, - "description": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "A brief explanation of the project's use in the configuration of a deployable architecture. It is possible to create a project without providing a description.", - }, "destroy_on_delete": &schema.Schema{ Type: schema.TypeBool, Required: true, Description: "The policy that indicates whether the resources are destroyed or not when a project is deleted.", }, + "description": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "A brief explanation of the project's use in the configuration of a deployable architecture. It is possible to create a project without providing a description.", + }, }, }, }, @@ -173,15 +172,15 @@ func ResourceIbmProject() *schema.Resource { Description: "The name and description of a project configuration.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "description": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The configuration name. It is unique within the account across projects and regions.", + Description: "A project configuration description.", }, - "description": &schema.Schema{ + "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "A project configuration description.", + Description: "The configuration name. It is unique within the account across projects and regions.", }, }, }, @@ -297,15 +296,15 @@ func ResourceIbmProject() *schema.Resource { Description: "The environment definition used in the project collection.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "description": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The name of the environment. It is unique within the account across projects and regions.", + Description: "The description of the environment.", }, - "description": &schema.Schema{ + "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The description of the environment.", + Description: "The name of the environment. It is unique within the account across projects and regions.", }, }, }, @@ -434,18 +433,16 @@ func resourceIbmProjectRead(context context.Context, d *schema.ResourceData, met if err = d.Set("created_at", flex.DateTimeToString(project.CreatedAt)); err != nil { return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) } - if !core.IsNil(project.CumulativeNeedsAttentionView) { - cumulativeNeedsAttentionView := []map[string]interface{}{} - for _, cumulativeNeedsAttentionViewItem := range project.CumulativeNeedsAttentionView { - cumulativeNeedsAttentionViewItemMap, err := resourceIbmProjectCumulativeNeedsAttentionToMap(&cumulativeNeedsAttentionViewItem) - if err != nil { - return diag.FromErr(err) - } - cumulativeNeedsAttentionView = append(cumulativeNeedsAttentionView, cumulativeNeedsAttentionViewItemMap) - } - if err = d.Set("cumulative_needs_attention_view", cumulativeNeedsAttentionView); err != nil { - return diag.FromErr(fmt.Errorf("Error setting cumulative_needs_attention_view: %s", err)) + cumulativeNeedsAttentionView := []map[string]interface{}{} + for _, cumulativeNeedsAttentionViewItem := range project.CumulativeNeedsAttentionView { + cumulativeNeedsAttentionViewItemMap, err := resourceIbmProjectCumulativeNeedsAttentionToMap(&cumulativeNeedsAttentionViewItem) + if err != nil { + return diag.FromErr(err) } + cumulativeNeedsAttentionView = append(cumulativeNeedsAttentionView, cumulativeNeedsAttentionViewItemMap) + } + if err = d.Set("cumulative_needs_attention_view", cumulativeNeedsAttentionView); err != nil { + return diag.FromErr(fmt.Errorf("Error setting cumulative_needs_attention_view: %s", err)) } if !core.IsNil(project.CumulativeNeedsAttentionViewError) { if err = d.Set("cumulative_needs_attention_view_error", project.CumulativeNeedsAttentionViewError); err != nil { @@ -466,31 +463,27 @@ func resourceIbmProjectRead(context context.Context, d *schema.ResourceData, met return diag.FromErr(fmt.Errorf("Error setting event_notifications_crn: %s", err)) } } - if !core.IsNil(project.Configs) { - configs := []map[string]interface{}{} - for _, configsItem := range project.Configs { - configsItemMap, err := resourceIbmProjectProjectConfigSummaryToMap(&configsItem) - if err != nil { - return diag.FromErr(err) - } - configs = append(configs, configsItemMap) - } - if err = d.Set("configs", configs); err != nil { - return diag.FromErr(fmt.Errorf("Error setting configs: %s", err)) + configs := []map[string]interface{}{} + for _, configsItem := range project.Configs { + configsItemMap, err := resourceIbmProjectProjectConfigSummaryToMap(&configsItem) + if err != nil { + return diag.FromErr(err) } + configs = append(configs, configsItemMap) } - if !core.IsNil(project.Environments) { - environments := []map[string]interface{}{} - for _, environmentsItem := range project.Environments { - environmentsItemMap, err := resourceIbmProjectProjectEnvironmentSummaryToMap(&environmentsItem) - if err != nil { - return diag.FromErr(err) - } - environments = append(environments, environmentsItemMap) - } - if err = d.Set("environments", environments); err != nil { - return diag.FromErr(fmt.Errorf("Error setting environments: %s", err)) + if err = d.Set("configs", configs); err != nil { + return diag.FromErr(fmt.Errorf("Error setting configs: %s", err)) + } + environments := []map[string]interface{}{} + for _, environmentsItem := range project.Environments { + environmentsItemMap, err := resourceIbmProjectProjectEnvironmentSummaryToMap(&environmentsItem) + if err != nil { + return diag.FromErr(err) } + environments = append(environments, environmentsItemMap) + } + if err = d.Set("environments", environments); err != nil { + return diag.FromErr(fmt.Errorf("Error setting environments: %s", err)) } return nil @@ -552,18 +545,18 @@ func resourceIbmProjectDelete(context context.Context, d *schema.ResourceData, m func resourceIbmProjectMapToProjectPrototypeDefinition(modelMap map[string]interface{}) (*projectv1.ProjectPrototypeDefinition, error) { model := &projectv1.ProjectPrototypeDefinition{} model.Name = core.StringPtr(modelMap["name"].(string)) - if modelMap["description"] != nil && modelMap["description"].(string) != "" { - model.Description = core.StringPtr(modelMap["description"].(string)) - } if modelMap["destroy_on_delete"] != nil { model.DestroyOnDelete = core.BoolPtr(modelMap["destroy_on_delete"].(bool)) } + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) + } return model, nil } func resourceIbmProjectMapToProjectConfigPrototype(modelMap map[string]interface{}) (*projectv1.ProjectConfigPrototype, error) { model := &projectv1.ProjectConfigPrototype{} - DefinitionModel, err := resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlock(modelMap["definition"].([]interface{})[0].(map[string]interface{})) + DefinitionModel, err := resourceIbmProjectMapToProjectConfigDefinitionBlockPrototype(modelMap["definition"].([]interface{})[0].(map[string]interface{})) if err != nil { return model, err } @@ -578,12 +571,22 @@ func resourceIbmProjectMapToProjectConfigPrototype(modelMap map[string]interface return model, nil } -func resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlock(modelMap map[string]interface{}) (projectv1.ProjectConfigPrototypeDefinitionBlockIntf, error) { - model := &projectv1.ProjectConfigPrototypeDefinitionBlock{} - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectMapToProjectConfigDefinitionBlockPrototype(modelMap map[string]interface{}) (projectv1.ProjectConfigDefinitionBlockPrototypeIntf, error) { + model := &projectv1.ProjectConfigDefinitionBlockPrototype{} + if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { + ComplianceProfileModel, err := resourceIbmProjectMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.ComplianceProfile = ComplianceProfileModel + } + if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { + model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) + } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + model.Name = core.StringPtr(modelMap["name"].(string)) if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -595,32 +598,12 @@ func resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlock(modelMap map[s model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } + model.Settings = modelMap["settings"].(map[string]interface{}) } - if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { - ComplianceProfileModel, err := resourceIbmProjectMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) - if err != nil { - return model, err - } - model.ComplianceProfile = ComplianceProfileModel - } - if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { - model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) - } - if modelMap["resource_crns"] != nil && len(modelMap["resource_crns"].([]interface{})) > 0 { + if modelMap["resource_crns"] != nil { resourceCrns := []string{} for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) @@ -630,20 +613,6 @@ func resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlock(modelMap map[s return model, nil } -func resourceIbmProjectMapToProjectConfigAuth(modelMap map[string]interface{}) (*projectv1.ProjectConfigAuth, error) { - model := &projectv1.ProjectConfigAuth{} - if modelMap["trusted_profile_id"] != nil && modelMap["trusted_profile_id"].(string) != "" { - model.TrustedProfileID = core.StringPtr(modelMap["trusted_profile_id"].(string)) - } - if modelMap["method"] != nil && modelMap["method"].(string) != "" { - model.Method = core.StringPtr(modelMap["method"].(string)) - } - if modelMap["api_key"] != nil && modelMap["api_key"].(string) != "" { - model.ApiKey = core.StringPtr(modelMap["api_key"].(string)) - } - return model, nil -} - func resourceIbmProjectMapToProjectComplianceProfile(modelMap map[string]interface{}) (*projectv1.ProjectComplianceProfile, error) { model := &projectv1.ProjectComplianceProfile{} if modelMap["id"] != nil && modelMap["id"].(string) != "" { @@ -664,14 +633,38 @@ func resourceIbmProjectMapToProjectComplianceProfile(modelMap map[string]interfa return model, nil } -func resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlockDAConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigPrototypeDefinitionBlockDAConfigDefinitionProperties, error) { - model := &projectv1.ProjectConfigPrototypeDefinitionBlockDAConfigDefinitionProperties{} - if modelMap["name"] != nil && modelMap["name"].(string) != "" { - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectMapToProjectConfigAuth(modelMap map[string]interface{}) (*projectv1.ProjectConfigAuth, error) { + model := &projectv1.ProjectConfigAuth{} + if modelMap["trusted_profile_id"] != nil && modelMap["trusted_profile_id"].(string) != "" { + model.TrustedProfileID = core.StringPtr(modelMap["trusted_profile_id"].(string)) + } + if modelMap["method"] != nil && modelMap["method"].(string) != "" { + model.Method = core.StringPtr(modelMap["method"].(string)) + } + if modelMap["api_key"] != nil && modelMap["api_key"].(string) != "" { + model.ApiKey = core.StringPtr(modelMap["api_key"].(string)) + } + return model, nil +} + +func resourceIbmProjectMapToProjectConfigDefinitionBlockPrototypeDAConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigDefinitionBlockPrototypeDAConfigDefinitionProperties, error) { + model := &projectv1.ProjectConfigDefinitionBlockPrototypeDAConfigDefinitionProperties{} + if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { + ComplianceProfileModel, err := resourceIbmProjectMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.ComplianceProfile = ComplianceProfileModel + } + if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { + model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -683,42 +676,29 @@ func resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlockDAConfigDefinit model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } - } - if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { - ComplianceProfileModel, err := resourceIbmProjectMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) - if err != nil { - return model, err - } - model.ComplianceProfile = ComplianceProfileModel - } - if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { - model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) + model.Settings = modelMap["settings"].(map[string]interface{}) } return model, nil } -func resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlockResourceConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigPrototypeDefinitionBlockResourceConfigDefinitionProperties, error) { - model := &projectv1.ProjectConfigPrototypeDefinitionBlockResourceConfigDefinitionProperties{} - if modelMap["name"] != nil && modelMap["name"].(string) != "" { - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectMapToProjectConfigDefinitionBlockPrototypeResourceConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigDefinitionBlockPrototypeResourceConfigDefinitionProperties, error) { + model := &projectv1.ProjectConfigDefinitionBlockPrototypeResourceConfigDefinitionProperties{} + if modelMap["resource_crns"] != nil { + resourceCrns := []string{} + for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { + resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) + } + model.ResourceCrns = resourceCrns } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -730,27 +710,10 @@ func resourceIbmProjectMapToProjectConfigPrototypeDefinitionBlockResourceConfigD model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } - } - if modelMap["resource_crns"] != nil && len(modelMap["resource_crns"].([]interface{})) > 0 { - resourceCrns := []string{} - for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { - resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) - } - model.ResourceCrns = resourceCrns + model.Settings = modelMap["settings"].(map[string]interface{}) } return model, nil } @@ -775,10 +738,10 @@ func resourceIbmProjectMapToEnvironmentPrototype(modelMap map[string]interface{} func resourceIbmProjectMapToEnvironmentDefinitionRequiredProperties(modelMap map[string]interface{}) (*projectv1.EnvironmentDefinitionRequiredProperties, error) { model := &projectv1.EnvironmentDefinitionRequiredProperties{} - model.Name = core.StringPtr(modelMap["name"].(string)) if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + model.Name = core.StringPtr(modelMap["name"].(string)) if modelMap["authorizations"] != nil && len(modelMap["authorizations"].([]interface{})) > 0 { AuthorizationsModel, err := resourceIbmProjectMapToProjectConfigAuth(modelMap["authorizations"].([]interface{})[0].(map[string]interface{})) if err != nil { @@ -787,12 +750,7 @@ func resourceIbmProjectMapToEnvironmentDefinitionRequiredProperties(modelMap map model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { ComplianceProfileModel, err := resourceIbmProjectMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) @@ -809,22 +767,20 @@ func resourceIbmProjectMapToProjectPatchDefinitionBlock(modelMap map[string]inte if modelMap["name"] != nil && modelMap["name"].(string) != "" { model.Name = core.StringPtr(modelMap["name"].(string)) } - if modelMap["description"] != nil && modelMap["description"].(string) != "" { - model.Description = core.StringPtr(modelMap["description"].(string)) - } if modelMap["destroy_on_delete"] != nil { model.DestroyOnDelete = core.BoolPtr(modelMap["destroy_on_delete"].(bool)) } + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) + } return model, nil } func resourceIbmProjectProjectDefinitionPropertiesToMap(model *projectv1.ProjectDefinitionProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["name"] = model.Name - if model.Description != nil { - modelMap["description"] = model.Description - } modelMap["destroy_on_delete"] = model.DestroyOnDelete + modelMap["description"] = model.Description return modelMap, nil } @@ -867,7 +823,7 @@ func resourceIbmProjectProjectConfigSummaryToMap(model *projectv1.ProjectConfigS modelMap["created_at"] = model.CreatedAt.String() modelMap["modified_at"] = model.ModifiedAt.String() modelMap["href"] = model.Href - definitionMap, err := resourceIbmProjectProjectConfigDefinitionNameDescriptionToMap(model.Definition) + definitionMap, err := resourceIbmProjectProjectConfigSummaryDefinitionToMap(model.Definition) if err != nil { return modelMap, err } @@ -891,14 +847,14 @@ func resourceIbmProjectProjectConfigVersionSummaryToMap(model *projectv1.Project return modelMap, nil } -func resourceIbmProjectProjectConfigDefinitionNameDescriptionToMap(model *projectv1.ProjectConfigDefinitionNameDescription) (map[string]interface{}, error) { +func resourceIbmProjectProjectConfigSummaryDefinitionToMap(model *projectv1.ProjectConfigSummaryDefinition) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name - } if model.Description != nil { modelMap["description"] = model.Description } + if model.Name != nil { + modelMap["name"] = model.Name + } return modelMap, nil } @@ -931,7 +887,7 @@ func resourceIbmProjectProjectEnvironmentSummaryToMap(model *projectv1.ProjectEn modelMap["project"] = []map[string]interface{}{projectMap} modelMap["created_at"] = model.CreatedAt.String() modelMap["href"] = model.Href - definitionMap, err := resourceIbmProjectEnvironmentDefinitionNameDescriptionToMap(model.Definition) + definitionMap, err := resourceIbmProjectProjectEnvironmentSummaryDefinitionToMap(model.Definition) if err != nil { return modelMap, err } @@ -939,13 +895,11 @@ func resourceIbmProjectProjectEnvironmentSummaryToMap(model *projectv1.ProjectEn return modelMap, nil } -func resourceIbmProjectEnvironmentDefinitionNameDescriptionToMap(model *projectv1.EnvironmentDefinitionNameDescription) (map[string]interface{}, error) { +func resourceIbmProjectProjectEnvironmentSummaryDefinitionToMap(model *projectv1.ProjectEnvironmentSummaryDefinition) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name - } if model.Description != nil { modelMap["description"] = model.Description } + modelMap["name"] = model.Name return modelMap, nil } diff --git a/ibm/service/project/resource_ibm_project_config.go b/ibm/service/project/resource_ibm_project_config.go index 7b748c63c3..da7c69446e 100644 --- a/ibm/service/project/resource_ibm_project_config.go +++ b/ibm/service/project/resource_ibm_project_config.go @@ -1,11 +1,10 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project import ( "context" - "encoding/json" "fmt" "log" @@ -201,16 +200,58 @@ func ResourceIbmProjectConfig() *schema.Resource { Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "compliance_profile": &schema.Schema{ + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Description: "The profile required for compliance.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The unique ID for that compliance profile.", + }, + "instance_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "A unique ID for an instance of a compliance profile.", + }, + "instance_location": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The location of the compliance instance.", + }, + "attachment_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "A unique ID for the attachment to a compliance profile.", + }, + "profile_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The name of the compliance profile.", + }, + }, + }, + }, + "locator_id": &schema.Schema{ Type: schema.TypeString, - Required: true, - Description: "The configuration name. It is unique within the account across projects and regions.", + Optional: true, + ForceNew: true, + Description: "A unique concatenation of catalogID.versionID that identifies the DA in the catalog. Either schematics.workspace_crn, definition.locator_id, or both must be specified.", }, "description": &schema.Schema{ Type: schema.TypeString, Optional: true, + Default: "", Description: "A project configuration description.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The configuration name. It is unique within the account across projects and regions.", + }, "environment_id": &schema.Schema{ Type: schema.TypeString, Optional: true, @@ -254,47 +295,6 @@ func ResourceIbmProjectConfig() *schema.Resource { Description: "Schematics environment variables to use to deploy the configuration. Settings are only available if they were specified when the configuration was initially created.", Elem: &schema.Schema{Type: schema.TypeString}, }, - "compliance_profile": &schema.Schema{ - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Description: "The profile required for compliance.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "The unique ID for that compliance profile.", - }, - "instance_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "A unique ID for an instance of a compliance profile.", - }, - "instance_location": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "The location of the compliance instance.", - }, - "attachment_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "A unique ID for the attachment to a compliance profile.", - }, - "profile_name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "The name of the compliance profile.", - }, - }, - }, - }, - "locator_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Description: "A unique concatenation of catalogID.versionID that identifies the DA in the catalog. Either schematics.workspace_crn, definition.locator_id, or both must be specified.", - }, "resource_crns": &schema.Schema{ Type: schema.TypeList, Optional: true, @@ -448,7 +448,7 @@ func resourceIbmProjectConfigCreate(context context.Context, d *schema.ResourceD createConfigOptions := &projectv1.CreateConfigOptions{} createConfigOptions.SetProjectID(d.Get("project_id").(string)) - definitionModel, err := resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlock(d.Get("definition.0").(map[string]interface{})) + definitionModel, err := resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPrototype(d.Get("definition.0").(map[string]interface{})) if err != nil { return diag.FromErr(err) } @@ -511,14 +511,12 @@ func resourceIbmProjectConfigRead(context context.Context, d *schema.ResourceDat if err = d.Set("is_draft", projectConfig.IsDraft); err != nil { return diag.FromErr(fmt.Errorf("Error setting is_draft: %s", err)) } - if !core.IsNil(projectConfig.NeedsAttentionState) { - needsAttentionState := []interface{}{} - for _, needsAttentionStateItem := range projectConfig.NeedsAttentionState { - needsAttentionState = append(needsAttentionState, needsAttentionStateItem) - } - if err = d.Set("needs_attention_state", needsAttentionState); err != nil { - return diag.FromErr(fmt.Errorf("Error setting needs_attention_state: %s", err)) - } + needsAttentionState := []interface{}{} + for _, needsAttentionStateItem := range projectConfig.NeedsAttentionState { + needsAttentionState = append(needsAttentionState, needsAttentionStateItem) + } + if err = d.Set("needs_attention_state", needsAttentionState); err != nil { + return diag.FromErr(fmt.Errorf("Error setting needs_attention_state: %s", err)) } if err = d.Set("created_at", flex.DateTimeToString(projectConfig.CreatedAt)); err != nil { return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) @@ -531,18 +529,16 @@ func resourceIbmProjectConfigRead(context context.Context, d *schema.ResourceDat return diag.FromErr(fmt.Errorf("Error setting last_saved_at: %s", err)) } } - if !core.IsNil(projectConfig.Outputs) { - outputs := []map[string]interface{}{} - for _, outputsItem := range projectConfig.Outputs { - outputsItemMap, err := resourceIbmProjectConfigOutputValueToMap(&outputsItem) - if err != nil { - return diag.FromErr(err) - } - outputs = append(outputs, outputsItemMap) - } - if err = d.Set("outputs", outputs); err != nil { - return diag.FromErr(fmt.Errorf("Error setting outputs: %s", err)) + outputs := []map[string]interface{}{} + for _, outputsItem := range projectConfig.Outputs { + outputsItemMap, err := resourceIbmProjectConfigOutputValueToMap(&outputsItem) + if err != nil { + return diag.FromErr(err) } + outputs = append(outputs, outputsItemMap) + } + if err = d.Set("outputs", outputs); err != nil { + return diag.FromErr(fmt.Errorf("Error setting outputs: %s", err)) } projectMap, err := resourceIbmProjectConfigProjectReferenceToMap(projectConfig.Project) if err != nil { @@ -592,7 +588,7 @@ func resourceIbmProjectConfigUpdate(context context.Context, d *schema.ResourceD " The resource must be re-created to update this property.", "project_id")) } if d.HasChange("definition") { - definition, err := resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlock(d.Get("definition.0").(map[string]interface{})) + definition, err := resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPatch(d.Get("definition.0").(map[string]interface{})) if err != nil { return diag.FromErr(err) } @@ -638,12 +634,22 @@ func resourceIbmProjectConfigDelete(context context.Context, d *schema.ResourceD return nil } -func resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlock(modelMap map[string]interface{}) (projectv1.ProjectConfigPrototypeDefinitionBlockIntf, error) { - model := &projectv1.ProjectConfigPrototypeDefinitionBlock{} - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPrototype(modelMap map[string]interface{}) (projectv1.ProjectConfigDefinitionBlockPrototypeIntf, error) { + model := &projectv1.ProjectConfigDefinitionBlockPrototype{} + if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { + ComplianceProfileModel, err := resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.ComplianceProfile = ComplianceProfileModel + } + if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { + model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) + } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + model.Name = core.StringPtr(modelMap["name"].(string)) if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -655,32 +661,12 @@ func resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlock(modelMap model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } + model.Settings = modelMap["settings"].(map[string]interface{}) } - if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { - ComplianceProfileModel, err := resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) - if err != nil { - return model, err - } - model.ComplianceProfile = ComplianceProfileModel - } - if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { - model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) - } - if modelMap["resource_crns"] != nil && len(modelMap["resource_crns"].([]interface{})) > 0 { + if modelMap["resource_crns"] != nil { resourceCrns := []string{} for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) @@ -690,20 +676,6 @@ func resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlock(modelMap return model, nil } -func resourceIbmProjectConfigMapToProjectConfigAuth(modelMap map[string]interface{}) (*projectv1.ProjectConfigAuth, error) { - model := &projectv1.ProjectConfigAuth{} - if modelMap["trusted_profile_id"] != nil && modelMap["trusted_profile_id"].(string) != "" { - model.TrustedProfileID = core.StringPtr(modelMap["trusted_profile_id"].(string)) - } - if modelMap["method"] != nil && modelMap["method"].(string) != "" { - model.Method = core.StringPtr(modelMap["method"].(string)) - } - if modelMap["api_key"] != nil && modelMap["api_key"].(string) != "" { - model.ApiKey = core.StringPtr(modelMap["api_key"].(string)) - } - return model, nil -} - func resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap map[string]interface{}) (*projectv1.ProjectComplianceProfile, error) { model := &projectv1.ProjectComplianceProfile{} if modelMap["id"] != nil && modelMap["id"].(string) != "" { @@ -724,14 +696,38 @@ func resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap map[string]i return model, nil } -func resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlockDAConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigPrototypeDefinitionBlockDAConfigDefinitionProperties, error) { - model := &projectv1.ProjectConfigPrototypeDefinitionBlockDAConfigDefinitionProperties{} - if modelMap["name"] != nil && modelMap["name"].(string) != "" { - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectConfigMapToProjectConfigAuth(modelMap map[string]interface{}) (*projectv1.ProjectConfigAuth, error) { + model := &projectv1.ProjectConfigAuth{} + if modelMap["trusted_profile_id"] != nil && modelMap["trusted_profile_id"].(string) != "" { + model.TrustedProfileID = core.StringPtr(modelMap["trusted_profile_id"].(string)) + } + if modelMap["method"] != nil && modelMap["method"].(string) != "" { + model.Method = core.StringPtr(modelMap["method"].(string)) + } + if modelMap["api_key"] != nil && modelMap["api_key"].(string) != "" { + model.ApiKey = core.StringPtr(modelMap["api_key"].(string)) + } + return model, nil +} + +func resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPrototypeDAConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigDefinitionBlockPrototypeDAConfigDefinitionProperties, error) { + model := &projectv1.ProjectConfigDefinitionBlockPrototypeDAConfigDefinitionProperties{} + if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { + ComplianceProfileModel, err := resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.ComplianceProfile = ComplianceProfileModel + } + if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { + model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -743,42 +739,29 @@ func resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlockDAConfigD model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } - } - if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { - ComplianceProfileModel, err := resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) - if err != nil { - return model, err - } - model.ComplianceProfile = ComplianceProfileModel - } - if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { - model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) + model.Settings = modelMap["settings"].(map[string]interface{}) } return model, nil } -func resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlockResourceConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigPrototypeDefinitionBlockResourceConfigDefinitionProperties, error) { - model := &projectv1.ProjectConfigPrototypeDefinitionBlockResourceConfigDefinitionProperties{} - if modelMap["name"] != nil && modelMap["name"].(string) != "" { - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPrototypeResourceConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigDefinitionBlockPrototypeResourceConfigDefinitionProperties, error) { + model := &projectv1.ProjectConfigDefinitionBlockPrototypeResourceConfigDefinitionProperties{} + if modelMap["resource_crns"] != nil { + resourceCrns := []string{} + for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { + resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) + } + model.ResourceCrns = resourceCrns } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -790,27 +773,10 @@ func resourceIbmProjectConfigMapToProjectConfigPrototypeDefinitionBlockResourceC model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } - } - if modelMap["resource_crns"] != nil && len(modelMap["resource_crns"].([]interface{})) > 0 { - resourceCrns := []string{} - for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { - resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) - } - model.ResourceCrns = resourceCrns + model.Settings = modelMap["settings"].(map[string]interface{}) } return model, nil } @@ -823,14 +789,24 @@ func resourceIbmProjectConfigMapToSchematicsWorkspace(modelMap map[string]interf return model, nil } -func resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlock(modelMap map[string]interface{}) (projectv1.ProjectConfigPatchDefinitionBlockIntf, error) { - model := &projectv1.ProjectConfigPatchDefinitionBlock{} - if modelMap["name"] != nil && modelMap["name"].(string) != "" { - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPatch(modelMap map[string]interface{}) (projectv1.ProjectConfigDefinitionBlockPatchIntf, error) { + model := &projectv1.ProjectConfigDefinitionBlockPatch{} + if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { + ComplianceProfileModel, err := resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.ComplianceProfile = ComplianceProfileModel + } + if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { + model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -842,21 +818,23 @@ func resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlock(modelMap map model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap + model.Settings = modelMap["settings"].(map[string]interface{}) + } + if modelMap["resource_crns"] != nil { + resourceCrns := []string{} + for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { + resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) } + model.ResourceCrns = resourceCrns } + return model, nil +} + +func resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPatchDAConfigDefinitionPropertiesPatch(modelMap map[string]interface{}) (*projectv1.ProjectConfigDefinitionBlockPatchDAConfigDefinitionPropertiesPatch, error) { + model := &projectv1.ProjectConfigDefinitionBlockPatchDAConfigDefinitionPropertiesPatch{} if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { ComplianceProfileModel, err := resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) if err != nil { @@ -867,24 +845,12 @@ func resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlock(modelMap map if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) } - if modelMap["resource_crns"] != nil && len(modelMap["resource_crns"].([]interface{})) > 0 { - resourceCrns := []string{} - for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { - resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) - } - model.ResourceCrns = resourceCrns + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) } - return model, nil -} - -func resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlockDAConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigPatchDefinitionBlockDAConfigDefinitionProperties, error) { - model := &projectv1.ProjectConfigPatchDefinitionBlockDAConfigDefinitionProperties{} if modelMap["name"] != nil && modelMap["name"].(string) != "" { model.Name = core.StringPtr(modelMap["name"].(string)) } - if modelMap["description"] != nil && modelMap["description"].(string) != "" { - model.Description = core.StringPtr(modelMap["description"].(string)) - } if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -896,42 +862,29 @@ func resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlockDAConfigDefin model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } - } - if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { - ComplianceProfileModel, err := resourceIbmProjectConfigMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) - if err != nil { - return model, err - } - model.ComplianceProfile = ComplianceProfileModel - } - if modelMap["locator_id"] != nil && modelMap["locator_id"].(string) != "" { - model.LocatorID = core.StringPtr(modelMap["locator_id"].(string)) + model.Settings = modelMap["settings"].(map[string]interface{}) } return model, nil } -func resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlockResourceConfigDefinitionProperties(modelMap map[string]interface{}) (*projectv1.ProjectConfigPatchDefinitionBlockResourceConfigDefinitionProperties, error) { - model := &projectv1.ProjectConfigPatchDefinitionBlockResourceConfigDefinitionProperties{} - if modelMap["name"] != nil && modelMap["name"].(string) != "" { - model.Name = core.StringPtr(modelMap["name"].(string)) +func resourceIbmProjectConfigMapToProjectConfigDefinitionBlockPatchResourceConfigDefinitionPropertiesPatch(modelMap map[string]interface{}) (*projectv1.ProjectConfigDefinitionBlockPatchResourceConfigDefinitionPropertiesPatch, error) { + model := &projectv1.ProjectConfigDefinitionBlockPatchResourceConfigDefinitionPropertiesPatch{} + if modelMap["resource_crns"] != nil { + resourceCrns := []string{} + for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { + resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) + } + model.ResourceCrns = resourceCrns } if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } if modelMap["environment_id"] != nil && modelMap["environment_id"].(string) != "" { model.EnvironmentID = core.StringPtr(modelMap["environment_id"].(string)) } @@ -943,27 +896,10 @@ func resourceIbmProjectConfigMapToProjectConfigPatchDefinitionBlockResourceConfi model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["settings"] != nil { - bytes, _ := json.Marshal(modelMap["settings"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Settings = newMap - } - } - if modelMap["resource_crns"] != nil && len(modelMap["resource_crns"].([]interface{})) > 0 { - resourceCrns := []string{} - for _, resourceCrnsItem := range modelMap["resource_crns"].([]interface{}) { - resourceCrns = append(resourceCrns, resourceCrnsItem.(string)) - } - model.ResourceCrns = resourceCrns + model.Settings = modelMap["settings"].(map[string]interface{}) } return model, nil } @@ -1040,10 +976,22 @@ func resourceIbmProjectConfigProjectConfigResponseDefinitionToMap(model projectv } else if _, ok := model.(*projectv1.ProjectConfigResponseDefinition); ok { modelMap := make(map[string]interface{}) model := model.(*projectv1.ProjectConfigResponseDefinition) - modelMap["name"] = model.Name + if model.ComplianceProfile != nil { + complianceProfileMap, err := resourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) + if err != nil { + return modelMap, err + } + if len(complianceProfileMap) > 0 { + modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} + } + } + if model.LocatorID != nil { + modelMap["locator_id"] = model.LocatorID + } if model.Description != nil { modelMap["description"] = model.Description } + modelMap["name"] = model.Name if model.EnvironmentID != nil { modelMap["environment_id"] = model.EnvironmentID } @@ -1061,32 +1009,16 @@ func resourceIbmProjectConfigProjectConfigResponseDefinitionToMap(model projectv for k, v := range model.Inputs { inputs[k] = fmt.Sprintf("%v", v) } - if len(inputs) > 0 { - modelMap["inputs"] = inputs - } + modelMap["inputs"] = inputs } if model.Settings != nil { settings := make(map[string]interface{}) for k, v := range model.Settings { settings[k] = fmt.Sprintf("%v", v) } - if len(settings) > 0 { - modelMap["settings"] = settings - } - } - if model.ComplianceProfile != nil { - complianceProfileMap, err := resourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) - if err != nil { - return modelMap, err - } - if len(complianceProfileMap) > 0 { - modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} - } - } - if model.LocatorID != nil { - modelMap["locator_id"] = model.LocatorID + modelMap["settings"] = settings } - if model.ResourceCrns != nil && len(model.ResourceCrns) > 0 { + if model.ResourceCrns != nil { modelMap["resource_crns"] = model.ResourceCrns } return modelMap, nil @@ -1095,20 +1027,6 @@ func resourceIbmProjectConfigProjectConfigResponseDefinitionToMap(model projectv } } -func resourceIbmProjectConfigProjectConfigAuthToMap(model *projectv1.ProjectConfigAuth) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - if model.TrustedProfileID != nil { - modelMap["trusted_profile_id"] = model.TrustedProfileID - } - if model.Method != nil { - modelMap["method"] = model.Method - } - if model.ApiKey != nil { - modelMap["api_key"] = model.ApiKey - } - return modelMap, nil -} - func resourceIbmProjectConfigProjectComplianceProfileToMap(model *projectv1.ProjectComplianceProfile) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.ID != nil { @@ -1129,14 +1047,38 @@ func resourceIbmProjectConfigProjectComplianceProfileToMap(model *projectv1.Proj return modelMap, nil } +func resourceIbmProjectConfigProjectConfigAuthToMap(model *projectv1.ProjectConfigAuth) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.TrustedProfileID != nil { + modelMap["trusted_profile_id"] = model.TrustedProfileID + } + if model.Method != nil { + modelMap["method"] = model.Method + } + if model.ApiKey != nil { + modelMap["api_key"] = model.ApiKey + } + return modelMap, nil +} + func resourceIbmProjectConfigProjectConfigResponseDefinitionDAConfigDefinitionPropertiesToMap(model *projectv1.ProjectConfigResponseDefinitionDAConfigDefinitionProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name + if model.ComplianceProfile != nil { + complianceProfileMap, err := resourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) + if err != nil { + return modelMap, err + } + modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} + } + if model.LocatorID != nil { + modelMap["locator_id"] = model.LocatorID } if model.Description != nil { modelMap["description"] = model.Description } + if model.Name != nil { + modelMap["name"] = model.Name + } if model.EnvironmentID != nil { modelMap["environment_id"] = model.EnvironmentID } @@ -1145,51 +1087,36 @@ func resourceIbmProjectConfigProjectConfigResponseDefinitionDAConfigDefinitionPr if err != nil { return modelMap, err } - if len(authorizationsMap) > 0 { - modelMap["authorizations"] = []map[string]interface{}{authorizationsMap} - } + modelMap["authorizations"] = []map[string]interface{}{authorizationsMap} } if model.Inputs != nil { inputs := make(map[string]interface{}) for k, v := range model.Inputs { inputs[k] = fmt.Sprintf("%v", v) } - if len(inputs) > 0 { - modelMap["inputs"] = inputs - } + modelMap["inputs"] = inputs } if model.Settings != nil { settings := make(map[string]interface{}) for k, v := range model.Settings { settings[k] = fmt.Sprintf("%v", v) } - if len(settings) > 0 { - modelMap["settings"] = settings - } - } - if model.ComplianceProfile != nil { - complianceProfileMap, err := resourceIbmProjectConfigProjectComplianceProfileToMap(model.ComplianceProfile) - if err != nil { - return modelMap, err - } - if len(complianceProfileMap) > 0 { - modelMap["compliance_profile"] = []map[string]interface{}{complianceProfileMap} - } - } - if model.LocatorID != nil { - modelMap["locator_id"] = model.LocatorID + modelMap["settings"] = settings } return modelMap, nil } func resourceIbmProjectConfigProjectConfigResponseDefinitionResourceConfigDefinitionPropertiesToMap(model *projectv1.ProjectConfigResponseDefinitionResourceConfigDefinitionProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.Name != nil { - modelMap["name"] = model.Name + if model.ResourceCrns != nil { + modelMap["resource_crns"] = model.ResourceCrns } if model.Description != nil { modelMap["description"] = model.Description } + if model.Name != nil { + modelMap["name"] = model.Name + } if model.EnvironmentID != nil { modelMap["environment_id"] = model.EnvironmentID } @@ -1205,21 +1132,14 @@ func resourceIbmProjectConfigProjectConfigResponseDefinitionResourceConfigDefini for k, v := range model.Inputs { inputs[k] = fmt.Sprintf("%v", v) } - if len(inputs) > 0 { - modelMap["inputs"] = inputs - } + modelMap["inputs"] = inputs } if model.Settings != nil { settings := make(map[string]interface{}) for k, v := range model.Settings { settings[k] = fmt.Sprintf("%v", v) } - if len(settings) > 0 { - modelMap["settings"] = settings - } - } - if model.ResourceCrns != nil && len(model.ResourceCrns) > 0 { - modelMap["resource_crns"] = model.ResourceCrns + modelMap["settings"] = settings } return modelMap, nil } diff --git a/ibm/service/project/resource_ibm_project_config_test.go b/ibm/service/project/resource_ibm_project_config_test.go index 8a827c81f1..bcbc58de64 100644 --- a/ibm/service/project/resource_ibm_project_config_test.go +++ b/ibm/service/project/resource_ibm_project_config_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project_test diff --git a/ibm/service/project/resource_ibm_project_environment.go b/ibm/service/project/resource_ibm_project_environment.go index d44f2b0497..e005537f17 100644 --- a/ibm/service/project/resource_ibm_project_environment.go +++ b/ibm/service/project/resource_ibm_project_environment.go @@ -1,11 +1,10 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project import ( "context" - "encoding/json" "fmt" "log" @@ -43,16 +42,17 @@ func ResourceIbmProjectEnvironment() *schema.Resource { Description: "The environment definition.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The name of the environment. It is unique within the account across projects and regions.", - }, "description": &schema.Schema{ Type: schema.TypeString, Optional: true, + Default: "", Description: "The description of the environment.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The name of the environment. It is unique within the account across projects and regions.", + }, "authorizations": &schema.Schema{ Type: schema.TypeList, MaxItems: 1, @@ -317,7 +317,7 @@ func resourceIbmProjectEnvironmentUpdate(context context.Context, d *schema.Reso " The resource must be re-created to update this property.", "project_id")) } if d.HasChange("definition") { - definition, err := resourceIbmProjectEnvironmentMapToEnvironmentDefinitionProperties(d.Get("definition.0").(map[string]interface{})) + definition, err := resourceIbmProjectEnvironmentMapToEnvironmentDefinitionPropertiesPatch(d.Get("definition.0").(map[string]interface{})) if err != nil { return diag.FromErr(err) } @@ -365,10 +365,10 @@ func resourceIbmProjectEnvironmentDelete(context context.Context, d *schema.Reso func resourceIbmProjectEnvironmentMapToEnvironmentDefinitionRequiredProperties(modelMap map[string]interface{}) (*projectv1.EnvironmentDefinitionRequiredProperties, error) { model := &projectv1.EnvironmentDefinitionRequiredProperties{} - model.Name = core.StringPtr(modelMap["name"].(string)) if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + model.Name = core.StringPtr(modelMap["name"].(string)) if modelMap["authorizations"] != nil && len(modelMap["authorizations"].([]interface{})) > 0 { AuthorizationsModel, err := resourceIbmProjectEnvironmentMapToProjectConfigAuth(modelMap["authorizations"].([]interface{})[0].(map[string]interface{})) if err != nil { @@ -377,12 +377,7 @@ func resourceIbmProjectEnvironmentMapToEnvironmentDefinitionRequiredProperties(m model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { ComplianceProfileModel, err := resourceIbmProjectEnvironmentMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) @@ -428,14 +423,14 @@ func resourceIbmProjectEnvironmentMapToProjectComplianceProfile(modelMap map[str return model, nil } -func resourceIbmProjectEnvironmentMapToEnvironmentDefinitionProperties(modelMap map[string]interface{}) (*projectv1.EnvironmentDefinitionProperties, error) { - model := &projectv1.EnvironmentDefinitionProperties{} - if modelMap["name"] != nil && modelMap["name"].(string) != "" { - model.Name = core.StringPtr(modelMap["name"].(string)) - } +func resourceIbmProjectEnvironmentMapToEnvironmentDefinitionPropertiesPatch(modelMap map[string]interface{}) (*projectv1.EnvironmentDefinitionPropertiesPatch, error) { + model := &projectv1.EnvironmentDefinitionPropertiesPatch{} if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } if modelMap["authorizations"] != nil && len(modelMap["authorizations"].([]interface{})) > 0 { AuthorizationsModel, err := resourceIbmProjectEnvironmentMapToProjectConfigAuth(modelMap["authorizations"].([]interface{})[0].(map[string]interface{})) if err != nil { @@ -444,12 +439,7 @@ func resourceIbmProjectEnvironmentMapToEnvironmentDefinitionProperties(modelMap model.Authorizations = AuthorizationsModel } if modelMap["inputs"] != nil { - bytes, _ := json.Marshal(modelMap["inputs"].(map[string]interface{})) - newMap := make(map[string]interface{}) - json.Unmarshal(bytes, &newMap) - if len(newMap) > 0 { - model.Inputs = newMap - } + model.Inputs = modelMap["inputs"].(map[string]interface{}) } if modelMap["compliance_profile"] != nil && len(modelMap["compliance_profile"].([]interface{})) > 0 { ComplianceProfileModel, err := resourceIbmProjectEnvironmentMapToProjectComplianceProfile(modelMap["compliance_profile"].([]interface{})[0].(map[string]interface{})) @@ -463,10 +453,10 @@ func resourceIbmProjectEnvironmentMapToEnvironmentDefinitionProperties(modelMap func resourceIbmProjectEnvironmentEnvironmentDefinitionRequiredPropertiesToMap(model *projectv1.EnvironmentDefinitionRequiredProperties) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - modelMap["name"] = model.Name if model.Description != nil { modelMap["description"] = model.Description } + modelMap["name"] = model.Name if model.Authorizations != nil { authorizationsMap, err := resourceIbmProjectEnvironmentProjectConfigAuthToMap(model.Authorizations) if err != nil { @@ -481,9 +471,7 @@ func resourceIbmProjectEnvironmentEnvironmentDefinitionRequiredPropertiesToMap(m for k, v := range model.Inputs { inputs[k] = fmt.Sprintf("%v", v) } - if len(inputs) > 0 { - modelMap["inputs"] = inputs - } + modelMap["inputs"] = inputs } if model.ComplianceProfile != nil { complianceProfileMap, err := resourceIbmProjectEnvironmentProjectComplianceProfileToMap(model.ComplianceProfile) diff --git a/ibm/service/project/resource_ibm_project_environment_test.go b/ibm/service/project/resource_ibm_project_environment_test.go index 5d33d6db32..6a976e3eb8 100644 --- a/ibm/service/project/resource_ibm_project_environment_test.go +++ b/ibm/service/project/resource_ibm_project_environment_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project_test diff --git a/ibm/service/project/resource_ibm_project_test.go b/ibm/service/project/resource_ibm_project_test.go index 20174656ec..661cbb9d89 100644 --- a/ibm/service/project/resource_ibm_project_test.go +++ b/ibm/service/project/resource_ibm_project_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2023 All Rights Reserved. +// Copyright IBM Corp. 2024 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package project_test diff --git a/website/docs/d/project.html.markdown b/website/docs/d/project.html.markdown index 7960495c97..d8db66d883 100644 --- a/website/docs/d/project.html.markdown +++ b/website/docs/d/project.html.markdown @@ -37,7 +37,7 @@ Nested schema for **configs**: * `definition` - (List) The name and description of a project configuration. Nested schema for **definition**: * `description` - (String) A project configuration description. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `name` - (String) The configuration name. It is unique within the account across projects and regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9][a-zA-Z0-9-_ ]*$/`. * `deployment_model` - (String) The configuration type. @@ -85,7 +85,7 @@ Nested schema for **cumulative_needs_attention_view**: * `definition` - (List) The definition of the project. Nested schema for **definition**: * `description` - (String) A brief explanation of the project's use in the configuration of a deployable architecture. It is possible to create a project without providing a description. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `destroy_on_delete` - (Boolean) The policy that indicates whether the resources are destroyed or not when a project is deleted. * `name` - (String) The name of the project. It is unique within the account across regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^'"`<>{}\\x00-\\x1F]+$/`. @@ -97,7 +97,7 @@ Nested schema for **environments**: * `definition` - (List) The environment definition used in the project collection. Nested schema for **definition**: * `description` - (String) The description of the environment. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `name` - (String) The name of the environment. It is unique within the account across projects and regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^'"`<>{}\\x00-\\x1F]+$/`. * `href` - (String) A URL. diff --git a/website/docs/d/project_config.html.markdown b/website/docs/d/project_config.html.markdown index 21021df943..233f91b9d7 100644 --- a/website/docs/d/project_config.html.markdown +++ b/website/docs/d/project_config.html.markdown @@ -58,7 +58,7 @@ Nested schema for **definition**: * `profile_name` - (String) The name of the compliance profile. * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^`<>\\x00-\\x1F]*$/`. * `description` - (String) A project configuration description. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `environment_id` - (String) The ID of the project environment. * Constraints: The maximum length is `128` characters. The value must match regular expression `/^[\\.\\-0-9a-zA-Z]+$/`. * `inputs` - (Map) The input variables for configuration definition and environment. diff --git a/website/docs/d/project_environment.html.markdown b/website/docs/d/project_environment.html.markdown index a975ff2fb4..d06f95d38e 100644 --- a/website/docs/d/project_environment.html.markdown +++ b/website/docs/d/project_environment.html.markdown @@ -58,7 +58,7 @@ Nested schema for **definition**: * `profile_name` - (String) The name of the compliance profile. * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^`<>\\x00-\\x1F]*$/`. * `description` - (String) The description of the environment. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `inputs` - (Map) The input variables for configuration definition and environment. * `name` - (String) The name of the environment. It is unique within the account across projects and regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^'"`<>{}\\x00-\\x1F]+$/`. diff --git a/website/docs/r/project.html.markdown b/website/docs/r/project.html.markdown index 3f0b5d0280..9db8f477ef 100644 --- a/website/docs/r/project.html.markdown +++ b/website/docs/r/project.html.markdown @@ -30,8 +30,8 @@ You can specify the following arguments for this resource. * `definition` - (Required, List) The definition of the project. Nested schema for **definition**: - * `description` - (Optional, String) A brief explanation of the project's use in the configuration of a deployable architecture. It is possible to create a project without providing a description. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * `description` - (Required, String) A brief explanation of the project's use in the configuration of a deployable architecture. It is possible to create a project without providing a description. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `destroy_on_delete` - (Required, Boolean) The policy that indicates whether the resources are destroyed or not when a project is deleted. * `name` - (Required, String) The name of the project. It is unique within the account across regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^'"`<>{}\\x00-\\x1F]+$/`. @@ -52,7 +52,7 @@ Nested schema for **configs**: * `definition` - (List) The name and description of a project configuration. Nested schema for **definition**: * `description` - (String) A project configuration description. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `name` - (String) The configuration name. It is unique within the account across projects and regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9][a-zA-Z0-9-_ ]*$/`. * `deployment_model` - (String) The configuration type. @@ -99,7 +99,7 @@ Nested schema for **environments**: * `definition` - (List) The environment definition used in the project collection. Nested schema for **definition**: * `description` - (String) The description of the environment. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `name` - (String) The name of the environment. It is unique within the account across projects and regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^'"`<>{}\\x00-\\x1F]+$/`. * `href` - (String) A URL. diff --git a/website/docs/r/project_config.html.markdown b/website/docs/r/project_config.html.markdown index ab71abbf40..9459f221fa 100644 --- a/website/docs/r/project_config.html.markdown +++ b/website/docs/r/project_config.html.markdown @@ -57,7 +57,7 @@ Nested schema for **definition**: * `profile_name` - (Optional, String) The name of the compliance profile. * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^`<>\\x00-\\x1F]*$/`. * `description` - (Optional, String) A project configuration description. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `environment_id` - (Optional, String) The ID of the project environment. * Constraints: The maximum length is `128` characters. The value must match regular expression `/^[\\.\\-0-9a-zA-Z]+$/`. * `inputs` - (Optional, Map) The input variables for configuration definition and environment. diff --git a/website/docs/r/project_environment.html.markdown b/website/docs/r/project_environment.html.markdown index 218a8dfa38..db8000b55d 100644 --- a/website/docs/r/project_environment.html.markdown +++ b/website/docs/r/project_environment.html.markdown @@ -53,7 +53,7 @@ Nested schema for **definition**: * `profile_name` - (Optional, String) The name of the compliance profile. * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^`<>\\x00-\\x1F]*$/`. * `description` - (Optional, String) The description of the environment. - * Constraints: The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. + * Constraints: The default value is ``. The maximum length is `1024` characters. The minimum length is `0` characters. The value must match regular expression `/^$|^(?!\\s)(?!.*\\s$)[^\\x00-\\x1F]*$/`. * `inputs` - (Optional, Map) The input variables for configuration definition and environment. * `name` - (Required, String) The name of the environment. It is unique within the account across projects and regions. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^(?!\\s)(?!.*\\s$)[^'"`<>{}\\x00-\\x1F]+$/`. From b09f65d0945964d4a0b495bb6e33c851b76228d9 Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 30 Jan 2024 09:26:48 +0530 Subject: [PATCH 03/34] Refactor Cloud connection refactor data source and documentation (#5053) * cloud connection * Pull ibm_ pi_constants.go from constant-refactor * Remove const replace dataSourceIBMAttr_Read with dataSourceIBMPICloudConnectionRead * Replace bool with Boolean * Update Attribute name * Update website/docs/d/pi_cloud_connections.html.markdown Co-authored-by: Yussuf Shaikh * Update website/docs/d/pi_cloud_connections.html.markdown Co-authored-by: Yussuf Shaikh --------- Co-authored-by: Yussuf Shaikh --- .../data_source_ibm_pi_cloud_connection.go | 171 +++++----- ...ata_source_ibm_pi_cloud_connection_test.go | 9 +- .../data_source_ibm_pi_cloud_connections.go | 171 +++++----- ibm/service/power/ibm_pi_constants.go | 321 +++++++++++++++--- .../docs/d/pi_cloud_connection.html.markdown | 27 +- .../docs/d/pi_cloud_connections.html.markdown | 23 +- 6 files changed, 462 insertions(+), 260 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_cloud_connection.go b/ibm/service/power/data_source_ibm_pi_cloud_connection.go index 8e5bc59f83..f877aac73b 100644 --- a/ibm/service/power/data_source_ibm_pi_cloud_connection.go +++ b/ibm/service/power/data_source_ibm_pi_cloud_connection.go @@ -7,116 +7,104 @@ import ( "context" "log" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" -) - -const ( - PICloudConnectionId = "cloud_connection_id" - PICloudConnectionName = "name" - PICloudConnectionSpeed = "speed" - PICloudConnectionGlobalRouting = "global_routing" - PICloudConnectionMetered = "metered" - PICloudConnectionStatus = "status" - PICloudConnectionClassicEnabled = "classic_enabled" - PICloudConnectionUserIPAddress = "user_ip_address" - PICloudConnectionIBMIPAddress = "ibm_ip_address" - PICloudConnectionPort = "port" - PICloudConnectionNetworks = "networks" - PICloudConnectionClassicGreDest = "gre_destination_address" - PICloudConnectionClassicGreSource = "gre_source_address" - PICloudConnectionVPCEnabled = "vpc_enabled" - PICloudConnectionVPCCRNs = "vpc_crns" - PICloudConnectionConnectionMode = "connection_mode" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPICloudConnection() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPICloudConnectionRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - helpers.PICloudConnectionName: { - Type: schema.TypeString, + Arg_CloudConnectionName: { + Description: "The cloud connection name to be used.", Required: true, - Description: "Cloud Connection Name to be used", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - PICloudConnectionSpeed: { - Type: schema.TypeInt, - Computed: true, + // Attributes + Attr_ClassicEnabled: { + Computed: true, + Description: "Enable classic endpoint destination.", + Type: schema.TypeBool, }, - PICloudConnectionGlobalRouting: { - Type: schema.TypeBool, - Computed: true, + Attr_ConnectionMode: { + Computed: true, + Description: "Type of service the gateway is attached to.", + Type: schema.TypeString, }, - PICloudConnectionMetered: { - Type: schema.TypeBool, - Computed: true, + Attr_GlobalRouting: { + Computed: true, + Description: "Enable global routing for this cloud connection.", + Type: schema.TypeBool, }, - PICloudConnectionStatus: { - Type: schema.TypeString, - Computed: true, + Attr_GreDestinationAddress: { + Computed: true, + Description: "GRE destination IP address.", + Type: schema.TypeString, }, - PICloudConnectionIBMIPAddress: { - Type: schema.TypeString, - Computed: true, + Attr_GreSourceAddress: { + Computed: true, + Description: "GRE auto-assigned source IP address.", + Type: schema.TypeString, }, - PICloudConnectionUserIPAddress: { - Type: schema.TypeString, - Computed: true, + Attr_IBMIPAddress: { + Computed: true, + Description: "The IBM IP address.", + Type: schema.TypeString, }, - PICloudConnectionPort: { - Type: schema.TypeString, - Computed: true, + Attr_Metered: { + Computed: true, + Description: "Enable metering for this cloud connection.", + Type: schema.TypeBool, }, - PICloudConnectionNetworks: { - Type: schema.TypeSet, + Attr_Networks: { Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, Description: "Set of Networks attached to this cloud connection", + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeSet, }, - PICloudConnectionClassicEnabled: { - Type: schema.TypeBool, + Attr_Port: { Computed: true, - Description: "Enable classic endpoint destination", - }, - PICloudConnectionClassicGreDest: { + Description: "Port.", Type: schema.TypeString, + }, + Attr_Speed: { Computed: true, - Description: "GRE destination IP address", + Description: "Speed of the cloud connection (speed in megabits per second)", + Type: schema.TypeInt, }, - PICloudConnectionClassicGreSource: { - Type: schema.TypeString, + Attr_Status: { Computed: true, - Description: "GRE auto-assigned source IP address", + Description: "Link status.", + Type: schema.TypeString, }, - PICloudConnectionVPCEnabled: { - Type: schema.TypeBool, + Attr_UserIPAddress: { Computed: true, - Description: "Enable VPC for this cloud connection", + Description: "User IP address.", + Type: schema.TypeString, }, - PICloudConnectionVPCCRNs: { - Type: schema.TypeSet, + Attr_VPCCRNs: { Computed: true, + Description: "Set of VPCs attached to this cloud connection.", Elem: &schema.Schema{Type: schema.TypeString}, - Description: "Set of VPCs attached to this cloud connection", + Type: schema.TypeSet, }, - PICloudConnectionConnectionMode: { - Type: schema.TypeString, + Attr_VPCEnabled: { Computed: true, - Description: "Type of service the gateway is attached to", + Description: "Enable VPC for this cloud connection.", + Type: schema.TypeBool, }, }, } @@ -128,8 +116,8 @@ func dataSourceIBMPICloudConnectionRead(ctx context.Context, d *schema.ResourceD return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - cloudConnectionName := d.Get(helpers.PICloudConnectionName).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + cloudConnectionName := d.Get(Arg_CloudConnectionName).(string) client := instance.NewIBMPICloudConnectionClient(ctx, sess, cloudInstanceID) // Get API does not work with name for Cloud Connection hence using GetAll (max 2) @@ -165,16 +153,18 @@ func dataSourceIBMPICloudConnectionRead(ctx context.Context, d *schema.ResourceD } d.SetId(*cloudConnection.CloudConnectionID) - d.Set(helpers.PICloudConnectionName, cloudConnection.Name) - d.Set(PICloudConnectionGlobalRouting, cloudConnection.GlobalRouting) - d.Set(PICloudConnectionMetered, cloudConnection.Metered) - d.Set(PICloudConnectionIBMIPAddress, cloudConnection.IbmIPAddress) - d.Set(PICloudConnectionUserIPAddress, cloudConnection.UserIPAddress) - d.Set(PICloudConnectionStatus, cloudConnection.LinkStatus) - d.Set(PICloudConnectionPort, cloudConnection.Port) - d.Set(PICloudConnectionSpeed, cloudConnection.Speed) - d.Set(helpers.PICloudInstanceId, cloudInstanceID) - d.Set(PICloudConnectionConnectionMode, cloudConnection.ConnectionMode) + + d.Set(Arg_CloudInstanceID, cloudInstanceID) + d.Set(Arg_CloudConnectionName, cloudConnection.Name) + + d.Set(Attr_GlobalRouting, cloudConnection.GlobalRouting) + d.Set(Attr_Metered, cloudConnection.Metered) + d.Set(Attr_IBMIPAddress, cloudConnection.IbmIPAddress) + d.Set(Attr_UserIPAddress, cloudConnection.UserIPAddress) + d.Set(Attr_Status, cloudConnection.LinkStatus) + d.Set(Attr_Port, cloudConnection.Port) + d.Set(Attr_Speed, cloudConnection.Speed) + d.Set(Attr_ConnectionMode, cloudConnection.ConnectionMode) if cloudConnection.Networks != nil { networks := make([]string, len(cloudConnection.Networks)) for i, ccNetwork := range cloudConnection.Networks { @@ -182,24 +172,25 @@ func dataSourceIBMPICloudConnectionRead(ctx context.Context, d *schema.ResourceD networks[i] = *ccNetwork.NetworkID } } - d.Set(PICloudConnectionNetworks, networks) + d.Set(Attr_Networks, networks) } if cloudConnection.Classic != nil { - d.Set(PICloudConnectionClassicEnabled, cloudConnection.Classic.Enabled) + d.Set(Attr_ClassicEnabled, cloudConnection.Classic.Enabled) if cloudConnection.Classic.Gre != nil { - d.Set(PICloudConnectionClassicGreDest, cloudConnection.Classic.Gre.DestIPAddress) - d.Set(PICloudConnectionClassicGreSource, cloudConnection.Classic.Gre.SourceIPAddress) + d.Set(Attr_GreDestinationAddress, cloudConnection.Classic.Gre.DestIPAddress) + d.Set(Attr_GreSourceAddress, cloudConnection.Classic.Gre.SourceIPAddress) } } if cloudConnection.Vpc != nil { - d.Set(PICloudConnectionVPCEnabled, cloudConnection.Vpc.Enabled) + d.Set(Attr_VPCEnabled, cloudConnection.Vpc.Enabled) if cloudConnection.Vpc.Vpcs != nil && len(cloudConnection.Vpc.Vpcs) > 0 { vpcCRNs := make([]string, len(cloudConnection.Vpc.Vpcs)) for i, vpc := range cloudConnection.Vpc.Vpcs { vpcCRNs[i] = *vpc.VpcID } - d.Set(PICloudConnectionVPCCRNs, vpcCRNs) + d.Set(Attr_VPCCRNs, vpcCRNs) } } + return nil } diff --git a/ibm/service/power/data_source_ibm_pi_cloud_connection_test.go b/ibm/service/power/data_source_ibm_pi_cloud_connection_test.go index 732b10ad1f..60eda0cb08 100644 --- a/ibm/service/power/data_source_ibm_pi_cloud_connection_test.go +++ b/ibm/service/power/data_source_ibm_pi_cloud_connection_test.go @@ -30,9 +30,8 @@ func TestAccIBMPICloudConnectionDataSource_basic(t *testing.T) { func testAccCheckIBMPICloudConnectionDataSourceConfig() string { return fmt.Sprintf(` - data "ibm_pi_cloud_connection" "example" { - pi_cloud_connection_name = "%s" - pi_cloud_instance_id = "%s" - } - `, acc.PiCloudConnectionName, acc.Pi_cloud_instance_id) + data "ibm_pi_cloud_connection" "example" { + pi_cloud_connection_name = "%s" + pi_cloud_instance_id = "%s" + }`, acc.PiCloudConnectionName, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_cloud_connections.go b/ibm/service/power/data_source_ibm_pi_cloud_connections.go index ad5a35e434..2e99b1ea97 100644 --- a/ibm/service/power/data_source_ibm_pi_cloud_connections.go +++ b/ibm/service/power/data_source_ibm_pi_cloud_connections.go @@ -7,113 +7,118 @@ import ( "context" "log" - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -/* -Datasource to get the list of Cloud Connections in a power instance -*/ - -const PICloudConnections = "connections" - +// Datasource to list Cloud Connections in a power instance func DataSourceIBMPICloudConnections() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPICloudConnectionsRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - PICloudConnections: { - Type: schema.TypeList, - Computed: true, + + // Attributes + Attr_Connections: { + Computed: true, + Description: "List of all the Cloud Connections.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - PICloudConnectionId: { - Type: schema.TypeString, - Computed: true, + Attr_ClassicEnabled: { + Computed: true, + Description: "Enable classic endpoint destination.", + Type: schema.TypeBool, }, - PICloudConnectionName: { - Type: schema.TypeString, - Computed: true, + Attr_CloudConnectionID: { + Computed: true, + Description: "The unique identifier of the cloud connection.", + Type: schema.TypeString, }, - PICloudConnectionSpeed: { - Type: schema.TypeInt, - Computed: true, + Attr_ConnectionMode: { + Computed: true, + Description: "Type of service the gateway is attached to.", + Type: schema.TypeString, }, - PICloudConnectionGlobalRouting: { - Type: schema.TypeBool, - Computed: true, + Attr_GlobalRouting: { + Computed: true, + Description: "Enable global routing for this cloud connection.", + Type: schema.TypeBool, }, - PICloudConnectionMetered: { - Type: schema.TypeBool, - Computed: true, + Attr_GreDestinationAddress: { + Computed: true, + Description: "GRE destination IP address.", + Type: schema.TypeString, }, - PICloudConnectionStatus: { - Type: schema.TypeString, - Computed: true, + Attr_GreSourceAddress: { + Computed: true, + Description: "GRE auto-assigned source IP address.", + Type: schema.TypeString, }, - PICloudConnectionIBMIPAddress: { - Type: schema.TypeString, - Computed: true, + Attr_IBMIPAddress: { + Computed: true, + Description: "IBM IP address.", + Type: schema.TypeString, }, - PICloudConnectionUserIPAddress: { - Type: schema.TypeString, - Computed: true, + Attr_Metered: { + Computed: true, + Description: "Enable metering for this cloud connection.", + Type: schema.TypeBool, }, - PICloudConnectionPort: { - Type: schema.TypeString, - Computed: true, + Attr_Name: { + Computed: true, + Description: "Name of the cloud connection.", + Type: schema.TypeString, }, - PICloudConnectionNetworks: { - Type: schema.TypeSet, + Attr_Networks: { Computed: true, + Description: "Set of Networks attached to this cloud connection.", Elem: &schema.Schema{Type: schema.TypeString}, - Description: "Set of Networks attached to this cloud connection", + Type: schema.TypeSet, }, - PICloudConnectionClassicEnabled: { - Type: schema.TypeBool, + Attr_Port: { Computed: true, - Description: "Enable classic endpoint destination", - }, - PICloudConnectionClassicGreDest: { + Description: "Port.", Type: schema.TypeString, + }, + Attr_Speed: { Computed: true, - Description: "GRE destination IP address", + Description: "Speed of the cloud connection (speed in megabits per second).", + Type: schema.TypeInt, }, - PICloudConnectionClassicGreSource: { - Type: schema.TypeString, + Attr_Status: { Computed: true, - Description: "GRE auto-assigned source IP address", + Description: "Link status.", + Type: schema.TypeString, }, - PICloudConnectionVPCEnabled: { - Type: schema.TypeBool, + Attr_UserIPAddress: { Computed: true, - Description: "Enable VPC for this cloud connection", + Description: "User IP address.", + Type: schema.TypeString, }, - PICloudConnectionVPCCRNs: { - Type: schema.TypeSet, + Attr_VPCCRNs: { Computed: true, + Description: "Set of VPCs attached to this cloud connection.", Elem: &schema.Schema{Type: schema.TypeString}, - Description: "Set of VPCs attached to this cloud connection", + Type: schema.TypeSet, }, - PICloudConnectionConnectionMode: { - Type: schema.TypeString, + Attr_VPCEnabled: { Computed: true, - Description: "Type of service the gateway is attached to", + Description: "Enable VPC for this cloud connection.", + Type: schema.TypeBool, }, }, }, + Type: schema.TypeList, }, }, } @@ -125,8 +130,8 @@ func dataSourceIBMPICloudConnectionsRead(ctx context.Context, d *schema.Resource return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - client := st.NewIBMPICloudConnectionClient(ctx, sess, cloudInstanceID) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + client := instance.NewIBMPICloudConnectionClient(ctx, sess, cloudInstanceID) cloudConnections, err := client.GetAll() if err != nil { @@ -137,16 +142,16 @@ func dataSourceIBMPICloudConnectionsRead(ctx context.Context, d *schema.Resource result := make([]map[string]interface{}, 0, len(cloudConnections.CloudConnections)) for _, cloudConnection := range cloudConnections.CloudConnections { cc := map[string]interface{}{ - PICloudConnectionId: *cloudConnection.CloudConnectionID, - PICloudConnectionName: *cloudConnection.Name, - PICloudConnectionGlobalRouting: *cloudConnection.GlobalRouting, - PICloudConnectionMetered: *cloudConnection.Metered, - PICloudConnectionIBMIPAddress: *cloudConnection.IbmIPAddress, - PICloudConnectionUserIPAddress: *cloudConnection.UserIPAddress, - PICloudConnectionStatus: *cloudConnection.LinkStatus, - PICloudConnectionPort: *cloudConnection.Port, - PICloudConnectionSpeed: *cloudConnection.Speed, - PICloudConnectionConnectionMode: cloudConnection.ConnectionMode, + Attr_CloudConnectionID: *cloudConnection.CloudConnectionID, + Attr_ConnectionMode: cloudConnection.ConnectionMode, + Attr_GlobalRouting: *cloudConnection.GlobalRouting, + Attr_IBMIPAddress: *cloudConnection.IbmIPAddress, + Attr_Metered: *cloudConnection.Metered, + Attr_Name: *cloudConnection.Name, + Attr_Port: *cloudConnection.Port, + Attr_Speed: *cloudConnection.Speed, + Attr_Status: *cloudConnection.LinkStatus, + Attr_UserIPAddress: *cloudConnection.UserIPAddress, } if cloudConnection.Networks != nil { @@ -156,23 +161,23 @@ func dataSourceIBMPICloudConnectionsRead(ctx context.Context, d *schema.Resource networks[i] = *ccNetwork.NetworkID } } - cc[PICloudConnectionNetworks] = networks + cc[Attr_Networks] = networks } if cloudConnection.Classic != nil { - cc[PICloudConnectionClassicEnabled] = cloudConnection.Classic.Enabled + cc[Attr_ClassicEnabled] = cloudConnection.Classic.Enabled if cloudConnection.Classic.Gre != nil { - cc[PICloudConnectionClassicGreDest] = cloudConnection.Classic.Gre.DestIPAddress - cc[PICloudConnectionClassicGreSource] = cloudConnection.Classic.Gre.SourceIPAddress + cc[Attr_GreDestinationAddress] = cloudConnection.Classic.Gre.DestIPAddress + cc[Attr_GreSourceAddress] = cloudConnection.Classic.Gre.SourceIPAddress } } if cloudConnection.Vpc != nil { - cc[PICloudConnectionVPCEnabled] = cloudConnection.Vpc.Enabled + cc[Attr_VPCEnabled] = cloudConnection.Vpc.Enabled if cloudConnection.Vpc.Vpcs != nil && len(cloudConnection.Vpc.Vpcs) > 0 { vpcCRNs := make([]string, len(cloudConnection.Vpc.Vpcs)) for i, vpc := range cloudConnection.Vpc.Vpcs { vpcCRNs[i] = *vpc.VpcID } - cc[PICloudConnectionVPCCRNs] = vpcCRNs + cc[Attr_VPCCRNs] = vpcCRNs } } @@ -181,7 +186,7 @@ func dataSourceIBMPICloudConnectionsRead(ctx context.Context, d *schema.Resource var genID, _ = uuid.GenerateUUID() d.SetId(genID) - d.Set(PICloudConnections, result) + d.Set(Attr_Connections, result) return nil } diff --git a/ibm/service/power/ibm_pi_constants.go b/ibm/service/power/ibm_pi_constants.go index b4f18b330c..db553ec77d 100644 --- a/ibm/service/power/ibm_pi_constants.go +++ b/ibm/service/power/ibm_pi_constants.go @@ -3,18 +3,253 @@ package power import "time" const ( - // used by all - Arg_CloudInstanceID = "pi_cloud_instance_id" + // Arguments + Arg_CloudConnectionName = "pi_cloud_connection_name" + Arg_CloudInstanceID = "pi_cloud_instance_id" + Arg_ImageName = "pi_image_name" + Arg_InstanceName = "pi_instance_name" + Arg_Key = "pi_ssh_key" + Arg_KeyName = "pi_key_name" + Arg_NetworkName = "pi_network_name" + Arg_PlacementGroupName = "pi_placement_group_name" + Arg_SAP = "sap" + Arg_SAPProfileID = "pi_sap_profile_id" + Arg_SPPPlacementGroupID = "pi_spp_placement_group_id" + Arg_SPPPlacementGroupName = "pi_spp_placement_group_name" + Arg_SPPPlacementGroupPolicy = "pi_spp_placement_group_policy" + Arg_SharedProcessorPoolHostGroup = "pi_shared_processor_pool_host_group" + Arg_SharedProcessorPoolID = "pi_shared_processor_pool_id" + Arg_SharedProcessorPoolName = "pi_shared_processor_pool_name" + Arg_SharedProcessorPoolPlacementGroupID = "pi_shared_processor_pool_placement_group_id" + Arg_SharedProcessorPoolReservedCores = "pi_shared_processor_pool_reserved_cores" + Arg_StoragePool = "pi_storage_pool" + Arg_StorageType = "pi_storage_type" + Arg_VTL = "vtl" + Arg_VolumeGroupID = "pi_volume_group_id" + Arg_VolumeID = "pi_volume_id" + Arg_VolumeOnboardingID = "pi_volume_onboarding_id" - // Keys - Arg_KeyName = "pi_key_name" - Arg_Key = "pi_ssh_key" + // Attributes + Attr_AccessConfig = "access_config" + Attr_Action = "action" + Attr_Addresses = "addresses" + Attr_AllocatedCores = "allocated_cores" + Attr_Architecture = "architecture" + Attr_Auxiliary = "auxiliary" + Attr_AuxiliaryChangedVolumeName = "auxiliary_changed_volume_name" + Attr_AuxiliaryVolumeName = "auxiliary_volume_name" + Attr_AvailabilityZone = "availability_zone" + Attr_AvailableCores = "available_cores" + Attr_AvailableIPCount = "available_ip_count" + Attr_BootVolumeID = "boot_volume_id" + Attr_Bootable = "bootable" + Attr_CIDR = "cidr" + Attr_CPUs = "cpus" + Attr_CRN = "crn" + Attr_Capabilities = "capabilities" + Attr_Capacity = "capacity" + Attr_Certified = "certified" + Attr_ClassicEnabled = "classic_enabled" + Attr_CloudConnectionID = "cloud_connection_id" + Attr_CloudInstanceID = "cloud_instance_id" + Attr_CloudInstances = "cloud_instances" + Attr_Code = "code" + Attr_ConnectionMode = "connection_mode" + Attr_Connections = "connections" + Attr_ConsistencyGroupName = "consistency_group_name" + Attr_ConsoleLanguages = "console_languages" + Attr_ContainerFormat = "container_format" + Attr_CopyRate = "copy_rate" + Attr_CopyType = "copy_type" + Attr_CoreMemoryRatio = "core_memory_ratio" + Attr_Cores = "cores" + Attr_CreateTime = "create_time" + Attr_CreationDate = "creation_date" + Attr_CyclePeriodSeconds = "cycle_period_seconds" + Attr_CyclingMode = "cycling_mode" + Attr_DNS = "dns" + Attr_Datacenters = "datacenters" + Attr_Default = "default" + Attr_DeploymentType = "deployment_type" + Attr_Description = "description" + Attr_DisasterRecoveryLocations = "disaster_recovery_locations" + Attr_DiskFormat = "disk_format" + Attr_DiskType = "disk_type" + Attr_Enabled = "enabled" + Attr_Endianness = "endianness" + Attr_ExternalIP = "external_ip" + Attr_FailureMessage = "failure_message" + Attr_FlashCopyMappings = "flash_copy_mappings" + Attr_FlashCopyName = "flash_copy_name" + Attr_FreezeTime = "freeze_time" + Attr_Gateway = "gateway" + Attr_GlobalRouting = "global_routing" + Attr_GreDestinationAddress = "gre_destination_address" + Attr_GreSourceAddress = "gre_source_address" + Attr_GroupID = "group_id" + Attr_HealthStatus = "health_status" + Attr_HostID = "host_id" + Attr_Href = "href" + Attr_Hypervisor = "hypervisor" + Attr_HypervisorType = "hypervisor_type" + Attr_IBMIPAddress = "ibm_ip_address" + Attr_ID = "id" + Attr_IP = "ip" + Attr_IPAddress = "ipaddress" + Attr_IPOctet = "ipoctet" + Attr_ImageID = "image_id" + Attr_ImageInfo = "image_info" + Attr_ImageType = "image_type" + Attr_Images = "images" + Attr_InputVolumes = "input_volumes" + Attr_InstanceSnapshots = "instance_snapshots" + Attr_InstanceVolumes = "instance_volumes" + Attr_Instances = "instances" + Attr_IsActive = "is_active" + Attr_Jumbo = "jumbo" + Attr_Key = "key" + Attr_KeyCreationDate = "creation_date" + Attr_KeyID = "key_id" + Attr_KeyName = "name" + Attr_Keys = "keys" + Attr_Language = "language" + Attr_LastUpdateDate = "last_update_date" + Attr_LastUpdatedDate = "last_updated_date" + Attr_Leases = "leases" + Attr_LicenseRepositoryCapacity = "license_repository_capacity" + Attr_Location = "location" + Attr_MTU = "mtu" + Attr_MacAddress = "macaddress" + Attr_MasterChangedVolumeName = "master_changed_volume_name" + Attr_MasterVolumeName = "master_volume_name" + Attr_Max = "max" + Attr_MaxAllocationSize = "max_allocation_size" + Attr_MaxAvailable = "max_available" + Attr_MaxCoresAvailable = "max_cores_available" + Attr_MaxMem = "maxmem" + Attr_MaxMemoryAvailable = "max_memory_available" + Attr_MaxProc = "maxproc" + Attr_MaxVirtualCores = "max_virtual_cores" + Attr_MaximumStorageAllocation = "max_storage_allocation" + Attr_Members = "members" + Attr_Memory = "memory" + Attr_Message = "message" + Attr_Metered = "metered" + Attr_Min = "min" + Attr_MinMem = "minmem" + Attr_MinProc = "minproc" + Attr_MinVirtualCores = "min_virtual_cores" + Attr_MirroringState = "mirroring_state" + Attr_Name = "name" + Attr_NetworkID = "network_id" + Attr_NetworkName = "network_name" + Attr_NetworkPorts = "network_ports" + Attr_Networks = "networks" + Attr_NumberOfVolumes = "number_of_volumes" + Attr_Onboardings = "onboardings" + Attr_OperatingSystem = "operating_system" + Attr_PVMInstanceID = "pvm_instance_id" + Attr_PVMInstances = "pvm_instances" + Attr_PVMSnapshots = "pvm_snapshots" + Attr_PercentComplete = "percent_complete" + Attr_PinPolicy = "pin_policy" + Attr_PlacementGroupID = "placement_group_id" + Attr_PlacementGroups = "placement_groups" + Attr_Policy = "policy" + Attr_Pool = "pool" + Attr_PoolName = "pool_name" + Attr_Port = "port" + Attr_PortID = "portid" + Attr_PrimaryRole = "primary_role" + Attr_ProcType = "proctype" + Attr_Processors = "processors" + Attr_ProfileID = "profile_id" + Attr_Profiles = "profiles" + Attr_Progress = "progress" + Attr_PublicIP = "public_ip" + Attr_Region = "region" + Attr_RemoteCopyID = "remote_copy_id" + Attr_RemoteCopyRelationshipNames = "remote_copy_relationship_names" + Attr_RemoteCopyRelationships = "remote_copy_relationships" + Attr_ReplicationEnabled = "replication_enabled" + Attr_ReplicationSites = "replication_sites" + Attr_ReplicationStatus = "replication_status" + Attr_ReplicationType = "replication_type" + Attr_ReservedCores = "reserved_cores" + Attr_ResultsOnboardedVolumes = "results_onboarded_volumes" + Attr_ResultsVolumeOnboardingFailures = "results_volume_onboarding_failures" + Attr_SPPPlacementGroups = "spp_placement_groups" + Attr_SSHKey = "ssh_key" + Attr_Shareable = "shreable" + Attr_SharedCoreRatio = "shared_core_ratio" + Attr_SharedProcessorPool = "shared_processor_pool" + Attr_SharedProcessorPoolID = "shared_processor_pool_id" + Attr_SharedProcessorPoolPlacementGroups = "spp_placement_groups" + Attr_SharedProcessorPoolStatus = "status" + Attr_SharedProcessorPools = "shared_processor_pools" + Attr_SharedProcessorPoolName = "name" + Attr_SharedProcessorPoolHostID = "host_id" + Attr_SharedProcessorPoolReservedCores = "reserved_cores" + Attr_SharedProcessorPoolAvailableCores = "available_cores" + Attr_SharedProcessorPoolAllocatedCores = "allocated_cores" + Attr_SharedProcessorPoolStatusDetail = "status_detail" + Attr_SharedProcessorPoolInstances = "instances" + Attr_SharedProcessorPoolInstanceCpus = "cpus" + Attr_SharedProcessorPoolInstanceUncapped = "uncapped" + Attr_SharedProcessorPoolInstanceAvailabilityZone = "availability_zone" + Attr_SharedProcessorPoolInstanceId = "id" + Attr_SharedProcessorPoolInstanceMemory = "memory" + Attr_SharedProcessorPoolInstanceName = "name" + Attr_SharedProcessorPoolInstanceStatus = "status" + Attr_SharedProcessorPoolInstanceVcpus = "vcpus" + Attr_Size = "size" + Attr_SourceVolumeName = "source_volume_name" + Attr_Speed = "speed" + Attr_StartTime = "start_time" + Attr_State = "state" + Attr_Status = "status" + Attr_StatusDescriptionErrors = "status_description_errors" + Attr_StatusDetail = "status_detail" + Attr_StoragePool = "storage_pool" + Attr_StoragePoolAffinity = "storage_pool_affinity" + Attr_StoragePoolsCapacity = "storage_pools_capacity" + Attr_StorageType = "storage_type" + Attr_StorageTypesCapacity = "storage_types_capacity" + Attr_Synchronized = "synchronized" + Attr_SysType = "systype" + Attr_SystemPoolName = "system_pool_name" + Attr_SystemPools = "system_pools" + Attr_Systems = "systems" + Attr_TargetVolumeName = "target_volume_name" + Attr_TenantID = "tenant_id" + Attr_TenantName = "tenant_name" + Attr_TotalCapacity = "total_capacity" + Attr_TotalInstances = "total_instances" + Attr_TotalMemoryConsumed = "total_memory_consumed" + Attr_TotalProcessorsConsumed = "total_processors_consumed" + Attr_TotalSSDStorageConsumed = "total_ssd_storage_consumed" + Attr_TotalStandardStorageConsumed = "total_standard_storage_consumed" + Attr_Type = "type" + Attr_URL = "url" + Attr_Uncapped = "uncapped" + Attr_UsedIPCount = "used_ip_count" + Attr_UsedIPPercent = "used_ip_percent" + Attr_UserIPAddress = "user_ip_address" + Attr_VCPUs = "vcpus" + Attr_VLanID = "vlan_id" + Attr_VPCCRNs = "vpc_crns" + Attr_VPCEnabled = "vpc_enabled" + Attr_VirtualCoresAssigned = "virtual_cores_assigned" + Attr_VolumeGroupName = "volume_group_name" + Attr_VolumeGroups = "volume_groups" + Attr_VolumeIDs = "volume_ids" + Attr_VolumePool = "volume_pool" + Attr_VolumeSnapshots = "volume_snapshots" + Attr_Volumes = "volumes" + Attr_WWN = "wwn" + Attr_Workspaces = "workspaces" - Attr_KeyID = "key_id" - Attr_Keys = "keys" - Attr_KeyCreationDate = "creation_date" - Attr_Key = "ssh_key" - Attr_KeyName = "name" + // TODO: Second Half Cleanup, remove extra variables // SAP Profile PISAPProfiles = "profiles" @@ -47,10 +282,6 @@ const ( Arg_PVMInstanceActionType = "pi_action" Arg_PVMInstanceHealthStatus = "pi_health_status" - Attr_Status = "status" - Attr_Progress = "progress" - Attr_HealthStatus = "health_status" - PVMInstanceHealthOk = "OK" PVMInstanceHealthWarning = "WARNING" @@ -58,16 +289,33 @@ const ( warningTimeOut = 60 * time.Second activeTimeOut = 2 * time.Minute // power service instance capabilities - CUSTOM_VIRTUAL_CORES = "custom-virtualcores" - PIInstanceDeploymentType = "pi_deployment_type" - PIInstanceNetwork = "pi_network" - PIInstanceStoragePool = "pi_storage_pool" - PISAPInstanceProfileID = "pi_sap_profile_id" - PISAPInstanceDeploymentType = "pi_sap_deployment_type" - PIInstanceStoragePoolAffinity = "pi_storage_pool_affinity" - Arg_PIInstanceSharedProcessorPool = "pi_shared_processor_pool" + CUSTOM_VIRTUAL_CORES = "custom-virtualcores" + + PICloudConnectionId = "cloud_connection_id" + PICloudConnectionStatus = "status" + PICloudConnectionIBMIPAddress = "ibm_ip_address" + PICloudConnectionUserIPAddress = "user_ip_address" + PICloudConnectionPort = "port" + PICloudConnectionClassicGreSource = "gre_source_address" + PICloudConnectionConnectionMode = "connection_mode" + PIInstanceDeploymentType = "pi_deployment_type" + PIInstanceMigratable = "pi_migratable" + PIInstanceNetwork = "pi_network" + PIInstanceLicenseRepositoryCapacity = "pi_license_repository_capacity" + PIInstanceStoragePool = "pi_storage_pool" + PIInstanceStorageType = "pi_storage_type" + PISAPInstanceProfileID = "pi_sap_profile_id" + PISAPInstanceDeploymentType = "pi_sap_deployment_type" + PIInstanceSharedProcessorPool = "pi_shared_processor_pool" + PIInstanceStorageConnection = "pi_storage_connection" + PIInstanceStoragePoolAffinity = "pi_storage_pool_affinity" + + PIInstanceUserData = "pi_user_data" + PIInstanceVolumeIds = "pi_volume_ids" + Attr_PIInstanceSharedProcessorPool = "shared_processor_pool" Attr_PIInstanceSharedProcessorPoolID = "shared_processor_pool_id" + Arg_PIInstanceSharedProcessorPool = "pi_shared_processor_pool" // Placement Group PIPlacementGroupID = "placement_group_id" @@ -109,37 +357,10 @@ const ( // Cloud Connections PICloudConnectionTransitEnabled = "pi_cloud_connection_transit_enabled" - // Shared Processor Pool - Arg_SharedProcessorPoolName = "pi_shared_processor_pool_name" - Arg_SharedProcessorPoolHostGroup = "pi_shared_processor_pool_host_group" - Arg_SharedProcessorPoolPlacementGroupID = "pi_shared_processor_pool_placement_group_id" - Arg_SharedProcessorPoolReservedCores = "pi_shared_processor_pool_reserved_cores" - Arg_SharedProcessorPoolID = "pi_shared_processor_pool_id" - Attr_SharedProcessorPoolID = "shared_processor_pool_id" - Attr_SharedProcessorPoolName = "name" - Attr_SharedProcessorPoolReservedCores = "reserved_cores" - Attr_SharedProcessorPoolAvailableCores = "available_cores" - Attr_SharedProcessorPoolAllocatedCores = "allocated_cores" - Attr_SharedProcessorPoolHostID = "host_id" - Attr_SharedProcessorPoolStatus = "status" - Attr_SharedProcessorPoolStatusDetail = "status_detail" - Attr_SharedProcessorPoolPlacementGroups = "spp_placement_groups" - Attr_SharedProcessorPoolInstances = "instances" - Attr_SharedProcessorPoolInstanceCpus = "cpus" - Attr_SharedProcessorPoolInstanceUncapped = "uncapped" - Attr_SharedProcessorPoolInstanceAvailabilityZone = "availability_zone" - Attr_SharedProcessorPoolInstanceId = "id" - Attr_SharedProcessorPoolInstanceMemory = "memory" - Attr_SharedProcessorPoolInstanceName = "name" - Attr_SharedProcessorPoolInstanceStatus = "status" - Attr_SharedProcessorPoolInstanceVcpus = "vcpus" - // SPP Placement Group - Arg_SPPPlacementGroupName = "pi_spp_placement_group_name" - Arg_SPPPlacementGroupPolicy = "pi_spp_placement_group_policy" + Attr_SPPPlacementGroupID = "spp_placement_group_id" Attr_SPPPlacementGroupMembers = "members" - Arg_SPPPlacementGroupID = "pi_spp_placement_group_id" Attr_SPPPlacementGroupPolicy = "policy" Attr_SPPPlacementGroupName = "name" diff --git a/website/docs/d/pi_cloud_connection.html.markdown b/website/docs/d/pi_cloud_connection.html.markdown index ca42eb4117..2e6de4d4bd 100644 --- a/website/docs/d/pi_cloud_connection.html.markdown +++ b/website/docs/d/pi_cloud_connection.html.markdown @@ -7,11 +7,9 @@ description: |- --- # ibm_pi_cloud_connection - Retrieve information about an existing IBM Cloud Power Virtual Server Cloud cloud connection. For more information, about IBM power virtual server cloud, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_cloud_connection" "example" { pi_cloud_connection_name = "test_cloud_connection" @@ -20,15 +18,12 @@ data "ibm_pi_cloud_connection" "example" { ``` **Notes** - - Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. - If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - - `region` - `lon` - `zone` - `lon04` - Example usage: - +Example usage: ```terraform provider "ibm" { region = "lon" @@ -37,28 +32,26 @@ data "ibm_pi_cloud_connection" "example" { ``` ## Argument reference - Review the argument references that you can specify for your data source. - `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. - `pi_cloud_connection_name` - (Required, String) The cloud connection name to be used. ## Attribute reference - In addition to all argument reference list, you can access the following attribute references after your data source is created. -- `id` - (String) The unique identifier of the cloud connection. -- `classic_enabled` - (Bool) Is classic endpoint destination enabled? +- `classic_enabled` - (Boolean) Enable classic endpoint destination. - `connection_mode` - (String) Type of service the gateway is attached to. -- `global_routing` - (String) Is global routing enabled for this cloud connection. -- `gre_destination_address` - (String) The GRE destination IP address. -- `gre_source_address` - (String) The GRE auto-assigned source IP address. +- `global_routing` - (String) Enable global routing for this cloud connection. +- `gre_destination_address` - (String) GRE destination IP address. +- `gre_source_address` - (String) GRE auto-assigned source IP address. +- `id` - (String) The unique identifier of the cloud connection. - `ibm_ip_address` - (String) The IBM IP address. -- `metered` - (String) Is metered enabled for this cloud connection. -- `networks` - (Set of String) Set of Networks attached to this cloud connection. +- `metered` - (String) Enable metering for this cloud connection. +- `networks` - (Set) Set of Networks attached to this cloud connection. - `port` - (String) Port. - `speed` - (Integer) Speed of the cloud connection (speed in megabits per second). - `status` - (String) Link status. - `user_ip_address` - (String) User IP address. -- `vpc_crns` - (Set of String) Set of VPCs attached to this cloud connection. -- `vpc_enabled` - (Bool) Is VPC enabled for this cloud connection? +- `vpc_crns` - (Set) Set of VPCs attached to this cloud connection. +- `vpc_enabled` - (Boolean) Enable VPC for this cloud connection. diff --git a/website/docs/d/pi_cloud_connections.html.markdown b/website/docs/d/pi_cloud_connections.html.markdown index 8925fd81e6..0ab04e36da 100644 --- a/website/docs/d/pi_cloud_connections.html.markdown +++ b/website/docs/d/pi_cloud_connections.html.markdown @@ -7,11 +7,9 @@ description: |- --- # ibm_pi_cloud_connections - Retrieve information about all cloud connections as a read-only data source. For more information, about IBM power virtual server cloud, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_cloud_connections" "example" { pi_cloud_instance_id = "" @@ -19,15 +17,13 @@ data "ibm_pi_cloud_connections" "example" { ``` **Notes** - - Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. - If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - `region` - `lon` - `zone` - `lon04` - Example usage: - +Example usage: ```terraform provider "ibm" { region = "lon" @@ -36,32 +32,29 @@ data "ibm_pi_cloud_connections" "example" { ``` ## Argument reference - Review the argument references that you can specify for your data source. - `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. ## Attribute reference - In addition to all argument reference list, you can access the following attribute references after your data source is created. - `connections` - (List) List of all the Cloud Connections. Nested scheme for `connections`: - - - `classic_enabled` - (Bool) Is Classic endpoint destination enabled. + - `classic_enabled` - (Boolean) Enable classic endpoint destination. - `cloud_connection_id` - (String) The unique identifier of the cloud connection. - - `global_routing` - (String) Is global routing enabled for this cloud connection. + - `connection_mode` - (String) Type of service the gateway is attached to. + - `global_routing` - (String) Enable global routing for this cloud connection. - `gre_destination_address` - (String) GRE destination IP address. - `gre_source_address` - (String) GRE auto-assigned source IP address. - `ibm_ip_address` - (String) IBM IP address. - - `metered` - (String) Is metered enabled for this cloud connection. + - `metered` - (String) Enable metering for this cloud connection. - `name` - (String) Name of the cloud connection. - - `networks` - (Set of String) Set of Networks attached to this cloud connection. + - `networks` - (Set) Set of Networks attached to this cloud connection. - `port` - (String) Port. - `speed` - (Integer) Speed of the cloud connection (speed in megabits per second). - `status` - (String) Link status. - `user_ip_address` - (String) User IP address. - - `vpc_crns` - (Set of String) Set of VPCs attached to this cloud connection. - - `vpc_enabled` - (Bool) Is VPC enabled for this cloud connection. - - `connection_mode` - (String) Type of service the gateway is attached to. + - `vpc_crns` - (Set) Set of VPCs attached to this cloud connection. + - `vpc_enabled` - (Boolean) Enable VPC for this cloud connection. From e3324074cb60c8f403d540a99e0f1bf076c7c8f6 Mon Sep 17 00:00:00 2001 From: Matthew Brandyberry Date: Tue, 30 Jan 2024 05:32:00 -0600 Subject: [PATCH 04/34] support empty lists for CBR rule contexts and zone addresses (#5058) * support empty lists for CBR rule contexts and zone addresses * update resource markdown --- .../resource_ibm_cbr_rule.go | 13 +++++++------ .../resource_ibm_cbr_zone.go | 10 +++++----- website/docs/d/cbr_rule.html.markdown | 2 +- website/docs/d/cbr_zone.html.markdown | 2 +- website/docs/r/cbr_rule.html.markdown | 2 +- website/docs/r/cbr_zone.html.markdown | 2 +- 6 files changed, 16 insertions(+), 15 deletions(-) diff --git a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule.go b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule.go index dfcbd65ddb..18c7154623 100644 --- a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule.go +++ b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule.go @@ -35,7 +35,7 @@ func ResourceIBMCbrRule() *schema.Resource { }, "contexts": &schema.Schema{ Type: schema.TypeList, - Required: true, + Optional: true, Description: "The contexts this rule applies to.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -122,6 +122,7 @@ func ResourceIBMCbrRule() *schema.Resource { Type: schema.TypeList, MaxItems: 1, Optional: true, + Computed: true, Description: "The operations this rule applies to.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -144,7 +145,7 @@ func ResourceIBMCbrRule() *schema.Resource { "enforcement_mode": &schema.Schema{ Type: schema.TypeString, Optional: true, - Default: "enabled", + Computed: true, ValidateFunc: validate.InvokeValidator("ibm_cbr_rule", "enforcement_mode"), Description: "The rule enforcement mode: * `enabled` - The restrictions are enforced and reported. This is the default. * `disabled` - The restrictions are disabled. Nothing is enforced or reported. * `report` - The restrictions are evaluated and reported, but not enforced.", }, @@ -252,8 +253,8 @@ func resourceIBMCbrRuleCreate(context context.Context, d *schema.ResourceData, m if _, ok := d.GetOk("description"); ok { createRuleOptions.SetDescription(d.Get("description").(string)) } + contexts := []contextbasedrestrictionsv1.RuleContext{} if _, ok := d.GetOk("contexts"); ok { - var contexts []contextbasedrestrictionsv1.RuleContext for _, e := range d.Get("contexts").([]interface{}) { value := e.(map[string]interface{}) contextsItem, err := resourceIBMCbrRuleMapToRuleContext(value) @@ -262,8 +263,8 @@ func resourceIBMCbrRuleCreate(context context.Context, d *schema.ResourceData, m } contexts = append(contexts, *contextsItem) } - createRuleOptions.SetContexts(contexts) } + createRuleOptions.SetContexts(contexts) if _, ok := d.GetOk("resources"); ok { var resources []contextbasedrestrictionsv1.Resource for _, e := range d.Get("resources").([]interface{}) { @@ -408,8 +409,8 @@ func resourceIBMCbrRuleUpdate(context context.Context, d *schema.ResourceData, m if _, ok := d.GetOk("description"); ok { replaceRuleOptions.SetDescription(d.Get("description").(string)) } + contexts := []contextbasedrestrictionsv1.RuleContext{} if _, ok := d.GetOk("contexts"); ok { - var contexts []contextbasedrestrictionsv1.RuleContext for _, e := range d.Get("contexts").([]interface{}) { value := e.(map[string]interface{}) contextsItem, err := resourceIBMCbrRuleMapToRuleContext(value) @@ -418,8 +419,8 @@ func resourceIBMCbrRuleUpdate(context context.Context, d *schema.ResourceData, m } contexts = append(contexts, *contextsItem) } - replaceRuleOptions.SetContexts(contexts) } + replaceRuleOptions.SetContexts(contexts) if _, ok := d.GetOk("resources"); ok { var resources []contextbasedrestrictionsv1.Resource for _, e := range d.Get("resources").([]interface{}) { diff --git a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone.go b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone.go index d525000caa..f8be760a0a 100644 --- a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone.go +++ b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone.go @@ -47,7 +47,7 @@ func ResourceIBMCbrZone() *schema.Resource { }, "addresses": &schema.Schema{ Type: schema.TypeList, - Required: true, + Optional: true, Description: "The list of addresses in the zone.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -249,8 +249,8 @@ func resourceIBMCbrZoneCreate(context context.Context, d *schema.ResourceData, m if _, ok := d.GetOk("description"); ok { createZoneOptions.SetDescription(d.Get("description").(string)) } + addresses := []contextbasedrestrictionsv1.AddressIntf{} if _, ok := d.GetOk("addresses"); ok { - var addresses []contextbasedrestrictionsv1.AddressIntf for _, e := range d.Get("addresses").([]interface{}) { value := e.(map[string]interface{}) addressesItem, err := resourceIBMCbrZoneMapToAddress(value) @@ -259,8 +259,8 @@ func resourceIBMCbrZoneCreate(context context.Context, d *schema.ResourceData, m } addresses = append(addresses, addressesItem) } - createZoneOptions.SetAddresses(addresses) } + createZoneOptions.SetAddresses(addresses) if _, ok := d.GetOk("excluded"); ok { var excluded []contextbasedrestrictionsv1.AddressIntf for _, e := range d.Get("excluded").([]interface{}) { @@ -401,8 +401,8 @@ func resourceIBMCbrZoneUpdate(context context.Context, d *schema.ResourceData, m if _, ok := d.GetOk("description"); ok { replaceZoneOptions.SetDescription(d.Get("description").(string)) } + addresses := []contextbasedrestrictionsv1.AddressIntf{} if _, ok := d.GetOk("addresses"); ok { - var addresses []contextbasedrestrictionsv1.AddressIntf for _, e := range d.Get("addresses").([]interface{}) { value := e.(map[string]interface{}) addressesItem, err := resourceIBMCbrZoneMapToAddress(value) @@ -411,8 +411,8 @@ func resourceIBMCbrZoneUpdate(context context.Context, d *schema.ResourceData, m } addresses = append(addresses, addressesItem) } - replaceZoneOptions.SetAddresses(addresses) } + replaceZoneOptions.SetAddresses(addresses) if _, ok := d.GetOk("excluded"); ok { var excluded []contextbasedrestrictionsv1.AddressIntf for _, e := range d.Get("excluded").([]interface{}) { diff --git a/website/docs/d/cbr_rule.html.markdown b/website/docs/d/cbr_rule.html.markdown index 07925ccca9..cf89cc6106 100644 --- a/website/docs/d/cbr_rule.html.markdown +++ b/website/docs/d/cbr_rule.html.markdown @@ -31,7 +31,7 @@ In addition to all argument references listed, you can access the following attr * `id` - The unique identifier of the cbr_rule. * `contexts` - (List) The contexts this rule applies to. - * Constraints: The maximum length is `1000` items. The minimum length is `1` item. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. Nested scheme for **contexts**: * `attributes` - (List) The attributes. * Constraints: The minimum length is `1` item. diff --git a/website/docs/d/cbr_zone.html.markdown b/website/docs/d/cbr_zone.html.markdown index e91a07c493..a0f495a59a 100644 --- a/website/docs/d/cbr_zone.html.markdown +++ b/website/docs/d/cbr_zone.html.markdown @@ -36,7 +36,7 @@ In addition to all argument references listed, you can access the following attr * `address_count` - (Integer) The number of addresses in the zone. * `addresses` - (List) The list of addresses in the zone. - * Constraints: The maximum length is `1000` items. The minimum length is `1` item. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. Nested scheme for **addresses**: * `ref` - (List) A service reference value. Nested scheme for **ref**: diff --git a/website/docs/r/cbr_rule.html.markdown b/website/docs/r/cbr_rule.html.markdown index 82399a036b..e08049b341 100644 --- a/website/docs/r/cbr_rule.html.markdown +++ b/website/docs/r/cbr_rule.html.markdown @@ -101,7 +101,7 @@ resource "ibm_cbr_rule" "cbr_rule" { Review the argument reference that you can specify for your resource. * `contexts` - (Optional, List) The contexts this rule applies to. - * Constraints: The maximum length is `1000` items. The minimum length is `1` item. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. Nested scheme for **contexts**: * `attributes` - (Required, List) The attributes. * Constraints: The minimum length is `1` item. diff --git a/website/docs/r/cbr_zone.html.markdown b/website/docs/r/cbr_zone.html.markdown index 71a9db498c..1fa3dc850f 100644 --- a/website/docs/r/cbr_zone.html.markdown +++ b/website/docs/r/cbr_zone.html.markdown @@ -47,7 +47,7 @@ Review the argument reference that you can specify for your resource. * `account_id` - (Optional, String) The id of the account owning this zone. * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\-]+$/`. * `addresses` - (Optional, List) The list of addresses in the zone. - * Constraints: The maximum length is `1000` items. The minimum length is `1` item. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. Nested scheme for **addresses**: * `ref` - (Optional, List) A service reference value. Nested scheme for **ref**: From abb4292599d9ff620f158d87b88eaa903bba725e Mon Sep 17 00:00:00 2001 From: Shaun Colley <80714407+swcolley@users.noreply.github.com> Date: Tue, 30 Jan 2024 06:55:48 -0500 Subject: [PATCH 05/34] fix(IAM Policy Management): Add operator support to subject_attributes in Authorziation Policy (#5076) * fix(IAM Policy Management): Add operator support to subject_attributes in Authorziation Policy Signed-off-by: Shaun Colley * fix(IAM Policy Management): re-formatted Signed-off-by: Shaun Colley * fix(IAM Policy Management): updated package and fixed test case Signed-off-by: Shaun Colley --------- Signed-off-by: Shaun Colley Co-authored-by: HARINI KANTAREDDY --- go.mod | 2 +- go.sum | 2 + ibm/flex/structures.go | 49 +++- ...rce_ibm_iam_authorization_policies_test.go | 4 +- .../resource_ibm_iam_access_group_policy.go | 8 +- .../resource_ibm_iam_authorization_policy.go | 249 ++++++++++++------ ...ource_ibm_iam_authorization_policy_test.go | 105 +++++++- .../r/iam_authorization_policy.html.markdown | 38 ++- 8 files changed, 354 insertions(+), 103 deletions(-) diff --git a/go.mod b/go.mod index 6d61f8d701..dcba6684a4 100644 --- a/go.mod +++ b/go.mod @@ -24,7 +24,7 @@ require ( github.com/IBM/ibm-hpcs-uko-sdk v0.0.20-beta github.com/IBM/keyprotect-go-client v0.12.2 github.com/IBM/networking-go-sdk v0.44.0 - github.com/IBM/platform-services-go-sdk v0.55.0 + github.com/IBM/platform-services-go-sdk v0.56.3 github.com/IBM/project-go-sdk v0.2.0 github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 github.com/IBM/scc-go-sdk/v5 v5.1.4 diff --git a/go.sum b/go.sum index a2527c8d95..6e087e9ce1 100644 --- a/go.sum +++ b/go.sum @@ -160,6 +160,8 @@ github.com/IBM/networking-go-sdk v0.44.0 h1:6acyMd6hwxcjK3bJ2suiUBTjzg8mRFAvYD76 github.com/IBM/networking-go-sdk v0.44.0/go.mod h1:XtqYRInR5NHmFUXhOL6RovpDdv6PnJfZ1lPFvssA8MA= github.com/IBM/platform-services-go-sdk v0.55.0 h1:W598xZanL61bwd8O2DQexr4qjIr+/tP0Y845zoms5yA= github.com/IBM/platform-services-go-sdk v0.55.0/go.mod h1:CWSprvsCsXWvujmBzbtoJSmbRZS9FVV3O594b0t/GiM= +github.com/IBM/platform-services-go-sdk v0.56.3 h1:DQ1VMQSknhPsdT7d+AybKiZT82esczAkHCIBkwYubzQ= +github.com/IBM/platform-services-go-sdk v0.56.3/go.mod h1:+U6Kg7o5u/Bh4ZkLxjymSgfdpVsaWAtsMtzhwclUry0= github.com/IBM/project-go-sdk v0.2.0 h1:DMv0HQfS3GQHkkagZ4E2vt1H1paN5Gh357K9izeaGj8= github.com/IBM/project-go-sdk v0.2.0/go.mod h1:lqe0M4cKvABI1iHR1b+KfasVcxQL6nl2VJ8eOyQs8Ig= github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 h1:NPUhkoOCRuv3OFWt19PmwjXGGTKlvmbuPg9fUrBUNe4= diff --git a/ibm/flex/structures.go b/ibm/flex/structures.go index 3429894e39..a2feb7bb9b 100644 --- a/ibm/flex/structures.go +++ b/ibm/flex/structures.go @@ -1639,7 +1639,11 @@ func FlattenV2PolicyResource(resource iampolicymanagementv1.V2PolicyResource) [] if len(customAttributes) > 0 { out := make(map[string]string) for _, a := range customAttributes { - out[*a.Key] = fmt.Sprint(a.Value) + if *a.Operator == "stringExists" && a.Value == true { + out[*a.Key] = fmt.Sprint("*") + } else if *a.Operator == "stringMatch" || *a.Operator == "stringEquals" { + out[*a.Key] = fmt.Sprint(a.Value) + } } l["attributes"] = out } @@ -3345,10 +3349,12 @@ func GetResourceAttribute(name string, r iampolicymanagementv1.PolicyResource) * func GetV2PolicyResourceAttribute(key string, r iampolicymanagementv1.V2PolicyResource) string { for _, a := range r.Attributes { - if *a.Key == key && - (*a.Operator == "stringMatch" || - *a.Operator == "stringEquals") { - return a.Value.(string) + if *a.Key == key { + if *a.Operator == "stringExists" && a.Value == true { + return fmt.Sprint("*") + } else if *a.Operator == "stringMatch" || *a.Operator == "stringEquals" { + return a.Value.(string) + } } } return *core.StringPtr("") @@ -3363,7 +3369,7 @@ func GetSubjectAttribute(name string, s iampolicymanagementv1.PolicySubject) *st return core.StringPtr("") } -func GetV2PolicySubjectAttribute(key string, s iampolicymanagementv1.V2PolicySubject) *string { +func GetV2PolicySubjectAttribute(key string, s iampolicymanagementv1.V2PolicySubject) interface{} { for _, a := range s.Attributes { if *a.Key == key && (*a.Operator == "stringMatch" || @@ -3371,7 +3377,7 @@ func GetV2PolicySubjectAttribute(key string, s iampolicymanagementv1.V2PolicySub return a.Value } } - return core.StringPtr("") + return interface{}(core.StringPtr("")) } func SetResourceAttribute(name *string, value *string, r []iampolicymanagementv1.ResourceAttribute) []iampolicymanagementv1.ResourceAttribute { @@ -3512,6 +3518,7 @@ func GetRoleNamesFromPolicyResponse(policy iampolicymanagementv1.V2PolicyTemplat controlResponse := policy.Control.(*iampolicymanagementv1.ControlResponse) policyRoles := MapRolesToPolicyRoles(controlResponse.Grant.Roles) resourceAttributes := policy.Resource.Attributes + subjectAttributes := policy.Subject.Attributes userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() if err != nil { @@ -3519,11 +3526,20 @@ func GetRoleNamesFromPolicyResponse(policy iampolicymanagementv1.V2PolicyTemplat } var ( - serviceName string - resourceType string - serviceGroupID string + serviceName string + sourceServiceName string + resourceType string + serviceGroupID string ) + for _, a := range subjectAttributes { + if *a.Key == "serviceName" && + (*a.Operator == "stringMatch" || + *a.Operator == "stringEquals") { + sourceServiceName = a.Value.(string) + } + } + for _, a := range resourceAttributes { if *a.Key == "serviceName" && (*a.Operator == "stringMatch" || @@ -3550,6 +3566,11 @@ func GetRoleNamesFromPolicyResponse(policy iampolicymanagementv1.V2PolicyTemplat if accountManagement, ok := d.GetOk("account_management"); ok { isAccountManagementPolicy = accountManagement.(bool) } + + if serviceName == "" && resourceType == "resource-group" { + serviceName = "resource-controller" + } + if serviceName == "" && // no specific service specified !isAccountManagementPolicy && // not all account management services resourceType != "resource-group" && // not to a resource group @@ -3565,6 +3586,14 @@ func GetRoleNamesFromPolicyResponse(policy iampolicymanagementv1.V2PolicyTemplat listRoleOptions.ServiceGroupID = &serviceGroupID } + if sourceServiceName != "" { + listRoleOptions.SourceServiceName = &sourceServiceName + } + + if *policy.Type != "" { + listRoleOptions.PolicyType = policy.Type + } + roleList, _, err := iamPolicyManagementClient.ListRoles(listRoleOptions) if err != nil { diff --git a/ibm/service/iampolicy/data_source_ibm_iam_authorization_policies_test.go b/ibm/service/iampolicy/data_source_ibm_iam_authorization_policies_test.go index 213b185ac1..b33893b921 100644 --- a/ibm/service/iampolicy/data_source_ibm_iam_authorization_policies_test.go +++ b/ibm/service/iampolicy/data_source_ibm_iam_authorization_policies_test.go @@ -73,8 +73,8 @@ func testAccCheckIBMIAMAuthorizationPoliciesDataSourceMultiplePolicies() string resource "ibm_iam_authorization_policy" "policy1" { source_service_name = "is" source_resource_type = "load-balancer" - target_service_name = "cloudcerts" - roles = ["Reader"] + target_service_name = "secrets-manager" + roles = ["SecretsReader"] } ` } diff --git a/ibm/service/iampolicy/resource_ibm_iam_access_group_policy.go b/ibm/service/iampolicy/resource_ibm_iam_access_group_policy.go index 5bfcaf2be9..5dda95b0ab 100644 --- a/ibm/service/iampolicy/resource_ibm_iam_access_group_policy.go +++ b/ibm/service/iampolicy/resource_ibm_iam_access_group_policy.go @@ -481,9 +481,9 @@ func resourceIBMIAMAccessGroupPolicyRead(d *schema.ResourceData, meta interface{ return fmt.Errorf("[ERROR] Error retrieving access group policy: %s\n%s", err, res) } - retrievedAttribute := flex.GetV2PolicySubjectAttribute("access_group_id", *accessGroupPolicy.Subject) - if accessGroupId != *retrievedAttribute { - return fmt.Errorf("[ERROR] Policy %s does not belong to access group %s, retrievedAttr: %s", accessGroupPolicyId, accessGroupId, *retrievedAttribute) + retrievedAttribute := flex.GetV2PolicySubjectAttribute("access_group_id", *accessGroupPolicy.Subject).(string) + if accessGroupId != retrievedAttribute { + return fmt.Errorf("[ERROR] Policy %s does not belong to access group %s, retrievedAttr: %s", accessGroupPolicyId, accessGroupId, retrievedAttribute) } d.Set("access_group_id", accessGroupId) @@ -770,7 +770,7 @@ func resourceIBMIAMAccessGroupPolicyExists(d *schema.ResourceData, meta interfac return false, nil } - tempID := fmt.Sprintf("%s/%s", *flex.GetV2PolicySubjectAttribute("access_group_id", *accessGroupPolicy.Subject), *accessGroupPolicy.ID) + tempID := fmt.Sprintf("%s/%s", flex.GetV2PolicySubjectAttribute("access_group_id", *accessGroupPolicy.Subject), *accessGroupPolicy.ID) return tempID == d.Id(), nil } diff --git a/ibm/service/iampolicy/resource_ibm_iam_authorization_policy.go b/ibm/service/iampolicy/resource_ibm_iam_authorization_policy.go index c1facb1f30..a242a001d5 100644 --- a/ibm/service/iampolicy/resource_ibm_iam_authorization_policy.go +++ b/ibm/service/iampolicy/resource_ibm_iam_authorization_policy.go @@ -139,6 +139,11 @@ func ResourceIBMIAMAuthorizationPolicy() *schema.Resource { Required: true, Description: "Value of attribute.", }, + "operator": { + Type: schema.TypeString, + Optional: true, + Description: "Operator of attribute.", + }, }, }, }, @@ -219,8 +224,8 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf var sourceServiceName, targetServiceName string policyType := "authorization" - policySubject := &iampolicymanagementv1.PolicySubject{} - policyResource := &iampolicymanagementv1.PolicyResource{} + policySubject := &iampolicymanagementv1.V2PolicySubject{} + policyResource := &iampolicymanagementv1.V2PolicyResource{} userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() if err != nil { @@ -238,23 +243,54 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf a := attribute.(map[string]interface{}) name := a["name"].(string) value := a["value"].(string) + operator := a["operator"].(string) if name == "serviceName" { sourceServiceName = value } - at := iampolicymanagementv1.SubjectAttribute{ - Name: &name, - Value: &value, + + if operator == "" && value == "*" && name == "resourceGroupId" { + at := iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: &name, + Value: true, + Operator: core.StringPtr("stringExists"), + } + policySubject.Attributes = append(policySubject.Attributes, at) + } else if operator == "stringExists" { + var resourceValue bool + if value == "true" { + resourceValue = true + } else if value == "false" { + resourceValue = false + } else { + return fmt.Errorf("[ERROR] Only values \"true\" and \"false\" are allowed when operator is \"stringExists\". Received %s.", value) + } + at := iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: &name, + Value: &resourceValue, + Operator: &operator, + } + policySubject.Attributes = append(policySubject.Attributes, at) + } else { + if operator == "" { + operator = "stringEquals" + } + at := iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: &name, + Value: &value, + Operator: &operator, + } + policySubject.Attributes = append(policySubject.Attributes, at) } - policySubject.Attributes = append(policySubject.Attributes, at) } } else { if name, ok := d.GetOk("source_service_name"); ok { sourceServiceName = name.(string) - serviceNameSubjectAttribute := &iampolicymanagementv1.SubjectAttribute{ - Name: core.StringPtr("serviceName"), - Value: &sourceServiceName, + serviceNameSubjectAttribute := &iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: core.StringPtr("serviceName"), + Value: &sourceServiceName, + Operator: core.StringPtr("stringEquals"), } policySubject.Attributes = append(policySubject.Attributes, *serviceNameSubjectAttribute) } @@ -264,35 +300,48 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf sourceServiceAccount = account.(string) } - accountIdSubjectAttribute := &iampolicymanagementv1.SubjectAttribute{ - Name: core.StringPtr("accountId"), - Value: &sourceServiceAccount, + accountIdSubjectAttribute := &iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: core.StringPtr("accountId"), + Value: &sourceServiceAccount, + Operator: core.StringPtr("stringEquals"), } policySubject.Attributes = append(policySubject.Attributes, *accountIdSubjectAttribute) if sID, ok := d.GetOk("source_resource_instance_id"); ok { - serviceInstanceSubjectAttribute := iampolicymanagementv1.SubjectAttribute{ - Name: core.StringPtr("serviceInstance"), - Value: core.StringPtr(sID.(string)), + serviceInstanceSubjectAttribute := iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: core.StringPtr("serviceInstance"), + Value: core.StringPtr(sID.(string)), + Operator: core.StringPtr("stringEquals"), } policySubject.Attributes = append(policySubject.Attributes, serviceInstanceSubjectAttribute) } if sType, ok := d.GetOk("source_resource_type"); ok { - resourceTypeSubjectAttribute := iampolicymanagementv1.SubjectAttribute{ - Name: core.StringPtr("resourceType"), - Value: core.StringPtr(sType.(string)), + resourceTypeSubjectAttribute := iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: core.StringPtr("resourceType"), + Value: core.StringPtr(sType.(string)), + Operator: core.StringPtr("stringEquals"), } policySubject.Attributes = append(policySubject.Attributes, resourceTypeSubjectAttribute) } if sResGrpID, ok := d.GetOk("source_resource_group_id"); ok { - resourceGroupSubjectAttribute := iampolicymanagementv1.SubjectAttribute{ - Name: core.StringPtr("resourceGroupId"), - Value: core.StringPtr(sResGrpID.(string)), + if sResGrpID == "*" { + resourceGroupSubjectAttribute := iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: core.StringPtr("resourceGroupId"), + Value: true, + Operator: core.StringPtr("stringExists"), + } + policySubject.Attributes = append(policySubject.Attributes, resourceGroupSubjectAttribute) + } else { + resourceGroupSubjectAttribute := iampolicymanagementv1.V2PolicySubjectAttribute{ + Key: core.StringPtr("resourceGroupId"), + Value: core.StringPtr(sResGrpID.(string)), + Operator: core.StringPtr("stringEquals"), + } + policySubject.Attributes = append(policySubject.Attributes, resourceGroupSubjectAttribute) } - policySubject.Attributes = append(policySubject.Attributes, resourceGroupSubjectAttribute) } } @@ -309,26 +358,41 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf if name == "resourceType" && targetServiceName == "" { targetServiceName = "resource-controller" } - at := iampolicymanagementv1.ResourceAttribute{ - Name: &name, - Value: &value, - Operator: &operator, + if operator == "stringExists" { + var resourceValue bool + if value == "true" { + resourceValue = true + } else { + resourceValue = false + } + at := iampolicymanagementv1.V2PolicyResourceAttribute{ + Key: &name, + Value: &resourceValue, + Operator: &operator, + } + policyResource.Attributes = append(policyResource.Attributes, at) + } else { + at := iampolicymanagementv1.V2PolicyResourceAttribute{ + Key: &name, + Value: &value, + Operator: &operator, + } + policyResource.Attributes = append(policyResource.Attributes, at) } - policyResource.Attributes = append(policyResource.Attributes, at) } } else { if name, ok := d.GetOk("target_service_name"); ok { targetServiceName = name.(string) - serviceNameResourceAttribute := &iampolicymanagementv1.ResourceAttribute{ - Name: core.StringPtr("serviceName"), + serviceNameResourceAttribute := &iampolicymanagementv1.V2PolicyResourceAttribute{ + Key: core.StringPtr("serviceName"), Value: core.StringPtr(targetServiceName), Operator: core.StringPtr("stringEquals"), } policyResource.Attributes = append(policyResource.Attributes, *serviceNameResourceAttribute) } - accountIDResourceAttribute := &iampolicymanagementv1.ResourceAttribute{ - Name: core.StringPtr("accountId"), + accountIDResourceAttribute := &iampolicymanagementv1.V2PolicyResourceAttribute{ + Key: core.StringPtr("accountId"), Value: core.StringPtr(userDetails.UserAccount), Operator: core.StringPtr("stringEquals"), } @@ -336,17 +400,19 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf policyResource.Attributes = append(policyResource.Attributes, *accountIDResourceAttribute) if tID, ok := d.GetOk("target_resource_instance_id"); ok { - serviceInstanceResourceAttribute := iampolicymanagementv1.ResourceAttribute{ - Name: core.StringPtr("serviceInstance"), - Value: core.StringPtr(tID.(string)), + serviceInstanceResourceAttribute := iampolicymanagementv1.V2PolicyResourceAttribute{ + Key: core.StringPtr("serviceInstance"), + Value: core.StringPtr(tID.(string)), + Operator: core.StringPtr("stringEquals"), } policyResource.Attributes = append(policyResource.Attributes, serviceInstanceResourceAttribute) } if tType, ok := d.GetOk("target_resource_type"); ok { - resourceTypeResourceAttribute := iampolicymanagementv1.ResourceAttribute{ - Name: core.StringPtr("resourceType"), - Value: core.StringPtr(tType.(string)), + resourceTypeResourceAttribute := iampolicymanagementv1.V2PolicyResourceAttribute{ + Key: core.StringPtr("resourceType"), + Value: core.StringPtr(tType.(string)), + Operator: core.StringPtr("stringEquals"), } policyResource.Attributes = append(policyResource.Attributes, resourceTypeResourceAttribute) if targetServiceName == "" { @@ -355,9 +421,10 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf } if tResGrpID, ok := d.GetOk("target_resource_group_id"); ok { - resourceGroupResourceAttribute := iampolicymanagementv1.ResourceAttribute{ - Name: core.StringPtr("resourceGroupId"), - Value: core.StringPtr(tResGrpID.(string)), + resourceGroupResourceAttribute := iampolicymanagementv1.V2PolicyResourceAttribute{ + Key: core.StringPtr("resourceGroupId"), + Value: core.StringPtr(tResGrpID.(string)), + Operator: core.StringPtr("stringEquals"), } policyResource.Attributes = append(policyResource.Attributes, resourceGroupResourceAttribute) } @@ -381,13 +448,21 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf return err } - createPolicyOptions := iampapClient.NewCreatePolicyOptions( + policyGrant := &iampolicymanagementv1.Grant{ + Roles: flex.MapPolicyRolesToRoles(roles), + } + policyControl := &iampolicymanagementv1.Control{ + Grant: policyGrant, + } + + createPolicyOptions := iampapClient.NewCreateV2PolicyOptions( + policyControl, "authorization", - []iampolicymanagementv1.PolicySubject{*policySubject}, - roles, - []iampolicymanagementv1.PolicyResource{*policyResource}, ) + createPolicyOptions.SetSubject(policySubject) + createPolicyOptions.SetResource(policyResource) + if description, ok := d.GetOk("description"); ok { des := description.(string) createPolicyOptions.Description = &des @@ -397,7 +472,7 @@ func resourceIBMIAMAuthorizationPolicyCreate(d *schema.ResourceData, meta interf createPolicyOptions.SetHeaders(map[string]string{"Transaction-Id": transactionID.(string)}) } - authPolicy, resp, err := iampapClient.CreatePolicy(createPolicyOptions) + authPolicy, resp, err := iampapClient.CreateV2Policy(createPolicyOptions) if err != nil { return fmt.Errorf("[ERROR] Error creating authorization policy: %s %s", err, resp) } @@ -414,19 +489,19 @@ func resourceIBMIAMAuthorizationPolicyRead(d *schema.ResourceData, meta interfac return err } - getPolicyOptions := &iampolicymanagementv1.GetPolicyOptions{ - PolicyID: core.StringPtr(d.Id()), + getPolicyOptions := &iampolicymanagementv1.GetV2PolicyOptions{ + ID: core.StringPtr(d.Id()), } if transactionID, ok := d.GetOk("transaction_id"); ok { getPolicyOptions.SetHeaders(map[string]string{"Transaction-Id": transactionID.(string)}) } - authorizationPolicy, resp, err := iampapClient.GetPolicy(getPolicyOptions) + authorizationPolicy, resp, err := iampapClient.GetV2Policy(getPolicyOptions) err = resource.Retry(5*time.Minute, func() *resource.RetryError { var err error - authorizationPolicy, resp, err = iampapClient.GetPolicy(getPolicyOptions) + authorizationPolicy, resp, err = iampapClient.GetV2Policy(getPolicyOptions) if err != nil || authorizationPolicy == nil { if resp != nil && resp.StatusCode == 404 { return resource.RetryableError(err) @@ -437,15 +512,12 @@ func resourceIBMIAMAuthorizationPolicyRead(d *schema.ResourceData, meta interfac }) if conns.IsResourceTimeoutError(err) { - authorizationPolicy, resp, err = iampapClient.GetPolicy(getPolicyOptions) + authorizationPolicy, resp, err = iampapClient.GetV2Policy(getPolicyOptions) } if err != nil || resp == nil { return fmt.Errorf("[ERROR] Error retrieving authorizationPolicy: %s %s", err, resp) } - roles := make([]string, len(authorizationPolicy.Roles)) - for i, role := range authorizationPolicy.Roles { - roles[i] = *role.DisplayName - } + roles, err := flex.GetRoleNamesFromPolicyResponse(*authorizationPolicy, d, meta) if authorizationPolicy.Description != nil { d.Set("description", *authorizationPolicy.Description) } @@ -453,21 +525,22 @@ func resourceIBMIAMAuthorizationPolicyRead(d *schema.ResourceData, meta interfac d.Set("transaction_id", resp.Headers["Transaction-Id"][0]) } d.Set("roles", roles) - source := authorizationPolicy.Subjects[0] - target := authorizationPolicy.Resources[0] - - d.Set("resource_attributes", setAuthorizationResourceAttributes(target)) - d.Set("target_resource_instance_id", flex.GetResourceAttribute("serviceInstance", target)) - d.Set("target_resource_type", flex.GetResourceAttribute("resourceType", target)) - d.Set("target_resource_group_id", flex.GetResourceAttribute("resourceGroupId", target)) - d.Set("target_service_name", flex.GetResourceAttribute("serviceName", target)) - - d.Set("subject_attributes", setAuthorizationSubjectAttributes(source)) - d.Set("source_service_name", flex.GetSubjectAttribute("serviceName", source)) - d.Set("source_resource_instance_id", flex.GetSubjectAttribute("serviceInstance", source)) - d.Set("source_resource_type", flex.GetSubjectAttribute("resourceType", source)) - d.Set("source_service_account", flex.GetSubjectAttribute("accountId", source)) - d.Set("source_resource_group_id", flex.GetSubjectAttribute("resourceGroupId", source)) + source := authorizationPolicy.Subject + target := authorizationPolicy.Resource + + d.Set("resource_attributes", setAuthorizationResourceAttributes(*target)) + d.Set("target_resource_instance_id", flex.GetV2PolicyResourceAttribute("serviceInstance", *target)) + d.Set("target_resource_type", flex.GetV2PolicyResourceAttribute("resourceType", *target)) + d.Set("target_resource_group_id", flex.GetV2PolicyResourceAttribute("resourceGroupId", *target)) + d.Set("target_service_name", flex.GetV2PolicyResourceAttribute("serviceName", *target)) + if a, ok := d.GetOk("subject_attributes"); ok { + d.Set("subject_attributes", setAuthorizationSubjectAttributes(*source, a.(*schema.Set))) + } + d.Set("source_service_name", flex.GetV2PolicySubjectAttribute("serviceName", *source)) + d.Set("source_resource_instance_id", flex.GetV2PolicySubjectAttribute("serviceInstance", *source)) + d.Set("source_resource_type", flex.GetV2PolicySubjectAttribute("resourceType", *source)) + d.Set("source_service_account", flex.GetV2PolicySubjectAttribute("accountId", *source)) + d.Set("source_resource_group_id", flex.GetV2PolicySubjectAttribute("resourceGroupId", *source)) return nil } @@ -528,12 +601,12 @@ func resourceIBMIAMAuthorizationPolicyExists(d *schema.ResourceData, meta interf return *authorizationPolicy.ID == d.Id(), nil } -func setAuthorizationResourceAttributes(list iampolicymanagementv1.PolicyResource) []map[string]interface{} { +func setAuthorizationResourceAttributes(list iampolicymanagementv1.V2PolicyResource) []map[string]interface{} { result := make([]map[string]interface{}, 0) for _, attribute := range list.Attributes { l := map[string]interface{}{ - "name": attribute.Name, - "value": attribute.Value, + "name": attribute.Key, + "value": fmt.Sprintf("%v", attribute.Value), "operator": attribute.Operator, } result = append(result, l) @@ -541,12 +614,34 @@ func setAuthorizationResourceAttributes(list iampolicymanagementv1.PolicyResourc return result } -func setAuthorizationSubjectAttributes(list iampolicymanagementv1.PolicySubject) []map[string]interface{} { +func setAuthorizationSubjectAttributes(list iampolicymanagementv1.V2PolicySubject, a *schema.Set) []map[string]interface{} { + previousOperators := make([]string, 0) + + for _, item := range a.List() { + i := item.(map[string]interface{}) + + previousOperators = append(previousOperators, i["operator"].(string)) + } + result := make([]map[string]interface{}, 0) - for _, attribute := range list.Attributes { - l := map[string]interface{}{ - "name": attribute.Name, - "value": attribute.Value, + for i, attribute := range list.Attributes { + var l map[string]interface{} + if previousOperators[i] == "" && attribute.Value == true && *attribute.Operator == "stringExists" { + l = map[string]interface{}{ + "name": attribute.Key, + "value": "*", + } + } else if previousOperators[i] == "" { + l = map[string]interface{}{ + "name": attribute.Key, + "value": fmt.Sprintf("%v", attribute.Value), + } + } else { + l = map[string]interface{}{ + "name": attribute.Key, + "value": fmt.Sprintf("%v", attribute.Value), + "operator": attribute.Operator, + } } result = append(result, l) } diff --git a/ibm/service/iampolicy/resource_ibm_iam_authorization_policy_test.go b/ibm/service/iampolicy/resource_ibm_iam_authorization_policy_test.go index fe5b7436ca..d6a62efaa7 100644 --- a/ibm/service/iampolicy/resource_ibm_iam_authorization_policy_test.go +++ b/ibm/service/iampolicy/resource_ibm_iam_authorization_policy_test.go @@ -107,7 +107,7 @@ func TestAccIBMIAMAuthorizationPolicy_ResourceType(t *testing.T) { testAccCheckIBMIAMAuthorizationPolicyExists("ibm_iam_authorization_policy.policy", conf), resource.TestCheckResourceAttr("ibm_iam_authorization_policy.policy", "source_service_name", "is"), resource.TestCheckResourceAttr("ibm_iam_authorization_policy.policy", "source_resource_type", "load-balancer"), - resource.TestCheckResourceAttr("ibm_iam_authorization_policy.policy", "target_service_name", "hs-crypto"), + resource.TestCheckResourceAttr("ibm_iam_authorization_policy.policy", "target_service_name", "secrets-manager"), ), }, }, @@ -202,6 +202,27 @@ func TestAccIBMIAMAuthorizationPolicy_SourceResourceGroupId_ResourceAttributes(t }) } +func TestAccIBMIAMAuthorizationPolicy_SourceResourceGroupId_ResourceAttributes_WildCard(t *testing.T) { + var conf iampolicymanagementv1.PolicyTemplateMetaData + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMIAMAuthorizationPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMIAMAuthorizationPolicySourceResourceGroupIdResourceAttributesWildCard(acc.Tg_cross_network_account_id, acc.Tg_cross_network_account_id), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMIAMAuthorizationPolicyExists("ibm_iam_authorization_policy.policy", conf), + resource.TestCheckResourceAttrSet("ibm_iam_authorization_policy.policy", "id"), + resource.TestCheckResourceAttr("ibm_iam_authorization_policy.policy", "source_service_name", ""), + resource.TestCheckResourceAttr("ibm_iam_authorization_policy.policy", "target_service_name", "cloud-object-storage"), + ), + }, + }, + }) +} + func TestAccIBMIAMAuthorizationPolicy_TargetResourceType(t *testing.T) { var conf iampolicymanagementv1.PolicyTemplateMetaData @@ -265,6 +286,25 @@ func TestAccIBMIAMAuthorizationPolicy_With_Transaction_id(t *testing.T) { }) } +func TestAccIBMIAMAuthorizationPolicy_SourceResourceGroupIdWithStringExistsInSubjectAttributes(t *testing.T) { + var conf iampolicymanagementv1.PolicyTemplateMetaData + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMIAMAuthorizationPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMIAMAuthorizationPolicySourceResourceGroupIdWithStringExistsInSubjectAttributes(acc.Tg_cross_network_account_id, acc.Tg_cross_network_account_id), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMIAMAuthorizationPolicyExists("ibm_iam_authorization_policy.policy", conf), + resource.TestCheckResourceAttrSet("ibm_iam_authorization_policy.policy", "id"), + ), + }, + }, + }) +} + func testAccCheckIBMIAMAuthorizationPolicyDestroy(s *terraform.State) error { iamPolicyManagementClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).IAMPolicyManagementV1API() if err != nil { @@ -350,9 +390,9 @@ func testAccCheckIBMIAMAuthorizationPolicyResourceInstance(instanceName string) resource "ibm_iam_authorization_policy" "policy" { source_service_name = "cloud-object-storage" - source_resource_instance_id = ibm_resource_instance.instance1.id + source_resource_instance_id = ibm_resource_instance.instance1.guid target_service_name = "kms" - target_resource_instance_id = ibm_resource_instance.instance2.id + target_resource_instance_id = ibm_resource_instance.instance2.guid roles = ["Reader"] } @@ -364,8 +404,8 @@ func testAccCheckIBMIAMAuthorizationPolicyResourceType() string { resource "ibm_iam_authorization_policy" "policy" { source_service_name = "is" source_resource_type = "load-balancer" - target_service_name = "hs-crypto" - roles = ["Reader"] + target_service_name = "secrets-manager" + roles = ["SecretsReader"] } ` } @@ -426,7 +466,7 @@ func testAccCheckIBMIAMAuthorizationPolicyResourceAttributes(sServiceInstance, t } subject_attributes { name = "serviceInstance" - value = ibm_resource_instance.cos.id + value = ibm_resource_instance.cos.guid } subject_attributes { name = "serviceName" @@ -442,7 +482,7 @@ func testAccCheckIBMIAMAuthorizationPolicyResourceAttributes(sServiceInstance, t } resource_attributes { name = "serviceInstance" - value = ibm_resource_instance.kms.id + value = ibm_resource_instance.kms.guid } } `, sServiceInstance, tServiceInstance, sAccountID, tAccountID) @@ -497,6 +537,31 @@ func testAccCheckIBMIAMAuthorizationPolicySourceResourceGroupIdResourceAttribute `, sAccountID, tAccountID) } +func testAccCheckIBMIAMAuthorizationPolicySourceResourceGroupIdResourceAttributesWildCard(sAccountID, tAccountID string) string { + return fmt.Sprintf(` + resource "ibm_iam_authorization_policy" "policy" { + roles = ["Reader"] + subject_attributes { + name = "accountId" + value = "%s" + } + subject_attributes { + name = "resourceGroupId" + value = "*" + } + + resource_attributes { + name = "serviceName" + value = "cloud-object-storage" + } + resource_attributes { + name = "accountId" + value = "%s" + } + } + `, sAccountID, tAccountID) +} + func testAccCheckIBMIAMAuthorizationPolicyTargetResourceType() string { return ` resource "ibm_iam_authorization_policy" "policy" { @@ -534,3 +599,29 @@ func testAccCheckIBMIAMAuthorizationPolicyResourceTypeAndResourceAttributes(sAcc } `, sAccountID, tAccountID) } + +func testAccCheckIBMIAMAuthorizationPolicySourceResourceGroupIdWithStringExistsInSubjectAttributes(sAccountID, tAccountID string) string { + return fmt.Sprintf(` + resource "ibm_iam_authorization_policy" "policy" { + roles = ["Reader"] + subject_attributes { + name = "accountId" + value = "%s" + } + subject_attributes { + name = "resourceGroupId" + operator = "stringExists" + value = "true" + } + + resource_attributes { + name = "serviceName" + value = "cloud-object-storage" + } + resource_attributes { + name = "accountId" + value = "%s" + } + } + `, sAccountID, tAccountID) +} diff --git a/website/docs/r/iam_authorization_policy.html.markdown b/website/docs/r/iam_authorization_policy.html.markdown index 2758bb8b9d..bac30292cc 100644 --- a/website/docs/r/iam_authorization_policy.html.markdown +++ b/website/docs/r/iam_authorization_policy.html.markdown @@ -66,9 +66,9 @@ resource "ibm_resource_instance" "instance2" { resource "ibm_iam_authorization_policy" "policy" { source_service_name = "cloud-object-storage" - source_resource_instance_id = ibm_resource_instance.instance1.id + source_resource_instance_id = ibm_resource_instance.instance1.guid target_service_name = "kms" - target_resource_instance_id = ibm_resource_instance.instance2.id + target_resource_instance_id = ibm_resource_instance.instance2.guid roles = ["Reader"] } @@ -156,6 +156,40 @@ resource "ibm_iam_authorization_policy" "policy" { } ``` +### Authorization policy between all resource groups in an account and a target service using resource attributes + +```terraform + +resource "ibm_resource_group" "source_resource_group" { + name = "123123" +} + +resource "ibm_iam_authorization_policy" "policy" { + roles = [ + "Reader", + ] + + resource_attributes { + name = "accountId" + operator = "stringEquals" + value = "12345" + } + resource_attributes { + name = "serviceName" + operator = "stringEquals" + value = "cloud-object-storage" + } + + subject_attributes { + name = "accountId" + value = "12345" + } + subject_attributes { + name = "resourceGroupId" + value = "*" + } +} +``` ### Authorization policy between source service and target resource type "resource-group" using resource attributes From 35e4ed8c138458fa0bc5670edb4626bad6cbdc21 Mon Sep 17 00:00:00 2001 From: Deepak Selvakumar <77007253+deepaksibm@users.noreply.github.com> Date: Tue, 30 Jan 2024 17:27:00 +0530 Subject: [PATCH 06/34] fix(routing-table-route) - fix routing table route advertise patch and action (#5069) * fix(routing-table-route) - fix routing table route advertise patch * added action --- ...ta_source_ibm_is_vpc_routing_table_routes.go | 3 +++ .../resource_ibm_is_vpc_routing_table_route.go | 17 ++++------------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go index 205d002bdc..6e723e5db6 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go +++ b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go @@ -221,6 +221,9 @@ func dataSourceIBMISVPCRoutingTableRoutesList(d *schema.ResourceData, meta inter if instance.LifecycleState != nil { route[isRoutingTableRouteLifecycleState] = *instance.LifecycleState } + if instance.Action != nil { + route[isRoutingTableRouteAction] = *instance.Action + } if instance.Advertise != nil { route["advertise"] = *instance.Advertise } diff --git a/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go b/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go index 2862c247f6..dd5c23d053 100644 --- a/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go +++ b/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go @@ -343,20 +343,11 @@ func resourceIBMISVPCRoutingTableRouteUpdate(d *schema.ResourceData, meta interf // Construct an instance of the RoutePatch model routePatchModel := new(vpcv1.RoutePatch) - if d.HasChange(rName) || d.HasChange("advertise") { - // Construct an instance of the RoutePatch model - routePatchModel := new(vpcv1.RoutePatch) - if d.HasChange(rName) { - name := d.Get(rName).(string) - routePatchModel.Name = &name - hasChange = true - } + if d.HasChange("advertise") { + advertiseVal := d.Get("advertise").(bool) + routePatchModel.Advertise = &advertiseVal + hasChange = true - if d.HasChange("advertise") { - advertiseVal := d.Get("advertise").(bool) - routePatchModel.Advertise = &advertiseVal - hasChange = true - } } if d.HasChange(rName) { name := d.Get(rName).(string) From c1168819ac20a1c05eb602a709fe10a75d8c9e90 Mon Sep 17 00:00:00 2001 From: Matthew Brandyberry Date: Thu, 18 Jan 2024 10:47:03 -0600 Subject: [PATCH 07/34] encode test ids as constants for easy replacement --- .../data_source_ibm_cbr_rule_test.go | 17 +++++++++++------ .../data_source_ibm_cbr_zone_test.go | 6 +++--- .../resource_ibm_cbr_rule_test.go | 12 ++++++------ .../resource_ibm_cbr_zone_test.go | 8 ++++---- 4 files changed, 24 insertions(+), 19 deletions(-) diff --git a/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_rule_test.go b/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_rule_test.go index b2fa07dd41..f8c6982b37 100644 --- a/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_rule_test.go +++ b/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_rule_test.go @@ -13,6 +13,11 @@ import ( acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" ) +const ( + testAccountID = "12ab34cd56ef78ab90cd12ef34ab56cd" + testZoneID = "559052eb8f43302824e7ae490c0281eb" +) + func TestAccIBMCbrRuleDataSourceBasic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, @@ -77,13 +82,13 @@ func testAccCheckIBMCbrRuleDataSourceConfigBasic() string { contexts { attributes { name = "networkZoneId" - value = "559052eb8f43302824e7ae490c0281eb" + value = "%s" } } resources { attributes { name = "accountId" - value = "12ab34cd56ef78ab90cd12ef34ab56cd" + value = "%s" } attributes { name = "serviceName" @@ -94,7 +99,7 @@ func testAccCheckIBMCbrRuleDataSourceConfigBasic() string { data "ibm_cbr_rule" "cbr_rule" { rule_id = ibm_cbr_rule.cbr_rule.id } - `) + `, testZoneID, testAccountID) } func testAccCheckIBMCbrRuleDataSourceConfig(ruleDescription string, ruleEnforcementMode string) string { @@ -104,13 +109,13 @@ func testAccCheckIBMCbrRuleDataSourceConfig(ruleDescription string, ruleEnforcem contexts { attributes { name = "networkZoneId" - value = "559052eb8f43302824e7ae490c0281eb" + value = "%s" } } resources { attributes { name = "accountId" - value = "12ab34cd56ef78ab90cd12ef34ab56cd" + value = "%s" } attributes { name = "serviceName" @@ -133,5 +138,5 @@ func testAccCheckIBMCbrRuleDataSourceConfig(ruleDescription string, ruleEnforcem data "ibm_cbr_rule" "cbr_rule" { rule_id = ibm_cbr_rule.cbr_rule.id } - `, ruleDescription, ruleEnforcementMode) + `, ruleDescription, testZoneID, testAccountID, ruleEnforcementMode) } diff --git a/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_zone_test.go b/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_zone_test.go index 1a1e027648..22817af9fb 100644 --- a/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_zone_test.go +++ b/ibm/service/contextbasedrestrictions/data_source_ibm_cbr_zone_test.go @@ -45,7 +45,7 @@ func TestAccIBMCbrZoneDataSourceBasic(t *testing.T) { func TestAccIBMCbrZoneDataSourceAllArgs(t *testing.T) { zoneName := fmt.Sprintf("tf_name_%d", acctest.RandIntRange(10, 100)) - zoneAccountID := "12ab34cd56ef78ab90cd12ef34ab56cd" + zoneAccountID := testAccountID zoneDescription := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) resource.Test(t, resource.TestCase{ @@ -86,7 +86,7 @@ func testAccCheckIBMCbrZoneDataSourceConfigBasic() string { resource "ibm_cbr_zone" "cbr_zone" { name = "Test Zone Data Source Config Basic" description = "Test Zone Data Source Config Basic" - account_id = "12ab34cd56ef78ab90cd12ef34ab56cd" + account_id = "%s" addresses { type = "ipRange" value = "169.23.22.0-169.23.22.255" @@ -96,7 +96,7 @@ func testAccCheckIBMCbrZoneDataSourceConfigBasic() string { data "ibm_cbr_zone" "cbr_zone" { zone_id = ibm_cbr_zone.cbr_zone.id } - `) + `, testAccountID) } func testAccCheckIBMCbrZoneDataSourceConfig(zoneName string, zoneAccountID string, zoneDescription string) string { diff --git a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule_test.go b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule_test.go index 8434734ae3..a790388835 100644 --- a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule_test.go +++ b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule_test.go @@ -78,13 +78,13 @@ func testAccCheckIBMCbrRuleConfigBasic() string { contexts { attributes { name = "networkZoneId" - value = "559052eb8f43302824e7ae490c0281eb" + value = "%s" } } resources { attributes { name = "accountId" - value = "12ab34cd56ef78ab90cd12ef34ab56cd" + value = "%s" } attributes { name = "serviceName" @@ -97,7 +97,7 @@ func testAccCheckIBMCbrRuleConfigBasic() string { } enforcement_mode = "disabled" } - `) + `, testZoneID, testAccountID) } func testAccCheckIBMCbrRuleConfig(description string, enforcementMode string) string { @@ -108,13 +108,13 @@ func testAccCheckIBMCbrRuleConfig(description string, enforcementMode string) st contexts { attributes { name = "networkZoneId" - value = "559052eb8f43302824e7ae490c0281eb" + value = "%s" } } resources { attributes { name = "accountId" - value = "12ab34cd56ef78ab90cd12ef34ab56cd" + value = "%s" } attributes { name = "serviceName" @@ -133,7 +133,7 @@ func testAccCheckIBMCbrRuleConfig(description string, enforcementMode string) st } enforcement_mode = "%s" } - `, description, enforcementMode) + `, description, testZoneID, testAccountID, enforcementMode) } func testAccCheckIBMCbrRuleExists(n string, obj contextbasedrestrictionsv1.Rule) resource.TestCheckFunc { diff --git a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone_test.go b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone_test.go index 9910b07885..c627dd1a5c 100644 --- a/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone_test.go +++ b/ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone_test.go @@ -37,10 +37,10 @@ func TestAccIBMCbrZoneBasic(t *testing.T) { func TestAccIBMCbrZoneAllArgs(t *testing.T) { var conf contextbasedrestrictionsv1.Zone name := fmt.Sprintf("tf_name_%d", acctest.RandIntRange(10, 100)) - accountID := fmt.Sprintf("12ab34cd56ef78ab90cd12ef34ab56cd") + accountID := testAccountID description := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) nameUpdate := fmt.Sprintf("tf_name_%d", acctest.RandIntRange(10, 100)) - accountIDUpdate := fmt.Sprintf("12ab34cd56ef78ab90cd12ef34ab56cd") + accountIDUpdate := testAccountID descriptionUpdate := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) resource.Test(t, resource.TestCase{ @@ -79,13 +79,13 @@ func testAccCheckIBMCbrZoneConfigBasic() string { resource "ibm_cbr_zone" "cbr_zone" { name = "Test Zone Resource Config Basic" description = "Test Zone Resource Config Basic" - account_id = "12ab34cd56ef78ab90cd12ef34ab56cd" + account_id = "%s" addresses { type = "ipRange" value = "169.23.22.0-169.23.22.255" } } - `) + `, testAccountID) } func testAccCheckIBMCbrZoneConfig(name string, accountID string, description string) string { From 38db859fc0620986517c80055f19809bf84b18d0 Mon Sep 17 00:00:00 2001 From: Diksha Mali Date: Tue, 30 Jan 2024 05:02:09 +0530 Subject: [PATCH 08/34] Adding the fix for cos deletion access denied issue --- ibm/service/cos/resource_ibm_cos_bucket.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ibm/service/cos/resource_ibm_cos_bucket.go b/ibm/service/cos/resource_ibm_cos_bucket.go index abcc543635..a7bfcace0b 100644 --- a/ibm/service/cos/resource_ibm_cos_bucket.go +++ b/ibm/service/cos/resource_ibm_cos_bucket.go @@ -20,6 +20,7 @@ import ( token "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam/token" "github.com/IBM/ibm-cos-sdk-go/aws/session" "github.com/IBM/ibm-cos-sdk-go/service/s3" + rc "github.com/IBM/platform-services-go-sdk/resourcecontrollerv2" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -1550,7 +1551,26 @@ func resourceIBMCOSBucketExists(d *schema.ResourceData, meta interface{}) (bool, if len(bucket_meta) < 2 || len(strings.Split(bucket_meta[1], ":")) < 2 { return false, fmt.Errorf("[ERROR] Error parsing bucket ID. Bucket ID format must be: $CRN:meta:$buckettype:$bucketlocation") } - + resourceInstanceId := strings.Split(d.Id(), ":bucket:")[0] + resourceInstanceIdInput := resourceInstanceId + "::" + resourceInstanceGet := rc.GetResourceInstanceOptions{ + ID: &resourceInstanceIdInput, + } + rsConClientV2, errConf := meta.(conns.ClientSession).ResourceControllerV2API() + if errConf != nil { + return false, errConf + } + instance, resp, err := rsConClientV2.GetResourceInstance(&resourceInstanceGet) + if err != nil { + if resp != nil && resp.StatusCode == 404 { + return false, nil + } + fmt.Println(fmt.Errorf("[WARN] Error getting resource instance from cos bucket: %s with resp code: %s", err, resp)) + } + if instance != nil && (strings.Contains(*instance.State, "removed") || strings.Contains(*instance.State, "pending_reclamation")) { + log.Printf("[WARN] Removing instance from state because it's in removed or pending_reclamation state from the cos bucket resource") + return false, nil + } bucketName := parseBucketId(d.Id(), "bucketName") serviceID := parseBucketId(d.Id(), "serviceID") From ef4e36549e546c35d3f9333c6eae49d602b7ee17 Mon Sep 17 00:00:00 2001 From: Ujjwal Kumar Date: Mon, 29 Jan 2024 10:35:33 +0530 Subject: [PATCH 09/34] fix: fixed name update issue on is_instance boot_volume --- ibm/service/vpc/resource_ibm_is_instance.go | 24 ++++++ .../vpc/resource_ibm_is_instance_test.go | 83 +++++++++++++++++++ 2 files changed, 107 insertions(+) diff --git a/ibm/service/vpc/resource_ibm_is_instance.go b/ibm/service/vpc/resource_ibm_is_instance.go index 2debbf2734..da973a044a 100644 --- a/ibm/service/vpc/resource_ibm_is_instance.go +++ b/ibm/service/vpc/resource_ibm_is_instance.go @@ -3545,6 +3545,30 @@ func instanceUpdate(d *schema.ResourceData, meta interface{}) error { } } } + bootVolName := "boot_volume.0.name" + if d.HasChange(bootVolName) && !d.IsNewResource() { + volId := d.Get("boot_volume.0.volume_id").(string) + volName := d.Get(bootVolName).(string) + updateVolumeOptions := &vpcv1.UpdateVolumeOptions{ + ID: &volId, + } + volPatchModel := &vpcv1.VolumePatch{ + Name: &volName, + } + volPatchModelAsPatch, err := volPatchModel.AsPatch() + + if err != nil { + return (fmt.Errorf("[ERROR] Error encountered while apply as patch for boot volume name update of instance %s", err)) + } + + updateVolumeOptions.VolumePatch = volPatchModelAsPatch + + vol, res, err := instanceC.UpdateVolume(updateVolumeOptions) + + if vol == nil || err != nil { + return (fmt.Errorf("[ERROR] Error encountered while updating name of boot volume of instance %s/n%s", err, res)) + } + } bootVolAutoDel := "boot_volume.0.auto_delete_volume" if d.HasChange(bootVolAutoDel) && !d.IsNewResource() { listvolattoptions := &vpcv1.ListInstanceVolumeAttachmentsOptions{ diff --git a/ibm/service/vpc/resource_ibm_is_instance_test.go b/ibm/service/vpc/resource_ibm_is_instance_test.go index 6d0b0055b8..892958a5b4 100644 --- a/ibm/service/vpc/resource_ibm_is_instance_test.go +++ b/ibm/service/vpc/resource_ibm_is_instance_test.go @@ -252,6 +252,54 @@ ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCKVmnMOlHKcZK8tpt3MP1lqOLAcqcJzhsvJcjscgVE }, }) } +func TestAccIBMISInstance_RenameBoot(t *testing.T) { + var instance string + vpcname := fmt.Sprintf("tf-vpc-%d", acctest.RandIntRange(10, 100)) + name := fmt.Sprintf("tf-instnace-%d", acctest.RandIntRange(10, 100)) + subnetname := fmt.Sprintf("tf-subnet-%d", acctest.RandIntRange(10, 100)) + publicKey := strings.TrimSpace(` +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCKVmnMOlHKcZK8tpt3MP1lqOLAcqcJzhsvJcjscgVERRN7/9484SOBJ3HSKxxNG5JN8owAjy5f9yYwcUg+JaUVuytn5Pv3aeYROHGGg+5G346xaq3DAwX6Y5ykr2fvjObgncQBnuU5KHWCECO/4h8uWuwh/kfniXPVjFToc+gnkqA+3RKpAecZhFXwfalQ9mMuYGFxn+fwn8cYEApsJbsEmb0iJwPiZ5hjFC8wREuiTlhPHDgkBLOiycd20op2nXzDbHfCHInquEe/gYxEitALONxm0swBOwJZwlTDOB7C6y2dzlrtxr1L59m7pCkWI4EtTRLvleehBoj3u7jB4usR +`) + sshname := fmt.Sprintf("tf-ssh-%d", acctest.RandIntRange(10, 100)) + userData1 := "a" + rename1 := fmt.Sprintf("tf-bootvol-%d", acctest.RandIntRange(10, 100)) + rename2 := fmt.Sprintf("tf-bootvol-update-%d", acctest.RandIntRange(10, 100)) + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMISInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMISInstanceRenameConfig(vpcname, subnetname, sshname, publicKey, name, userData1, rename1), + Check: resource.ComposeTestCheckFunc( + testAccCheckIBMISInstanceExists("ibm_is_instance.testacc_instance", instance), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "name", name), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "user_data", userData1), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "boot_volume.0.name", rename1), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "zone", acc.ISZoneName), + ), + }, + { + Config: testAccCheckIBMISInstanceRenameConfig(vpcname, subnetname, sshname, publicKey, name, userData1, rename2), + Check: resource.ComposeTestCheckFunc( + testAccCheckIBMISInstanceExists("ibm_is_instance.testacc_instance", instance), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "name", name), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "user_data", userData1), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "boot_volume.0.name", rename2), + resource.TestCheckResourceAttr( + "ibm_is_instance.testacc_instance", "zone", acc.ISZoneName), + ), + }, + }, + }) +} func TestAccIBMISInstance_bootVolumeUserTags(t *testing.T) { var instance string @@ -1219,6 +1267,41 @@ func testAccCheckIBMISInstanceResizeConfig(vpcname, subnetname, sshname, publicK keys = [ibm_is_ssh_key.testacc_sshkey.id] }`, vpcname, subnetname, acc.ISZoneName, acc.ISCIDR, sshname, publicKey, name, acc.IsImage, acc.InstanceProfileName, resize, userData, acc.ISZoneName) } +func testAccCheckIBMISInstanceRenameConfig(vpcname, subnetname, sshname, publicKey, name, userData, rename string) string { + return fmt.Sprintf(` + resource "ibm_is_vpc" "testacc_vpc" { + name = "%s" + } + + resource "ibm_is_subnet" "testacc_subnet" { + name = "%s" + vpc = ibm_is_vpc.testacc_vpc.id + zone = "%s" + ipv4_cidr_block = "%s" + } + + resource "ibm_is_ssh_key" "testacc_sshkey" { + name = "%s" + public_key = "%s" + } + + resource "ibm_is_instance" "testacc_instance" { + name = "%s" + image = "%s" + profile = "%s" + boot_volume { + name = "%s" + } + primary_network_interface { + subnet = ibm_is_subnet.testacc_subnet.id + } + user_data = "%s" + vpc = ibm_is_vpc.testacc_vpc.id + zone = "%s" + keys = [ibm_is_ssh_key.testacc_sshkey.id] + } + `, vpcname, subnetname, acc.ISZoneName, acc.ISCIDR, sshname, publicKey, name, acc.IsImage, acc.InstanceProfileName, rename, userData, acc.ISZoneName) +} func testAccCheckIBMISInstanceBandwidthConfig(vpcname, subnetname, sshname, publicKey, name string, bandwidth int) string { return fmt.Sprintf(` From 998a204612d28a803909ccf5ae48455c678feec7 Mon Sep 17 00:00:00 2001 From: yonatanyell <69857977+yonatanyell@users.noreply.github.com> Date: Tue, 30 Jan 2024 14:32:38 +0200 Subject: [PATCH 10/34] SM docs fix (#5080) * SC addition * SC addition * SC addition * update function updated * SC unit tests added * SC unit tests added * d * tests fixes * tests fixes * update sdk * .secrets.baseline update * .secrets.baseline update * .secrets.baseline update * Update sm_service_credentials_secret_metadata.html.markdown * bugs fixes * bugs fixes * bugs fixes * docs bugs fixes * preferred_chain added for public cert lets encrypt configuration * support for creating secret version for username password & version_custom_metadata for all * support for creating secret version for username password & version_custom_metadata for all * support for creating secret version for username password & version_custom_metadata for all * support for creating secret version for username password & version_custom_metadata for all * support for creating secret version for username password & version_custom_metadata for all * support for creating secret version for username password & version_custom_metadata for all * preferred chain docs update * support for creating secret version for username password & version_custom_metadata for all * support for creating secret version for username password & version_custom_metadata for all * support for creating secret version for username password & version_custom_metadata for all * fix public cert bug --------- Co-authored-by: Yonathan-Yellin Co-authored-by: Avi Ribchinsky Co-authored-by: Tatyana Co-authored-by: Idan Adar Co-authored-by: HARINI KANTAREDDY --- .secrets.baseline | 2 +- .../resource_ibm_sm_public_certificate.go | 29 ++++++++++--------- ...onfiguration_ca_lets_encrypt.html.markdown | 4 +-- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index aabe3b44ef..0cd34d7245 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "go.mod|go.sum|.*.map|^.secrets.baseline$", "lines": null }, - "generated_at": "2024-01-27T06:56:14Z", + "generated_at": "2024-01-29T11:06:53Z", "plugins_used": [ { "name": "AWSKeyDetector" diff --git a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go index 61b5575d97..8cbd049687 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go @@ -635,21 +635,24 @@ func resourceIbmSmPublicCertificateRead(context context.Context, d *schema.Resou if err = d.Set("private_key", secret.PrivateKey); err != nil { return diag.FromErr(fmt.Errorf("Error setting private_key: %s", err)) } - // Call get version metadata API to get the current version_custom_metadata - getVersionMetdataOptions := &secretsmanagerv2.GetSecretVersionMetadataOptions{} - getVersionMetdataOptions.SetSecretID(secretId) - getVersionMetdataOptions.SetID("current") - versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) - if err != nil { - log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) - } + if *secret.StateDescription == "active" { + // Call get version metadata API to get the current version_custom_metadata + getVersionMetdataOptions := &secretsmanagerv2.GetSecretVersionMetadataOptions{} + getVersionMetdataOptions.SetSecretID(secretId) + getVersionMetdataOptions.SetID("current") + + versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) + if err != nil { + log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + } - versionMetadata := versionMetadataIntf.(*secretsmanagerv2.PublicCertificateVersionMetadata) - if versionMetadata.VersionCustomMetadata != nil { - if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + versionMetadata := versionMetadataIntf.(*secretsmanagerv2.PublicCertificateVersionMetadata) + if versionMetadata.VersionCustomMetadata != nil { + if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + } } } diff --git a/website/docs/r/sm_public_certificate_configuration_ca_lets_encrypt.html.markdown b/website/docs/r/sm_public_certificate_configuration_ca_lets_encrypt.html.markdown index 6c8cebb18c..e1e9cc1af3 100644 --- a/website/docs/r/sm_public_certificate_configuration_ca_lets_encrypt.html.markdown +++ b/website/docs/r/sm_public_certificate_configuration_ca_lets_encrypt.html.markdown @@ -32,8 +32,8 @@ Review the argument reference that you can specify for your resource. * Constraints: Allowable values are: `private`, `public`. * `lets_encrypt_environment` - (Required, String) The configuration of the Let's Encrypt CA environment. * Constraints: Allowable values are: `production`, `staging`. -* `lets_encrypt_preferred_chain` - (Optional, String) Prefer the chain with an issuer matching this Subject Common Name. - * Constraints: The maximum length is `30` characters. The minimum length is `2` characters. The value must match regular expression `/(.*?)/`. +* `lets_encrypt_preferred_chain` - (Optional, String) This field supports only the chains that Let's Encrypt provides. Keep empty to use the default or supply a valid Let's Encrypt-provided value. For a list of supported chains, see: https://letsencrypt.org/certificates/. + * Constraints: The value must match regular expression `/(.*?)/`. * `lets_encrypt_private_key` - (Required, String) The PEM encoded private key of your Lets Encrypt account. * Constraints: The maximum length is `100000` characters. The minimum length is `50` characters. The value must match regular expression `/(^-----BEGIN PRIVATE KEY-----.*?)/`. * `name` - (Required, String) A human-readable unique name to assign to your configuration. From 111c00402c422af8f52e436f0936e74a2907bc78 Mon Sep 17 00:00:00 2001 From: IBM-diksha <112411162+IBM-diksha@users.noreply.github.com> Date: Tue, 30 Jan 2024 18:53:53 +0530 Subject: [PATCH 11/34] Adding changes in the fix for cos deletion access denied issue (#5085) * Adding the fix for cos deletion access denied issue * Addressing the review comments --- ibm/service/cos/resource_ibm_cos_bucket.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm/service/cos/resource_ibm_cos_bucket.go b/ibm/service/cos/resource_ibm_cos_bucket.go index a7bfcace0b..fabf40bc9d 100644 --- a/ibm/service/cos/resource_ibm_cos_bucket.go +++ b/ibm/service/cos/resource_ibm_cos_bucket.go @@ -1565,7 +1565,7 @@ func resourceIBMCOSBucketExists(d *schema.ResourceData, meta interface{}) (bool, if resp != nil && resp.StatusCode == 404 { return false, nil } - fmt.Println(fmt.Errorf("[WARN] Error getting resource instance from cos bucket: %s with resp code: %s", err, resp)) + return false, fmt.Errorf("[WARN] Error getting resource instance from cos bucket: %s with resp code: %s", err, resp) } if instance != nil && (strings.Contains(*instance.State, "removed") || strings.Contains(*instance.State, "pending_reclamation")) { log.Printf("[WARN] Removing instance from state because it's in removed or pending_reclamation state from the cos bucket resource") From d08c60b853b80afad87ba2653f3d21a9974d1246 Mon Sep 17 00:00:00 2001 From: hkantare Date: Tue, 30 Jan 2024 20:40:05 +0530 Subject: [PATCH 12/34] Bump up version to 1.62.0 --- CHANGELOG.md | 34 ++++++++++++++++++++++++++++++++++ version/version.go | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b45831b62..d6842cdc6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,37 @@ +# 1.62.0 (Jan 30, 2024) +Features +* Support for Power Virtual Instance + - **Datasources** + - ibm_pi_volume_clone + - **Resources** + - ibm_pi_volume_clone +Enhancements +* Support security groups for Kuberentes workers ([4953](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/4953)) +* Support service_subnet, pod_subnet for Satellite location ([4953](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/4953)) +* Add resource instance sample config code part in the website doc ([5023](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5023)) +* fix(vpc-routing-table): support removing of advertise routes and accept routes from array ([5039](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5039)) +* support parameters for resource instance datasource ([5065](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5065)) +* remove forcenew from workerpool fields in cluster resource and added ApplyOnce ([4955](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/4955)) +* SM fixes ([5045](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5045)) +* Terraform support for ICD isolated compute and multitenant cores ([4628](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/4628)) +* Refactor Cloud connection refactor data source and documentation ([5053](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5053)) +* support empty lists for CBR rule contexts and zone addresses ([5058](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5058)) +* fix(IAM Policy Management): Add operator support to subject_attributes in Authorziation Policy ([5076](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5076)) +* fix(routing-table-route) - fix routing table route advertise patch and action ([5069](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5069)) +* encode test ids as constants for easy replacement ([5059](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5059)) +* Adding the fix for cos deletion access denied issue ([5083](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5083)) +* fix: fixed name update issue on is_instance boot_volume ([5084](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5084)) + +BugFixes +* CD scc doc updates ([4984](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/4984)) +* Fix mtu requirement bug ([5027](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5027)) +* listing all the connection for transit gateway over the pagination set ([5033](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5033)) +* Projects issue #2672 - "Terraform sees inputs as changed ([5042](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5033)) +* added a nil check on data source of bm servers ([5062](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5062)) +* Soft remove the datasources for secretManager v1 ([5063](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5063)) +* Schematics agent related fixes for GA ([5041](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5041)) +* SM docs fix ([5080](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5080)) + # 1.62.0-beta0 (Jan 21, 2024) Features * Support for Power Virtual Instance diff --git a/version/version.go b/version/version.go index 69b40ff553..5ee2b1e015 100644 --- a/version/version.go +++ b/version/version.go @@ -5,7 +5,7 @@ import ( ) // Version is the current provider main version -const Version = "1.62.0-beta0" +const Version = "1.62.0" // GitCommit is the git commit that was compiled. This will be filled in by the compiler. var GitCommit string From a0a83ed1220a70577c951516cebbaf81c9149ff2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A1lint=20R=C3=A9thelyi?= Date: Wed, 31 Jan 2024 17:06:41 +0000 Subject: [PATCH 13/34] remove forcenew, add computed and applyonce --- .../resource_ibm_satellite_location.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/ibm/service/satellite/resource_ibm_satellite_location.go b/ibm/service/satellite/resource_ibm_satellite_location.go index 9002077795..ccb0d40b81 100644 --- a/ibm/service/satellite/resource_ibm_satellite_location.go +++ b/ibm/service/satellite/resource_ibm_satellite_location.go @@ -210,16 +210,18 @@ func ResourceIBMSatelliteLocation() *schema.Resource { Sensitive: true, }, "service_subnet": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Description: "Custom subnet CIDR to provide private IP addresses for services", + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Custom subnet CIDR to provide private IP addresses for services", + DiffSuppressFunc: flex.ApplyOnce, }, "pod_subnet": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Description: "Custom subnet CIDR to provide private IP addresses for pods", + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Custom subnet CIDR to provide private IP addresses for pods", + DiffSuppressFunc: flex.ApplyOnce, }, }, } From a30b2625262c7495832aaf12dd923cb05c15b6ab Mon Sep 17 00:00:00 2001 From: Phaneendra Divi <115419375+PhaniDivi-613@users.noreply.github.com> Date: Mon, 5 Feb 2024 09:54:34 +0530 Subject: [PATCH 14/34] Added new region eu-fr2 (#5073) Co-authored-by: Divi-Tiru-Sai-Gopala-Pavana-Phaneendra Co-authored-by: HARINI KANTAREDDY --- .../atracker/resource_ibm_atracker_settings_test.go | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/ibm/service/atracker/resource_ibm_atracker_settings_test.go b/ibm/service/atracker/resource_ibm_atracker_settings_test.go index 07d7ad0efe..29f9c5138e 100644 --- a/ibm/service/atracker/resource_ibm_atracker_settings_test.go +++ b/ibm/service/atracker/resource_ibm_atracker_settings_test.go @@ -17,9 +17,8 @@ import ( func TestAccIBMAtrackerSettingsBasic(t *testing.T) { var conf atrackerv2.Settings - metadataRegionPrimary := "us-east" + metadataRegionPrimary := "us-south" privateAPIEndpointOnly := "false" - metadataRegionPrimaryUpdate := "us-south" resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, @@ -36,15 +35,6 @@ func TestAccIBMAtrackerSettingsBasic(t *testing.T) { resource.TestCheckResourceAttr("ibm_atracker_settings.atracker_settings", "private_api_endpoint_only", privateAPIEndpointOnly), ), }, - resource.TestStep{ - Config: testAccCheckIBMAtrackerSettingsConfigBasic(metadataRegionPrimaryUpdate, - metadataRegionPrimary, privateAPIEndpointOnly), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("ibm_atracker_settings.atracker_settings", "metadata_region_primary", metadataRegionPrimaryUpdate), - resource.TestCheckResourceAttr("ibm_atracker_settings.atracker_settings", "metadata_region_backup", metadataRegionPrimary), - resource.TestCheckResourceAttr("ibm_atracker_settings.atracker_settings", "private_api_endpoint_only", privateAPIEndpointOnly), - ), - }, }, }) } From 95dd2b142f00afb976d3116d904907ecbbfb7d46 Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Mon, 5 Feb 2024 10:02:48 +0530 Subject: [PATCH 15/34] Refactor sap profile data source and documentation (#5098) * Refactor sap profile data source and documentation * Pull ibm_ pi_constants.go from constant-refactor branch * Replace bool with Boolean --- .../power/data_source_ibm_pi_sap_profile.go | 60 +++++++++-------- .../power/data_source_ibm_pi_sap_profiles.go | 66 ++++++++++--------- website/docs/d/pi_sap_profile.html.markdown | 12 ++-- website/docs/d/pi_sap_profiles.html.markdown | 12 ++-- 4 files changed, 73 insertions(+), 77 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_sap_profile.go b/ibm/service/power/data_source_ibm_pi_sap_profile.go index 43510987d1..1f53d1ad72 100644 --- a/ibm/service/power/data_source_ibm_pi_sap_profile.go +++ b/ibm/service/power/data_source_ibm_pi_sap_profile.go @@ -7,49 +7,51 @@ import ( "context" "log" + "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - - "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" ) func DataSourceIBMPISAPProfile() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPISAPProfileRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - PISAPInstanceProfileID: { - Type: schema.TypeString, - Required: true, - Description: "SAP Profile ID", + Arg_SAPProfileID: { + Description: "SAP Profile ID", + Required: true, + Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - PISAPProfileCertified: { - Type: schema.TypeBool, + + // Attributes + Attr_Certified: { Computed: true, - Description: "Has certification been performed on profile", + Description: "Has certification been performed on profile.", + Type: schema.TypeBool, }, - PISAPProfileCores: { - Type: schema.TypeInt, + Attr_Cores: { Computed: true, - Description: "Amount of cores", - }, - PISAPProfileMemory: { + Description: "Amount of cores.", Type: schema.TypeInt, + }, + Attr_Memory: { Computed: true, - Description: "Amount of memory (in GB)", + Description: "Amount of memory (in GB).", + Type: schema.TypeInt, }, - PISAPProfileType: { - Type: schema.TypeString, + Attr_Type: { Computed: true, - Description: "Type of profile", + Description: "Type of profile.", + Type: schema.TypeString, }, }, } @@ -61,8 +63,8 @@ func dataSourceIBMPISAPProfileRead(ctx context.Context, d *schema.ResourceData, return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - profileID := d.Get(PISAPInstanceProfileID).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + profileID := d.Get(Arg_SAPProfileID).(string) client := instance.NewIBMPISAPInstanceClient(ctx, sess, cloudInstanceID) sapProfile, err := client.GetSAPProfile(profileID) @@ -72,10 +74,10 @@ func dataSourceIBMPISAPProfileRead(ctx context.Context, d *schema.ResourceData, } d.SetId(*sapProfile.ProfileID) - d.Set(PISAPProfileCertified, *sapProfile.Certified) - d.Set(PISAPProfileCores, *sapProfile.Cores) - d.Set(PISAPProfileMemory, *sapProfile.Memory) - d.Set(PISAPProfileType, *sapProfile.Type) + d.Set(Attr_Certified, *sapProfile.Certified) + d.Set(Attr_Cores, *sapProfile.Cores) + d.Set(Attr_Memory, *sapProfile.Memory) + d.Set(Attr_Type, *sapProfile.Type) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_sap_profiles.go b/ibm/service/power/data_source_ibm_pi_sap_profiles.go index 0b314791ca..a3c3c5f5a6 100644 --- a/ibm/service/power/data_source_ibm_pi_sap_profiles.go +++ b/ibm/service/power/data_source_ibm_pi_sap_profiles.go @@ -7,58 +7,60 @@ import ( "context" "log" + "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - - "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" ) func DataSourceIBMPISAPProfiles() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPISAPProfilesRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - PISAPProfiles: { - Type: schema.TypeList, - Computed: true, + + // Attributes + Attr_Profiles: { + Computed: true, + Description: "List of all the SAP Profiles.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - PISAPProfileCertified: { - Type: schema.TypeBool, + Attr_Certified: { Computed: true, - Description: "Has certification been performed on profile", + Description: "Has certification been performed on profile.", + Type: schema.TypeBool, }, - PISAPProfileCores: { - Type: schema.TypeInt, + Attr_Cores: { Computed: true, - Description: "Amount of cores", - }, - PISAPProfileMemory: { + Description: "Amount of cores.", Type: schema.TypeInt, - Computed: true, - Description: "Amount of memory (in GB)", }, - PISAPProfileID: { - Type: schema.TypeString, + Attr_Memory: { Computed: true, - Description: "SAP Profile ID", + Description: "Amount of memory (in GB).", + Type: schema.TypeInt, }, - PISAPProfileType: { + Attr_ProfileID: { + Computed: true, + Description: "SAP Profile ID.", Type: schema.TypeString, + }, + Attr_Type: { Computed: true, - Description: "Type of profile", + Description: "Type of profile.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, }, }, } @@ -70,7 +72,7 @@ func dataSourceIBMPISAPProfilesRead(ctx context.Context, d *schema.ResourceData, return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) client := instance.NewIBMPISAPInstanceClient(ctx, sess, cloudInstanceID) sapProfiles, err := client.GetAllSAPProfiles(cloudInstanceID) @@ -82,18 +84,18 @@ func dataSourceIBMPISAPProfilesRead(ctx context.Context, d *schema.ResourceData, result := make([]map[string]interface{}, 0, len(sapProfiles.Profiles)) for _, sapProfile := range sapProfiles.Profiles { profile := map[string]interface{}{ - PISAPProfileCertified: *sapProfile.Certified, - PISAPProfileCores: *sapProfile.Cores, - PISAPProfileMemory: *sapProfile.Memory, - PISAPProfileID: *sapProfile.ProfileID, - PISAPProfileType: *sapProfile.Type, + Attr_Certified: *sapProfile.Certified, + Attr_Cores: *sapProfile.Cores, + Attr_Memory: *sapProfile.Memory, + Attr_ProfileID: *sapProfile.ProfileID, + Attr_Type: *sapProfile.Type, } result = append(result, profile) } var genID, _ = uuid.GenerateUUID() d.SetId(genID) - d.Set(PISAPProfiles, result) + d.Set(Attr_Profiles, result) return nil } diff --git a/website/docs/d/pi_sap_profile.html.markdown b/website/docs/d/pi_sap_profile.html.markdown index 2be43b8874..32717c17f7 100644 --- a/website/docs/d/pi_sap_profile.html.markdown +++ b/website/docs/d/pi_sap_profile.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_sap_profile" @@ -11,7 +10,6 @@ description: |- Retrieve information about a SAP profile. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_sap_profile" "example" { pi_cloud_instance_id = "" @@ -20,14 +18,12 @@ data "ibm_pi_sap_profile" "example" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" diff --git a/website/docs/d/pi_sap_profiles.html.markdown b/website/docs/d/pi_sap_profiles.html.markdown index 4106f1fa84..630242ee68 100644 --- a/website/docs/d/pi_sap_profiles.html.markdown +++ b/website/docs/d/pi_sap_profiles.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_sap_profiles" @@ -11,7 +10,6 @@ description: |- Retrieve information about all SAP profiles. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_sap_profiles" "example" { pi_cloud_instance_id = "" @@ -19,14 +17,12 @@ data "ibm_pi_sap_profiles" "example" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" From 579dab501df6ad9b82c3e452527303f7a5a884c0 Mon Sep 17 00:00:00 2001 From: Phaneendra Divi <115419375+PhaniDivi-613@users.noreply.github.com> Date: Mon, 5 Feb 2024 10:11:35 +0530 Subject: [PATCH 16/34] Added new region eu-fr2 (#5074) Co-authored-by: Divi-Tiru-Sai-Gopala-Pavana-Phaneendra --- .../metricsrouter/resource_ibm_metrics_router_route_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm/service/metricsrouter/resource_ibm_metrics_router_route_test.go b/ibm/service/metricsrouter/resource_ibm_metrics_router_route_test.go index d84f2404bc..6c1e2e8fe7 100644 --- a/ibm/service/metricsrouter/resource_ibm_metrics_router_route_test.go +++ b/ibm/service/metricsrouter/resource_ibm_metrics_router_route_test.go @@ -139,7 +139,7 @@ func TestAccIBMMetricsRouterRouteSendNoTarget(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccCheckIBMMetricsRouterRouteNoTarget(name, action), - ExpectError: regexp.MustCompile("Send rule action requires non-empty targets"), + ExpectError: regexp.MustCompile("You have a rule with empty targets."), }, }, }) From 39adf82444e7a2e769e93cd56e6159420fc3559a Mon Sep 17 00:00:00 2001 From: ismirlia <90468712+ismirlia@users.noreply.github.com> Date: Mon, 5 Feb 2024 07:41:53 -0600 Subject: [PATCH 17/34] Update Forcenew instance fields (#5025) * Add forcenew field markings for instance * Update forcenew fields * Revert imageid forcenew The image id you pass in does not match the image id of the instance created, so if you apply twice in row terraform thinks it has to remake the instance when that's not true. --- ibm/service/power/resource_ibm_pi_instance.go | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/ibm/service/power/resource_ibm_pi_instance.go b/ibm/service/power/resource_ibm_pi_instance.go index 37236ed8ae..d48834dc25 100644 --- a/ibm/service/power/resource_ibm_pi_instance.go +++ b/ibm/service/power/resource_ibm_pi_instance.go @@ -83,20 +83,19 @@ func ResourceIBMPIInstance() *schema.Resource { Description: "Maximum memory size", }, helpers.PIInstanceVolumeIds: { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - DiffSuppressFunc: flex.ApplyOnce, - Description: "List of PI volumes", + Type: schema.TypeSet, + ForceNew: true, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + Description: "List of PI volumes", }, - helpers.PIInstanceUserData: { Type: schema.TypeString, + ForceNew: true, Optional: true, Description: "Base64 encoded data to be passed in for invoking a cloud init script", }, - helpers.PIInstanceStorageType: { Type: schema.TypeString, Optional: true, @@ -154,10 +153,10 @@ func ResourceIBMPIInstance() *schema.Resource { Description: "Indicates if all volumes attached to the server must reside in the same storage pool", }, PIInstanceNetwork: { - Type: schema.TypeList, - Required: true, - DiffSuppressFunc: flex.ApplyOnce, - Description: "List of one or more networks to attach to the instance", + Type: schema.TypeList, + ForceNew: true, + Required: true, + Description: "List of one or more networks to attach to the instance", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "ip_address": { @@ -190,13 +189,14 @@ func ResourceIBMPIInstance() *schema.Resource { }, helpers.PIPlacementGroupID: { Type: schema.TypeString, + ForceNew: true, Optional: true, Description: "Placement group ID", }, Arg_PIInstanceSharedProcessorPool: { Type: schema.TypeString, - Optional: true, ForceNew: true, + Optional: true, ConflictsWith: []string{PISAPInstanceProfileID}, Description: "Shared Processor Pool the instance is deployed on", }, @@ -247,10 +247,10 @@ func ResourceIBMPIInstance() *schema.Resource { Description: "Instance processor type", }, helpers.PIInstanceSSHKeyName: { - Type: schema.TypeString, - Optional: true, - DiffSuppressFunc: flex.ApplyOnce, - Description: "SSH key name", + Type: schema.TypeString, + ForceNew: true, + Optional: true, + Description: "SSH key name", }, helpers.PIInstanceMemory: { Type: schema.TypeFloat, @@ -261,6 +261,7 @@ func ResourceIBMPIInstance() *schema.Resource { }, PIInstanceDeploymentType: { Type: schema.TypeString, + ForceNew: true, Optional: true, Description: "Custom Deployment Type Information", }, @@ -272,23 +273,27 @@ func ResourceIBMPIInstance() *schema.Resource { }, PISAPInstanceDeploymentType: { Type: schema.TypeString, + ForceNew: true, Optional: true, Description: "Custom SAP Deployment Type Information", }, helpers.PIInstanceSystemType: { Type: schema.TypeString, + ForceNew: true, Optional: true, Computed: true, Description: "PI Instance system type", }, helpers.PIInstanceReplicants: { Type: schema.TypeInt, + ForceNew: true, Optional: true, Default: 1, Description: "PI Instance replicas count", }, helpers.PIInstanceReplicationPolicy: { Type: schema.TypeString, + ForceNew: true, Optional: true, ValidateFunc: validate.ValidateAllowedStringValues([]string{"affinity", "anti-affinity", "none"}), Default: "none", @@ -296,6 +301,7 @@ func ResourceIBMPIInstance() *schema.Resource { }, helpers.PIInstanceReplicationScheme: { Type: schema.TypeString, + ForceNew: true, Optional: true, ValidateFunc: validate.ValidateAllowedStringValues([]string{"prefix", "suffix"}), Default: "suffix", From f94402016e0d6a6fdc71aaded5fdbb64184e1c3d Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Mon, 5 Feb 2024 19:13:30 +0530 Subject: [PATCH 18/34] Refactor cloud instance data source and documentation (#5054) * Catalog Refactor cloud instance data source and documentation * Pull ibm_ pi_constants.go from constant-refactor --- .../data_source_ibm_pi_cloud_instance.go | 183 ++++++++++-------- .../data_source_ibm_pi_cloud_instance_test.go | 11 +- .../docs/d/pi_cloud_instance.html.markdown | 15 +- 3 files changed, 108 insertions(+), 101 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_cloud_instance.go b/ibm/service/power/data_source_ibm_pi_cloud_instance.go index f9fa86dcd5..4a09bf2768 100644 --- a/ibm/service/power/data_source_ibm_pi_cloud_instance.go +++ b/ibm/service/power/data_source_ibm_pi_cloud_instance.go @@ -6,96 +6,111 @@ package power import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPICloudInstance() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPICloudInstanceRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Start of Computed Attributes - "enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "tenant_id": { - Type: schema.TypeString, - Computed: true, - }, - "region": { - Type: schema.TypeString, - Computed: true, - }, - "capabilities": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "total_processors_consumed": { - Type: schema.TypeFloat, - Computed: true, + // Attributes + Attr_Capabilities: { + Computed: true, + Description: "Lists the capabilities for this cloud instance.", + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, }, - "total_instances": { - Type: schema.TypeFloat, - Computed: true, + Attr_Enabled: { + Computed: true, + Description: "Indicates whether the tenant is enabled.", + Type: schema.TypeBool, }, - "total_memory_consumed": { - Type: schema.TypeFloat, - Computed: true, - }, - "total_ssd_storage_consumed": { - Type: schema.TypeFloat, - Computed: true, - }, - "total_standard_storage_consumed": { - Type: schema.TypeFloat, - Computed: true, - }, - "pvm_instances": { - Type: schema.TypeList, - Computed: true, + Attr_PVMInstances: { + Computed: true, + Description: "PVM instances owned by the Cloud Instance.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, + Attr_CreationDate: { + Computed: true, + Description: "Date of PVM instance creation.", + Type: schema.TypeString, }, - "name": { - Type: schema.TypeString, - Computed: true, + Attr_Href: { + Computed: true, + Description: "Link to Cloud Instance resource.", + Type: schema.TypeString, }, - "href": { - Type: schema.TypeString, - Computed: true, + Attr_ID: { + Computed: true, + Description: "PVM Instance ID.", + Type: schema.TypeString, }, - "status": { - Type: schema.TypeString, - Computed: true, + Attr_Name: { + Computed: true, + Description: "Name of the server.", + Type: schema.TypeString, }, - "systype": { - Type: schema.TypeString, - Computed: true, + Attr_Status: { + Computed: true, + Description: "The status of the instance.", + Type: schema.TypeString, }, - "creation_date": { - Type: schema.TypeString, - Computed: true, + Attr_SysType: { + Computed: true, + Description: "System type used to host the instance.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, + }, + Attr_Region: { + Computed: true, + Description: "The region the cloud instance lives.", + Type: schema.TypeString, + }, + Attr_TenantID: { + Computed: true, + Description: "The tenant ID that owns this cloud instance.", + Type: schema.TypeString, + }, + Attr_TotalInstances: { + Computed: true, + Description: "The count of lpars that belong to this specific cloud instance.", + Type: schema.TypeFloat, + }, + Attr_TotalMemoryConsumed: { + Computed: true, + Description: "The total memory consumed by this service instance.", + Type: schema.TypeFloat, + }, + Attr_TotalProcessorsConsumed: { + Computed: true, + Description: "The total processors consumed by this service instance.", + Type: schema.TypeFloat, + }, + Attr_TotalSSDStorageConsumed: { + Computed: true, + Description: "The total SSD Storage consumed by this service instance.", + Type: schema.TypeFloat, + }, + Attr_TotalStandardStorageConsumed: { + Computed: true, + Description: "The total Standard Storage consumed by this service instance.", + Type: schema.TypeFloat, }, }, } @@ -107,7 +122,7 @@ func dataSourceIBMPICloudInstanceRead(ctx context.Context, d *schema.ResourceDat return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) cloud_instance := instance.NewIBMPICloudInstanceClient(ctx, sess, cloudInstanceID) cloud_instance_data, err := cloud_instance.Get(cloudInstanceID) @@ -116,35 +131,33 @@ func dataSourceIBMPICloudInstanceRead(ctx context.Context, d *schema.ResourceDat } d.SetId(*cloud_instance_data.CloudInstanceID) - d.Set("tenant_id", (cloud_instance_data.TenantID)) - d.Set("enabled", cloud_instance_data.Enabled) - d.Set("region", cloud_instance_data.Region) - d.Set("capabilities", cloud_instance_data.Capabilities) - d.Set("pvm_instances", flattenpvminstances(cloud_instance_data.PvmInstances)) - d.Set("total_ssd_storage_consumed", cloud_instance_data.Usage.StorageSSD) - d.Set("total_instances", cloud_instance_data.Usage.Instances) - d.Set("total_standard_storage_consumed", cloud_instance_data.Usage.StorageStandard) - d.Set("total_processors_consumed", cloud_instance_data.Usage.Processors) - d.Set("total_memory_consumed", cloud_instance_data.Usage.Memory) - return nil + d.Set(Attr_Capabilities, cloud_instance_data.Capabilities) + d.Set(Attr_Enabled, cloud_instance_data.Enabled) + d.Set(Attr_PVMInstances, flattenpvminstances(cloud_instance_data.PvmInstances)) + d.Set(Attr_Region, cloud_instance_data.Region) + d.Set(Attr_TenantID, (cloud_instance_data.TenantID)) + d.Set(Attr_TotalInstances, cloud_instance_data.Usage.Instances) + d.Set(Attr_TotalMemoryConsumed, cloud_instance_data.Usage.Memory) + d.Set(Attr_TotalProcessorsConsumed, cloud_instance_data.Usage.Processors) + d.Set(Attr_TotalSSDStorageConsumed, cloud_instance_data.Usage.StorageSSD) + d.Set(Attr_TotalStandardStorageConsumed, cloud_instance_data.Usage.StorageStandard) + return nil } func flattenpvminstances(list []*models.PVMInstanceReference) []map[string]interface{} { pvms := make([]map[string]interface{}, 0) for _, lpars := range list { - l := map[string]interface{}{ - "id": *lpars.PvmInstanceID, - "name": *lpars.ServerName, - "href": *lpars.Href, - "status": *lpars.Status, - "systype": lpars.SysType, - "creation_date": lpars.CreationDate.String(), + Attr_CreationDate: lpars.CreationDate.String(), + Attr_ID: *lpars.PvmInstanceID, + Attr_Href: *lpars.Href, + Attr_Name: *lpars.ServerName, + Attr_Status: *lpars.Status, + Attr_SysType: lpars.SysType, } pvms = append(pvms, l) - } return pvms } diff --git a/ibm/service/power/data_source_ibm_pi_cloud_instance_test.go b/ibm/service/power/data_source_ibm_pi_cloud_instance_test.go index 1d80d59337..d2f0b69db9 100644 --- a/ibm/service/power/data_source_ibm_pi_cloud_instance_test.go +++ b/ibm/service/power/data_source_ibm_pi_cloud_instance_test.go @@ -13,7 +13,6 @@ import ( ) func TestAccIBMPICloudInstanceDataSource_basic(t *testing.T) { - resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, Providers: acc.TestAccProviders, @@ -29,10 +28,8 @@ func TestAccIBMPICloudInstanceDataSource_basic(t *testing.T) { } func testAccCheckIBMPICloudInstanceDataSourceConfig() string { - return fmt.Sprintf(` - -data "ibm_pi_cloud_instance" "testacc_ds_cloud_instance" { - pi_cloud_instance_id = "%s" -}`, acc.Pi_cloud_instance_id) - + return fmt.Sprintf(` + data "ibm_pi_cloud_instance" "testacc_ds_cloud_instance" { + pi_cloud_instance_id = "%s" + }`, acc.Pi_cloud_instance_id) } diff --git a/website/docs/d/pi_cloud_instance.html.markdown b/website/docs/d/pi_cloud_instance.html.markdown index 5e65926b84..32dcbb43ba 100644 --- a/website/docs/d/pi_cloud_instance.html.markdown +++ b/website/docs/d/pi_cloud_instance.html.markdown @@ -10,21 +10,19 @@ description: |- Retrieve information about an existing IBM Power Virtual Server Cloud Instance as a read-only data source. For more information, about IBM power virtual server cloud, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_cloud_instance" "ds_cloud_instance" { pi_cloud_instance_id = "49fba6c9-23f8-40bc-9899-aca322ee7d5b" } ``` -## Notes: -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -46,7 +44,7 @@ In addition to the argument reference list, you can access the following attribu - `pvm_instances` - (List) PVM instances owned by the Cloud Instance. Nested scheme for `pvm_instances`: - - `creation_date` - (String) Date/Time of PVM creation. + - `creation_date` - (String) Date of PVM instance creation. - `href` - (String) Link to Cloud Instance resource. - `id` - (String) PVM Instance ID. - `name` - (String) Name of the server. @@ -59,4 +57,3 @@ In addition to the argument reference list, you can access the following attribu - `total_processors_consumed` - (String) The total processors consumed by this service instance. - `total_ssd_storage_consumed` - (String) The total SSD Storage consumed by this service instance. - `total_standard_storage_consumed` - (String) The total Standard Storage consumed by this service instance. - From 4c67edaeb3a57a28eb722f158c71debcfaed4a05 Mon Sep 17 00:00:00 2001 From: Ujjwal Kumar Date: Wed, 31 Jan 2024 10:52:11 +0530 Subject: [PATCH 19/34] updated is_images document --- website/docs/d/is_images.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/website/docs/d/is_images.html.markdown b/website/docs/d/is_images.html.markdown index 012e1beb74..a8dc652a19 100644 --- a/website/docs/d/is_images.html.markdown +++ b/website/docs/d/is_images.html.markdown @@ -36,11 +36,11 @@ data "ibm_is_images" "ds_images" { Review the argument references that you can specify for your data source. -* `catalog_managed` - (Optional, bool) Lists only those images which are managed as part of a catalog offering. -* `resource_group` - (Optional, string) The id of the resource group. -* `name` - (Optional, string) The name of the image. -* `visibility` - (Optional, string) Visibility of the image. -* `status` - (Optional, string) Status of the image. +- `catalog_managed` - (Optional, bool) Lists only those images which are managed as part of a catalog offering. +- `resource_group` - (Optional, string) The id of the resource group. +- `name` - (Optional, string) The name of the image. +- `visibility` - (Optional, string) Visibility of the image. Accepted values : **private**, **public** +- `status` - (Optional, string) Status of the image. Accepted value : **available**, **deleting**, **deprecated**, **failed**, **obsolete**, **pending**, **unusable** ## Attribute reference You can access the following attribute references after your data source is created. From d7271728942ac4f7ce23b1b7cbc7ca4ad057a6d0 Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Mon, 5 Feb 2024 19:31:16 +0530 Subject: [PATCH 20/34] Refactor Workspace data source and documentation (#5106) * Refactor workspace data source and documentation * Pull ibm_ pi_constants.go from constant-refactor * Update branch resolve conflicts --- .../power/data_source_ibm_pi_workspace.go | 52 +++++++-------- .../data_source_ibm_pi_workspace_test.go | 4 +- .../power/data_source_ibm_pi_workspaces.go | 65 +++++++++---------- .../data_source_ibm_pi_workspaces_test.go | 3 +- website/docs/d/pi_workspace.html.markdown | 23 +++---- website/docs/d/pi_workspaces.html.markdown | 37 +++++------ 6 files changed, 80 insertions(+), 104 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_workspace.go b/ibm/service/power/data_source_ibm_pi_workspace.go index 6fb23303ea..0864470922 100644 --- a/ibm/service/power/data_source_ibm_pi_workspace.go +++ b/ibm/service/power/data_source_ibm_pi_workspace.go @@ -7,7 +7,6 @@ import ( "context" "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -15,68 +14,63 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -const ( - WorkspaceCreationDate = "creation_date" - WorkspaceCRN = "crn" - WorkspaceRegion = "region" - WorkspaceType = "type" - WorkspaceUrl = "url" -) - func DatasourceIBMPIWorkspace() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPIWorkspaceRead, Schema: map[string]*schema.Schema{ + // Arguments Arg_CloudInstanceID: { - Type: schema.TypeString, + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, + + // Attributes Attr_WorkspaceCapabilities: { - Type: schema.TypeMap, Computed: true, - Description: "Workspace Capabilities", + Description: "Workspace Capabilities.", Elem: &schema.Schema{ Type: schema.TypeBool, }, + Type: schema.TypeMap, }, Attr_WorkspaceDetails: { - Type: schema.TypeMap, Computed: true, - Description: "Workspace information", + Description: "Workspace information.", + Type: schema.TypeMap, }, Attr_WorkspaceLocation: { - Type: schema.TypeMap, Computed: true, - Description: "Workspace location", + Description: "Workspace location.", + Type: schema.TypeMap, }, Attr_WorkspaceName: { - Type: schema.TypeString, Computed: true, - Description: "Workspace name", + Description: "Workspace name.", + Type: schema.TypeString, }, Attr_WorkspaceStatus: { - Type: schema.TypeString, Computed: true, - Description: "Workspace status", + Description: "Workspace status, active, critical, failed, provisioning.", + Type: schema.TypeString, }, Attr_WorkspaceType: { - Type: schema.TypeString, Computed: true, - Description: "Workspace type", + Description: "Workspace type, off-premises or on-premises.", + Type: schema.TypeString, }, }, } } func dataSourceIBMPIWorkspaceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - // session sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) client := instance.NewIBMPIWorkspacesClient(ctx, sess, cloudInstanceID) wsData, err := client.Get(cloudInstanceID) if err != nil { @@ -88,14 +82,14 @@ func dataSourceIBMPIWorkspaceRead(ctx context.Context, d *schema.ResourceData, m d.Set(Attr_WorkspaceType, wsData.Type) d.Set(Attr_WorkspaceCapabilities, wsData.Capabilities) wsdetails := map[string]interface{}{ - WorkspaceCreationDate: wsData.Details.CreationDate.String(), - WorkspaceCRN: *wsData.Details.Crn, + Attr_CreationDate: wsData.Details.CreationDate.String(), + Attr_CRN: *wsData.Details.Crn, } d.Set(Attr_WorkspaceDetails, flex.Flatten(wsdetails)) wslocation := map[string]interface{}{ - WorkspaceRegion: *wsData.Location.Region, - WorkspaceType: wsData.Location.Type, - WorkspaceUrl: wsData.Location.URL, + Attr_Region: *wsData.Location.Region, + Attr_Type: wsData.Location.Type, + Attr_URL: wsData.Location.URL, } d.Set(Attr_WorkspaceLocation, flex.Flatten(wslocation)) d.SetId(*wsData.ID) diff --git a/ibm/service/power/data_source_ibm_pi_workspace_test.go b/ibm/service/power/data_source_ibm_pi_workspace_test.go index b2adea8072..4a7df8e63a 100644 --- a/ibm/service/power/data_source_ibm_pi_workspace_test.go +++ b/ibm/service/power/data_source_ibm_pi_workspace_test.go @@ -25,10 +25,10 @@ func TestAccIBMPIWorkspaceDataSourceBasic(t *testing.T) { }, }) } + func testAccCheckIBMPIWorkspaceDataSourceConfig() string { return fmt.Sprintf(` data "ibm_pi_workspace" "test" { pi_cloud_instance_id = "%s" - } - `, acc.Pi_cloud_instance_id) + }`, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_workspaces.go b/ibm/service/power/data_source_ibm_pi_workspaces.go index c66e924b63..1208562947 100644 --- a/ibm/service/power/data_source_ibm_pi_workspaces.go +++ b/ibm/service/power/data_source_ibm_pi_workspaces.go @@ -7,7 +7,6 @@ import ( "context" "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -15,62 +14,61 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -const ( - Workspaces = "workspaces" -) - func DatasourceIBMPIWorkspaces() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPIWorkspacesRead, Schema: map[string]*schema.Schema{ + // Arguments Arg_CloudInstanceID: { - Type: schema.TypeString, + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - Workspaces: { + + // Attributes + Attr_Workspaces: { Type: schema.TypeList, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - Attr_WorkspaceCapabilities: { - Type: schema.TypeMap, Computed: true, - Description: "Workspace Capabilities", + Description: "Workspace Capabilities.", Elem: &schema.Schema{ Type: schema.TypeBool, }, + Type: schema.TypeMap, }, Attr_WorkspaceDetails: { - Type: schema.TypeMap, Computed: true, - Description: "Workspace information", + Description: "Workspace information.", + Type: schema.TypeMap, }, Attr_WorkspaceID: { - Type: schema.TypeString, Computed: true, - Description: "Workspace ID", + Description: "Workspace ID.", + Type: schema.TypeString, }, Attr_WorkspaceLocation: { - Type: schema.TypeMap, Computed: true, - Description: "Workspace location", + Description: "Workspace location.", + Type: schema.TypeMap, }, Attr_WorkspaceName: { - Type: schema.TypeString, Computed: true, - Description: "Workspace name", + Description: "Workspace name.", + Type: schema.TypeString, }, Attr_WorkspaceStatus: { - Type: schema.TypeString, Computed: true, - Description: "Workspace status", + Description: "Workspace status, active, critical, failed, provisioning.", + Type: schema.TypeString, }, Attr_WorkspaceType: { - Type: schema.TypeString, Computed: true, - Description: "Workspace type", + Description: "Workspace type, off-premises or on-premises.", + Type: schema.TypeString, }, }, }, @@ -79,13 +77,12 @@ func DatasourceIBMPIWorkspaces() *schema.Resource { } } func dataSourceIBMPIWorkspacesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - // session sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) client := instance.NewIBMPIWorkspacesClient(ctx, sess, cloudInstanceID) wsData, err := client.GetAll() if err != nil { @@ -95,26 +92,26 @@ func dataSourceIBMPIWorkspacesRead(ctx context.Context, d *schema.ResourceData, for _, ws := range wsData.Workspaces { if ws != nil { workspace := map[string]interface{}{ - Attr_WorkspaceName: ws.Name, - Attr_WorkspaceID: ws.ID, - Attr_WorkspaceStatus: ws.Status, - Attr_WorkspaceType: ws.Type, Attr_WorkspaceCapabilities: ws.Capabilities, Attr_WorkspaceDetails: map[string]interface{}{ - WorkspaceCreationDate: ws.Details.CreationDate.String(), - WorkspaceCRN: *ws.Details.Crn, + Attr_CreationDate: ws.Details.CreationDate.String(), + Attr_CRN: *ws.Details.Crn, }, + Attr_WorkspaceID: ws.ID, Attr_WorkspaceLocation: map[string]interface{}{ - WorkspaceRegion: *ws.Location.Region, - WorkspaceType: ws.Location.Type, - WorkspaceUrl: ws.Location.URL, + Attr_Region: *ws.Location.Region, + Attr_Type: ws.Location.Type, + Attr_URL: ws.Location.URL, }, + Attr_WorkspaceName: ws.Name, + Attr_WorkspaceStatus: ws.Status, + Attr_WorkspaceType: ws.Type, } workspaces = append(workspaces, workspace) } } var clientgenU, _ = uuid.GenerateUUID() d.SetId(clientgenU) - d.Set(Workspaces, workspaces) + d.Set(Attr_Workspaces, workspaces) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_workspaces_test.go b/ibm/service/power/data_source_ibm_pi_workspaces_test.go index 076d65a342..10b38e677a 100644 --- a/ibm/service/power/data_source_ibm_pi_workspaces_test.go +++ b/ibm/service/power/data_source_ibm_pi_workspaces_test.go @@ -30,6 +30,5 @@ func testAccCheckIBMPIWorkspacesDataSourceConfig() string { return fmt.Sprintf(` data "ibm_pi_workspaces" "test" { pi_cloud_instance_id = "%s" - } - `, acc.Pi_cloud_instance_id) + }`, acc.Pi_cloud_instance_id) } diff --git a/website/docs/d/pi_workspace.html.markdown b/website/docs/d/pi_workspace.html.markdown index 1b3195f016..6134e2a18c 100644 --- a/website/docs/d/pi_workspace.html.markdown +++ b/website/docs/d/pi_workspace.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_workspace" @@ -8,26 +7,22 @@ description: |- --- # ibm_pi_workspace - Retrieve information about your Power Systems account workspace. ## Example usage - ```terraform data "ibm_pi_workspace" "workspace" { pi_cloud_instance_id = "99fba9c9-66f9-99bc-9999-aca999ee9d9b" } ``` -## Notes - +**Notes** - Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. - If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - `region` - `lon` - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -36,13 +31,11 @@ Example usage: ``` ## Argument reference - Review the argument references that you can specify for your data source. - `pi_cloud_instance_id` - (Required, String) Cloud Instance ID of a PCloud Instance under your account. ## Attribute reference - In addition to all argument reference listed, you can access the following attribute references after your data source is created. - `id` - (String) Workspace ID. @@ -54,14 +47,14 @@ In addition to all argument reference listed, you can access the following attri - `pi_workspace_details` - (Map) Workspace information. Nested schema for `pi_workspace_details`: - - `creation_date` - (String) Workspace creation date. + - `creation_date` - (String) Date of workspace creation. - `crn` - (String) Workspace crn. - `pi_workspace_location` - (Map) Workspace location. Nested schema for `Workspace location`: - - `region` - (String) The Workspace location region zone. - - `type` - (String) The Workspace location region type. - - `url`- (String) The Workspace location region url. -- `pi_workspace_name` - (String) The Workspace name. -- `pi_workspace_status` - (String) The Workspace status, `active`, `critical`, `failed`, `provisioning`. -- `pi_workspace_type` - (String) The Workspace type, `off-premises` or `on-premises`. + - `region` - (String) Workspace location region zone. + - `type` - (String) Workspace location region type. + - `url`- (String) Workspace location region url. +- `pi_workspace_name` - (String) Workspace name. +- `pi_workspace_status` - (String) Workspace status, `active`, `critical`, `failed`, `provisioning`. +- `pi_workspace_type` - (String) Workspace type, `off-premises` or `on-premises`. diff --git a/website/docs/d/pi_workspaces.html.markdown b/website/docs/d/pi_workspaces.html.markdown index 12ca699246..0c5f6e5af2 100644 --- a/website/docs/d/pi_workspaces.html.markdown +++ b/website/docs/d/pi_workspaces.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_workspaces" @@ -8,26 +7,22 @@ description: |- --- # ibm_pi_workspaces - Retrieve information about Power Systems workspaces. ## Example usage - ```terraform data "ibm_pi_workspaces" "workspaces" { pi_cloud_instance_id = "99fba9c9-66f9-99bc-9999-aca999ee9d9b" } ``` -## Notes - +**Notes** - Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. - If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - `region` - `lon` - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -36,34 +31,32 @@ Example usage: ``` ## Argument reference - Review the argument references that you can specify for your data source. -- `pi_cloud_instance_id` - (Required, String) Cloud Instance ID of a PCloud Instance. +- `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. ## Attribute reference - In addition to all argument reference listed, you can access the following attribute references after your data source is created. -- `workspaces` - List of all Workspaces. +- `workspaces` - (List) List of all Workspaces. Nested schema for `workspaces` - `pi_workspace_capabilities` - (Map) Workspace Capabilities. Capabilities are `true` or `false`. - Some of `pi_workspace_capabilities` are: - - `cloud-connections` ,`power-edge-router`, `power-vpn-connections`, `transit-gateway-connection` + Some of `pi_workspace_capabilities` are: + - `cloud-connections`, `power-edge-router`, `power-vpn-connections`, `transit-gateway-connection` - `pi_workspace_details` - (Map) Workspace information. - Nested schema for `pi_workspace_details`: - - `creation_date` - (String) Workspace creation date. - - `crn` - (String) Workspace crn. + Nested schema for `pi_workspace_details`: + - `creation_date` - (String) Date of workspace creation. + - `crn` - (String) Workspace crn. - `pi_workspace_id` - (String) Workspace ID. - `pi_workspace_location` - (Map) Workspace location. - Nested schema for `Workspace location`: - - `region` - (String) The Workspace location region zone. - - `type` - (String) The Workspace location region type. - - `url`- (String) The Workspace location region url. - - `pi_workspace_name` - (String) The Workspace name. - - `pi_workspace_status` - (String) The Workspace status, `active`, `critical`, `failed`, `provisioning`. - - `pi_workspace_type` - (String) The Workspace type, `off-premises` or `on-premises`. + Nested schema for `Workspace location`: + - `region` - (String) Workspace location region zone. + - `type` - (String) Workspace location region type. + - `url`- (String) Workspace location region url. + - `pi_workspace_name` - (String) Workspace name. + - `pi_workspace_status` - (String) Workspace status, `active`, `critical`, `failed`, `provisioning`. + - `pi_workspace_type` - (String) Workspace type, `off-premises` or `on-premises`. From 9d2f3ae15012aaab41b8f5ab773eeda7889934b5 Mon Sep 17 00:00:00 2001 From: Pankaj Kumar Date: Thu, 14 Dec 2023 10:12:05 +0530 Subject: [PATCH 21/34] Event Notifications: enabled private endpoint --- ibm/conns/config.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ibm/conns/config.go b/ibm/conns/config.go index c2fc691288..7b9a05a556 100644 --- a/ibm/conns/config.go +++ b/ibm/conns/config.go @@ -1884,11 +1884,14 @@ func (c *Config) ClientSession() (interface{}, error) { }) } session.pushServiceClient = pnclient + // event notifications enurl := fmt.Sprintf("https://%s.event-notifications.cloud.ibm.com/event-notifications", c.Region) - if c.Visibility == "private" { - session.eventNotificationsApiClientErr = fmt.Errorf("Event Notifications Service does not support private endpoints") + + if c.Visibility == "private" || c.Visibility == "public-and-private" { + enurl = fmt.Sprintf("https://private.%s.event-notifications.cloud.ibm.com/event-notifications", c.Region) } + if fileMap != nil && c.Visibility != "public-and-private" { enurl = fileFallBack(fileMap, c.Visibility, "IBMCLOUD_EVENT_NOTIFICATIONS_API_ENDPOINT", c.Region, enurl) } From 30f2008eeb110fc8310f32275cb3423c586c46ec Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:32:52 +0530 Subject: [PATCH 22/34] Refactor spp placement group data source and documentation (#5101) * Refactor spp placement group data source and documentation * Pull ibm_ pi_constants.go from constant-refactor --- .../data_source_ibm_pi_spp_placement_group.go | 63 ++++++++-------- ..._source_ibm_pi_spp_placement_group_test.go | 9 ++- ...data_source_ibm_pi_spp_placement_groups.go | 71 ++++++++++--------- .../d/pi_spp_placement_group.html.markdown | 16 ++--- .../d/pi_spp_placement_groups.html.markdown | 14 ++-- 5 files changed, 83 insertions(+), 90 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_spp_placement_group.go b/ibm/service/power/data_source_ibm_pi_spp_placement_group.go index 5b6f632ae3..2985750318 100644 --- a/ibm/service/power/data_source_ibm_pi_spp_placement_group.go +++ b/ibm/service/power/data_source_ibm_pi_spp_placement_group.go @@ -6,60 +6,61 @@ package power import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPISPPPlacementGroup() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPISPPPlacementGroupRead, Schema: map[string]*schema.Schema{ - Arg_SPPPlacementGroupID: { - Type: schema.TypeString, - Required: true, - }, - - Attr_SPPPlacementGroupName: { - Type: schema.TypeString, - Computed: true, - }, - - Attr_SPPPlacementGroupPolicy: { - Type: schema.TypeString, - Computed: true, - }, - - helpers.PICloudInstanceId: { + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", + Required: true, Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, + }, + Arg_SPPPlacementGroupID: { + Description: "The ID of the shared processor pool placement group.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - Attr_SPPPlacementGroupMembers: { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, + // Attributes + Attr_Members: { + Computed: true, + Description: "List of shared processor pool IDs that are members of the placement group.", + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + }, + Attr_Name: { + Computed: true, + Description: "The name of the shared processor pool placement group.", + Type: schema.TypeString, + }, + Attr_Policy: { + Computed: true, + Description: "The value of the group's affinity policy. Valid values are affinity and anti-affinity.", + Type: schema.TypeString, }, }, } } func dataSourceIBMPISPPPlacementGroupRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) placementGroupID := d.Get(Arg_SPPPlacementGroupID).(string) - client := st.NewIBMPISPPPlacementGroupClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPISPPPlacementGroupClient(ctx, sess, cloudInstanceID) response, err := client.Get(placementGroupID) if err != nil || response == nil { @@ -67,9 +68,9 @@ func dataSourceIBMPISPPPlacementGroupRead(ctx context.Context, d *schema.Resourc } d.SetId(*response.ID) - d.Set(Attr_SPPPlacementGroupName, response.Name) - d.Set(Attr_SPPPlacementGroupPolicy, response.Policy) - d.Set(Attr_SPPPlacementGroupMembers, response.MemberSharedProcessorPools) + d.Set(Attr_Members, response.MemberSharedProcessorPools) + d.Set(Attr_Name, response.Name) + d.Set(Attr_Policy, response.Policy) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_spp_placement_group_test.go b/ibm/service/power/data_source_ibm_pi_spp_placement_group_test.go index a5f5d9d187..515a72b089 100644 --- a/ibm/service/power/data_source_ibm_pi_spp_placement_group_test.go +++ b/ibm/service/power/data_source_ibm_pi_spp_placement_group_test.go @@ -28,9 +28,8 @@ func TestAccIBMPISPPPlacementGroupDataSource_basic(t *testing.T) { func testAccCheckIBMPISPPPlacementGroupDataSourceConfig() string { return fmt.Sprintf(` -data "ibm_pi_spp_placement_group" "testacc_ds_spp_placement_group" { - pi_spp_placement_group_id = "%s" - pi_cloud_instance_id = "%s" -}`, acc.Pi_spp_placement_group_id, acc.Pi_cloud_instance_id) - + data "ibm_pi_spp_placement_group" "testacc_ds_spp_placement_group" { + pi_spp_placement_group_id = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_spp_placement_group_id, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_spp_placement_groups.go b/ibm/service/power/data_source_ibm_pi_spp_placement_groups.go index 8ac4d5d678..b75ab43e42 100644 --- a/ibm/service/power/data_source_ibm_pi_spp_placement_groups.go +++ b/ibm/service/power/data_source_ibm_pi_spp_placement_groups.go @@ -6,55 +6,56 @@ package power import ( "context" + "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" -) - -const ( - PISPPPlacementGroups = "spp_placement_groups" ) func DataSourceIBMPISPPPlacementGroups() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPISPPPlacementGroupsRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "PI cloud instance ID", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - PISPPPlacementGroups: { - Type: schema.TypeList, - Computed: true, + + // Attributes + Attr_SPPPlacementGroups: { + Computed: true, + Description: "List of all the shared processor pool placement groups.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - Attr_SPPPlacementGroupID: { - Type: schema.TypeString, - Computed: true, + Attr_Members: { + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Description: "The list of shared processor pool IDs that are members of the shared processor pool placement group.", + Type: schema.TypeList, }, - Attr_SPPPlacementGroupName: { - Type: schema.TypeString, - Computed: true, + Attr_Name: { + Computed: true, + Description: "User defined name for the shared processor pool placement group.", + Type: schema.TypeString, }, - Attr_SPPPlacementGroupMembers: { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, + Attr_Policy: { + Computed: true, + Description: "The value of the group's affinity policy. Valid values are affinity and anti-affinity.", + Type: schema.TypeString, }, - Attr_SPPPlacementGroupPolicy: { - Type: schema.TypeString, - Computed: true, + Attr_SPPPlacementGroupID: { + Computed: true, + Description: "The ID of the shared processor pool placement group.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, }, }, } @@ -66,9 +67,9 @@ func dataSourceIBMPISPPPlacementGroupsRead(ctx context.Context, d *schema.Resour return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) - client := st.NewIBMPISPPPlacementGroupClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPISPPPlacementGroupClient(ctx, sess, cloudInstanceID) groups, err := client.GetAll() if err != nil || groups == nil { return diag.Errorf("error fetching spp placement groups: %v", err) @@ -77,17 +78,17 @@ func dataSourceIBMPISPPPlacementGroupsRead(ctx context.Context, d *schema.Resour result := make([]map[string]interface{}, 0, len(groups.SppPlacementGroups)) for _, placementGroup := range groups.SppPlacementGroups { key := map[string]interface{}{ - Attr_SPPPlacementGroupID: placementGroup.ID, - Attr_SPPPlacementGroupName: placementGroup.Name, - Attr_SPPPlacementGroupMembers: placementGroup.MemberSharedProcessorPools, - Attr_SPPPlacementGroupPolicy: placementGroup.Policy, + Attr_Members: placementGroup.MemberSharedProcessorPools, + Attr_Name: placementGroup.Name, + Attr_Policy: placementGroup.Policy, + Attr_SPPPlacementGroupID: placementGroup.ID, } result = append(result, key) } var genID, _ = uuid.GenerateUUID() d.SetId(genID) - d.Set(PISPPPlacementGroups, result) + d.Set(Attr_SPPPlacementGroups, result) return nil } diff --git a/website/docs/d/pi_spp_placement_group.html.markdown b/website/docs/d/pi_spp_placement_group.html.markdown index 79af4c068e..b725105481 100644 --- a/website/docs/d/pi_spp_placement_group.html.markdown +++ b/website/docs/d/pi_spp_placement_group.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_spp_placement_group" @@ -11,7 +10,6 @@ description: |- Retrieve information about a shared processor pool placement group. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example Usage - ```terraform data "ibm_pi_spp_placement_group" "ds_placement_group" { pi_spp_placement_group_id = "my-spppg" @@ -20,20 +18,18 @@ data "ibm_pi_spp_placement_group" "ds_placement_group" { ``` **Notes** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - - Example usage: +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` +Example usage: ```terraform provider "ibm" { region = "lon" zone = "lon04" } ``` - ## Argument reference Review the argument references that you can specify for your data source. @@ -44,6 +40,6 @@ Review the argument references that you can specify for your data source. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. -- `members` - (List of strings) The list of shared processor pool IDs that are members of the placement group. +- `members` - (List) List of shared processor pool IDs that are members of the placement group. - `name` - (String) The name of the shared processor pool placement group. - `policy` - (String) The value of the group's affinity policy. Valid values are affinity and anti-affinity. diff --git a/website/docs/d/pi_spp_placement_groups.html.markdown b/website/docs/d/pi_spp_placement_groups.html.markdown index 61267fefb5..cc1503dd9f 100644 --- a/website/docs/d/pi_spp_placement_groups.html.markdown +++ b/website/docs/d/pi_spp_placement_groups.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_spp_placement_groups" @@ -11,7 +10,6 @@ description: |- Retrieve information about all shared processor pool placement groups. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_spp_placement_groups" "example" { pi_cloud_instance_id = "" @@ -19,14 +17,12 @@ data "ibm_pi_spp_placement_groups" "example" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -45,7 +41,7 @@ In addition to all argument reference list, you can access the following attribu - `spp_placement_groups` - (List) List of all the shared processor pool placement groups. Nested scheme for `spp_placement_groups`: + - `members` - (List) The list of shared processor pool IDs that are members of the shared processor pool placement group. - `name` - (String) User defined name for the shared processor pool placement group. - - `members` - (List of strings) The list of shared processor pool IDs that are members of the shared processor pool placement group. - `policy` - (String) The value of the group's affinity policy. Valid values are affinity and anti-affinity. - `spp_placement_group_id` - (String) The ID of the shared processor pool placement group. From 9fb09053ffa731ecc6858cf84e474eae335c4b54 Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:34:05 +0530 Subject: [PATCH 23/34] Refactor storage-system pool capacity data source and documentation (#5102) * Refactor storage-system pool capacity data source and documentation * Pull ibm_ pi_constants.go from constant-refactor * Arrange alphabetically * Replace bool with Boolean --- ...ata_source_ibm_pi_storage_pool_capacity.go | 63 ++++---- ...ta_source_ibm_pi_storage_pools_capacity.go | 94 +++++------ ...ata_source_ibm_pi_storage_type_capacity.go | 30 ++-- ...ta_source_ibm_pi_storage_types_capacity.go | 44 ++--- .../power/data_source_ibm_pi_system_pools.go | 151 ++++++++---------- .../docs/d/pi_storage_pool_capacity.markdown | 15 +- .../docs/d/pi_storage_pools_capacity.markdown | 12 +- website/docs/d/pi_system_pools.markdown | 59 ++++--- 8 files changed, 208 insertions(+), 260 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_storage_pool_capacity.go b/ibm/service/power/data_source_ibm_pi_storage_pool_capacity.go index 84500c05d0..004cffea82 100644 --- a/ibm/service/power/data_source_ibm_pi_storage_pool_capacity.go +++ b/ibm/service/power/data_source_ibm_pi_storage_pool_capacity.go @@ -6,58 +6,53 @@ package power import ( "context" "fmt" - "log" - st "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -const ( - PIPoolName = "pi_storage_pool" -) - func DataSourceIBMPIStoragePoolCapacity() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPIStoragePoolCapacityRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - PIPoolName: { - Type: schema.TypeString, + Arg_StoragePool: { + Description: "The storage pool name.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, - Description: "Storage pool name", }, - // Computed Attributes - MaxAllocationSize: { - Type: schema.TypeInt, + + // Attributes + Attr_MaxAllocationSize: { Computed: true, - Description: "Maximum allocation storage size (GB)", + Description: "Maximum allocation storage size (GB).", + Type: schema.TypeInt, }, - StorageType: { - Type: schema.TypeString, + Attr_ReplicationEnabled: { Computed: true, - Description: "Storage type of the storage pool", + Description: "Replication status of the storage pool.", + Type: schema.TypeBool, }, - TotalCapacity: { - Type: schema.TypeInt, + Attr_StorageType: { Computed: true, - Description: "Total pool capacity (GB)", + Description: "Storage type of the storage pool.", + Type: schema.TypeString, }, - ReplicationEnabled: { - Type: schema.TypeBool, + Attr_TotalCapacity: { Computed: true, - Description: "Replication status of the storage pool", + Description: "Total pool capacity (GB).", + Type: schema.TypeInt, }, }, } @@ -69,10 +64,10 @@ func dataSourceIBMPIStoragePoolCapacityRead(ctx context.Context, d *schema.Resou return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - storagePool := d.Get(PIPoolName).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + storagePool := d.Get(Arg_StoragePool).(string) - client := st.NewIBMPIStorageCapacityClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPIStorageCapacityClient(ctx, sess, cloudInstanceID) sp, err := client.GetStoragePoolCapacity(storagePool) if err != nil { log.Printf("[ERROR] get storage pool capacity failed %v", err) @@ -80,9 +75,9 @@ func dataSourceIBMPIStoragePoolCapacityRead(ctx context.Context, d *schema.Resou } d.SetId(fmt.Sprintf("%s/%s", cloudInstanceID, storagePool)) - d.Set(MaxAllocationSize, *sp.MaxAllocationSize) - d.Set(StorageType, sp.StorageType) - d.Set(TotalCapacity, sp.TotalCapacity) - d.Set(ReplicationEnabled, *sp.ReplicationEnabled) + d.Set(Attr_MaxAllocationSize, *sp.MaxAllocationSize) + d.Set(Attr_ReplicationEnabled, *sp.ReplicationEnabled) + d.Set(Attr_StorageType, sp.StorageType) + d.Set(Attr_TotalCapacity, sp.TotalCapacity) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_storage_pools_capacity.go b/ibm/service/power/data_source_ibm_pi_storage_pools_capacity.go index 4e64ec5209..6c5ac36fd4 100644 --- a/ibm/service/power/data_source_ibm_pi_storage_pools_capacity.go +++ b/ibm/service/power/data_source_ibm_pi_storage_pools_capacity.go @@ -5,95 +5,82 @@ package power import ( "context" - "log" - st "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" - - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -const ( - MaximumStorageAllocation = "maximum_storage_allocation" - StoragePoolsCapacity = "storage_pools_capacity" - MaxAllocationSize = "max_allocation_size" - PoolName = "pool_name" - StoragePool = "storage_pool" - StorageType = "storage_type" - TotalCapacity = "total_capacity" - ReplicationEnabled = "replication_enabled" -) - func DataSourceIBMPIStoragePoolsCapacity() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPIStoragePoolsCapacityRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - MaximumStorageAllocation: { - Type: schema.TypeMap, + + // Attributes + Attr_MaximumStorageAllocation: { Computed: true, - Description: "Maximum storage allocation", + Description: "Maximum storage allocation.", + Type: schema.TypeMap, }, - StoragePoolsCapacity: { - Type: schema.TypeList, + Attr_StoragePoolsCapacity: { Computed: true, - Description: "Storage pools capacity", + Description: "List of storage pools capacity.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - MaxAllocationSize: { - Type: schema.TypeInt, + Attr_MaxAllocationSize: { Computed: true, - Description: "Maximum allocation storage size (GB)", + Description: "Maximum allocation storage size (GB).", + Type: schema.TypeInt, }, - PoolName: { - Type: schema.TypeString, + Attr_PoolName: { Computed: true, - Description: "Pool name", - }, - StorageType: { + Description: "The pool name.", Type: schema.TypeString, + }, + Attr_ReplicationEnabled: { Computed: true, - Description: "Storage type of the storage pool", + Description: "Replication status of the storage pool.", + Type: schema.TypeBool, }, - TotalCapacity: { - Type: schema.TypeInt, + Attr_StorageType: { Computed: true, - Description: "Total pool capacity (GB)", + Description: "Storage type of the storage pool.", + Type: schema.TypeString, }, - ReplicationEnabled: { - Type: schema.TypeBool, + Attr_TotalCapacity: { Computed: true, - Description: "Replication status of the storage pool", + Description: "Total pool capacity (GB).", + Type: schema.TypeInt, }, }, }, + Type: schema.TypeList, }, }, } } func dataSourceIBMPIStoragePoolsCapacityRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) - client := st.NewIBMPIStorageCapacityClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPIStorageCapacityClient(ctx, sess, cloudInstanceID) spc, err := client.GetAllStoragePoolsCapacity() if err != nil { log.Printf("[ERROR] get all storage pools capacity failed %v", err) @@ -106,26 +93,25 @@ func dataSourceIBMPIStoragePoolsCapacityRead(ctx context.Context, d *schema.Reso if spc.MaximumStorageAllocation != nil { msa := spc.MaximumStorageAllocation data := map[string]interface{}{ - MaxAllocationSize: *msa.MaxAllocationSize, - StoragePool: *msa.StoragePool, - StorageType: *msa.StorageType, + Attr_MaxAllocationSize: *msa.MaxAllocationSize, + Attr_StoragePool: *msa.StoragePool, + Attr_StorageType: *msa.StorageType, } - d.Set(MaximumStorageAllocation, flex.Flatten(data)) + d.Set(Attr_MaximumStorageAllocation, flex.Flatten(data)) } result := make([]map[string]interface{}, 0, len(spc.StoragePoolsCapacity)) for _, sp := range spc.StoragePoolsCapacity { data := map[string]interface{}{ - MaxAllocationSize: *sp.MaxAllocationSize, - PoolName: sp.PoolName, - StorageType: sp.StorageType, - TotalCapacity: sp.TotalCapacity, - ReplicationEnabled: *sp.ReplicationEnabled, + Attr_MaxAllocationSize: *sp.MaxAllocationSize, + Attr_PoolName: sp.PoolName, + Attr_ReplicationEnabled: *sp.ReplicationEnabled, + Attr_StorageType: sp.StorageType, + Attr_TotalCapacity: sp.TotalCapacity, } - result = append(result, data) } - d.Set(StoragePoolsCapacity, result) + d.Set(Attr_StoragePoolsCapacity, result) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_storage_type_capacity.go b/ibm/service/power/data_source_ibm_pi_storage_type_capacity.go index d33d338ff1..6fa01bab6c 100644 --- a/ibm/service/power/data_source_ibm_pi_storage_type_capacity.go +++ b/ibm/service/power/data_source_ibm_pi_storage_type_capacity.go @@ -40,33 +40,33 @@ func DataSourceIBMPIStorageTypeCapacity() *schema.Resource { Description: "Storage type name", }, // Computed Attributes - MaximumStorageAllocation: { + Attr_MaximumStorageAllocation: { Type: schema.TypeMap, Computed: true, Description: "Maximum storage allocation", }, - StoragePoolsCapacity: { + Attr_StoragePoolsCapacity: { Type: schema.TypeList, Computed: true, Description: "Storage pools capacity", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - MaxAllocationSize: { + Attr_MaxAllocationSize: { Type: schema.TypeInt, Computed: true, Description: "Maximum allocation storage size (GB)", }, - PoolName: { + Attr_PoolName: { Type: schema.TypeString, Computed: true, Description: "Pool name", }, - StorageType: { + Attr_StorageType: { Type: schema.TypeString, Computed: true, Description: "Storage type of the storage pool", }, - TotalCapacity: { + Attr_TotalCapacity: { Type: schema.TypeInt, Computed: true, Description: "Total pool capacity (GB)", @@ -99,24 +99,24 @@ func dataSourceIBMPIStorageTypeCapacityRead(ctx context.Context, d *schema.Resou if stc.MaximumStorageAllocation != nil { msa := stc.MaximumStorageAllocation data := map[string]interface{}{ - MaxAllocationSize: *msa.MaxAllocationSize, - StoragePool: *msa.StoragePool, - StorageType: *msa.StorageType, + Attr_MaxAllocationSize: *msa.MaxAllocationSize, + Attr_StoragePool: *msa.StoragePool, + Attr_StorageType: *msa.StorageType, } - d.Set(MaximumStorageAllocation, flex.Flatten(data)) + d.Set(Attr_MaximumStorageAllocation, flex.Flatten(data)) } result := make([]map[string]interface{}, 0, len(stc.StoragePoolsCapacity)) for _, sp := range stc.StoragePoolsCapacity { data := map[string]interface{}{ - MaxAllocationSize: *sp.MaxAllocationSize, - PoolName: sp.PoolName, - StorageType: sp.StorageType, - TotalCapacity: sp.TotalCapacity, + Attr_MaxAllocationSize: *sp.MaxAllocationSize, + Attr_PoolName: sp.PoolName, + Attr_StorageType: sp.StorageType, + Attr_TotalCapacity: sp.TotalCapacity, } result = append(result, data) } - d.Set(StoragePoolsCapacity, result) + d.Set(Attr_StoragePoolsCapacity, result) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_storage_types_capacity.go b/ibm/service/power/data_source_ibm_pi_storage_types_capacity.go index 59feb27952..5f3f169dbe 100644 --- a/ibm/service/power/data_source_ibm_pi_storage_types_capacity.go +++ b/ibm/service/power/data_source_ibm_pi_storage_types_capacity.go @@ -34,7 +34,7 @@ func DataSourceIBMPIStorageTypesCapacity() *schema.Resource { ValidateFunc: validation.NoZeroValues, }, // Computed Attributes - MaximumStorageAllocation: { + Attr_MaximumStorageAllocation: { Type: schema.TypeMap, Computed: true, Description: "Maximum storage allocation", @@ -45,33 +45,33 @@ func DataSourceIBMPIStorageTypesCapacity() *schema.Resource { Description: "Storage types capacity", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - MaximumStorageAllocation: { + Attr_MaximumStorageAllocation: { Type: schema.TypeMap, Computed: true, Description: "Maximum storage allocation", }, - StoragePoolsCapacity: { + Attr_StoragePoolsCapacity: { Type: schema.TypeList, Computed: true, Description: "Storage pools capacity", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - MaxAllocationSize: { + Attr_MaxAllocationSize: { Type: schema.TypeInt, Computed: true, Description: "Maximum allocation storage size (GB)", }, - PoolName: { + Attr_PoolName: { Type: schema.TypeString, Computed: true, Description: "Pool name", }, - StorageType: { + Attr_StorageType: { Type: schema.TypeString, Computed: true, Description: "Storage type of the storage pool", }, - TotalCapacity: { + Attr_TotalCapacity: { Type: schema.TypeInt, Computed: true, Description: "Total pool capacity (GB)", @@ -79,7 +79,7 @@ func DataSourceIBMPIStorageTypesCapacity() *schema.Resource { }, }, }, - StorageType: { + Attr_StorageType: { Type: schema.TypeString, Computed: true, Description: "The storage type", @@ -112,11 +112,11 @@ func dataSourceIBMPIStorageTypesCapacityRead(ctx context.Context, d *schema.Reso if stc.MaximumStorageAllocation != nil { msa := stc.MaximumStorageAllocation data := map[string]interface{}{ - MaxAllocationSize: *msa.MaxAllocationSize, - StoragePool: *msa.StoragePool, - StorageType: *msa.StorageType, + Attr_MaxAllocationSize: *msa.MaxAllocationSize, + Attr_StoragePool: *msa.StoragePool, + Attr_StorageType: *msa.StorageType, } - d.Set(MaximumStorageAllocation, flex.Flatten(data)) + d.Set(Attr_MaximumStorageAllocation, flex.Flatten(data)) } stcResult := make([]map[string]interface{}, 0, len(stc.StorageTypesCapacity)) for _, st := range stc.StorageTypesCapacity { @@ -124,24 +124,24 @@ func dataSourceIBMPIStorageTypesCapacityRead(ctx context.Context, d *schema.Reso if st.MaximumStorageAllocation != nil { msa := st.MaximumStorageAllocation data := map[string]interface{}{ - MaxAllocationSize: *msa.MaxAllocationSize, - StoragePool: *msa.StoragePool, - StorageType: *msa.StorageType, + Attr_MaxAllocationSize: *msa.MaxAllocationSize, + Attr_StoragePool: *msa.StoragePool, + Attr_StorageType: *msa.StorageType, } - stResult[MaximumStorageAllocation] = flex.Flatten(data) + stResult[Attr_MaximumStorageAllocation] = flex.Flatten(data) } spc := make([]map[string]interface{}, 0, len(st.StoragePoolsCapacity)) for _, sp := range st.StoragePoolsCapacity { data := map[string]interface{}{ - MaxAllocationSize: *sp.MaxAllocationSize, - PoolName: sp.PoolName, - StorageType: sp.StorageType, - TotalCapacity: sp.TotalCapacity, + Attr_MaxAllocationSize: *sp.MaxAllocationSize, + Attr_PoolName: sp.PoolName, + Attr_StorageType: sp.StorageType, + Attr_TotalCapacity: sp.TotalCapacity, } spc = append(spc, data) } - stResult[StoragePoolsCapacity] = spc - stResult[StorageType] = st.StorageType + stResult[Attr_StoragePoolsCapacity] = spc + stResult[Attr_StorageType] = st.StorageType stcResult = append(stcResult, stResult) } diff --git a/ibm/service/power/data_source_ibm_pi_system_pools.go b/ibm/service/power/data_source_ibm_pi_system_pools.go index 7e2f52b633..f1664e0bc6 100644 --- a/ibm/service/power/data_source_ibm_pi_system_pools.go +++ b/ibm/service/power/data_source_ibm_pi_system_pools.go @@ -5,121 +5,100 @@ package power import ( "context" - "log" - st "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" - - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -const ( - SystemPoolName = "system_pool_name" - SystemPools = "system_pools" - SystemPool = "system_pool" - Capacity = "capacity" - CoreMemoryRatio = "core_memory_ratio" - MaxAvailable = "max_available" - MaxCoresAvailable = "max_cores_available" - MaxMemoryAvailable = "max_memory_available" - SharedCoreRatio = "shared_core_ratio" - Type = "type" - Systems = "systems" - Cores = "cores" - ID = "id" - Memory = "memory" - Default = "default" - Max = "max" - Min = "min" -) - func DataSourceIBMPISystemPools() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPISystemPoolsRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - SystemPools: { + + // Attributes + Attr_SystemPools: { Type: schema.TypeList, Computed: true, - Description: "List of available system pools within a particular DataCenter", + Description: "List of available system pools within a particular Datacenter.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - SystemPoolName: { - Type: schema.TypeString, + Attr_Capacity: { Computed: true, - Description: "The system pool name", - }, - Capacity: { + Description: "Advertised capacity cores and memory (GB).", Type: schema.TypeMap, - Computed: true, - Description: "Advertised capacity cores and memory (GB)", }, - CoreMemoryRatio: { - Type: schema.TypeFloat, + Attr_CoreMemoryRatio: { Computed: true, - Description: "Processor to Memory (GB) Ratio", + Description: "Processor to Memory (GB) Ratio.", + Type: schema.TypeFloat, }, - MaxAvailable: { - Type: schema.TypeMap, + Attr_MaxAvailable: { Computed: true, - Description: "Maximum configurable cores and memory (GB) (aggregated from all hosts)", - }, - MaxCoresAvailable: { + Description: "Maximum configurable cores and memory (GB) (aggregated from all hosts).", Type: schema.TypeMap, - Computed: true, - Description: "Maximum configurable cores available combined with available memory of that host", }, - MaxMemoryAvailable: { + Attr_MaxCoresAvailable: { + Computed: true, + Description: "Maximum configurable cores available combined with available memory of that host.", Type: schema.TypeMap, + }, + Attr_MaxMemoryAvailable: { Computed: true, - Description: "Maximum configurable memory available combined with available cores of that host", + Description: "Maximum configurable memory available combined with available cores of that host.", + Type: schema.TypeMap, }, - SharedCoreRatio: { + Attr_SharedCoreRatio: { + Computed: true, + Description: "The min-max-default allocation percentage of shared core per vCPU.", Type: schema.TypeMap, + }, + Attr_SystemPoolName: { Computed: true, - Description: "The min-max-default allocation percentage of shared core per vCPU", + Description: "The system pool name", + Type: schema.TypeString, }, - Systems: { - Type: schema.TypeList, + Attr_Systems: { Computed: true, - Description: "The DataCenter list of servers and their available resources", + Description: "The Datacenter list of servers and their available resources.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - Cores: { - Type: schema.TypeString, + Attr_Cores: { Computed: true, - Description: "The host available Processor units", - }, - ID: { + Description: "The host available Processor units.", Type: schema.TypeString, - Computed: true, - Description: "The host identifier", }, - Memory: { + Attr_ID: { + Computed: true, + Description: "The host identifier.", Type: schema.TypeString, + }, + Attr_Memory: { Computed: true, - Description: "The host available RAM memory in GiB", + Description: "The host available RAM memory in GiB.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, }, - Type: { - Type: schema.TypeString, + Attr_Type: { Computed: true, - Description: "Type of system hardware", + Description: "Type of system hardware.", + Type: schema.TypeString, }, }, }, @@ -134,9 +113,9 @@ func dataSourceIBMPISystemPoolsRead(ctx context.Context, d *schema.ResourceData, return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) - client := st.NewIBMPISystemPoolClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPISystemPoolClient(ctx, sess, cloudInstanceID) sps, err := client.GetSystemPools() if err != nil { log.Printf("[ERROR] get system pools capacity failed %v", err) @@ -149,37 +128,37 @@ func dataSourceIBMPISystemPoolsRead(ctx context.Context, d *schema.ResourceData, result := make([]map[string]interface{}, 0, len(sps)) for s, sp := range sps { data := map[string]interface{}{ - SystemPoolName: s, - Capacity: flattenMax(sp.Capacity), - CoreMemoryRatio: sp.CoreMemoryRatio, - MaxAvailable: flattenMax(sp.MaxAvailable), - MaxCoresAvailable: flattenMax(sp.MaxCoresAvailable), - MaxMemoryAvailable: flattenMax(sp.MaxMemoryAvailable), - SharedCoreRatio: flattenSharedCoreRatio(sp.SharedCoreRatio), - Type: sp.Type, - Systems: flattenSystems(sp.Systems), + Attr_SystemPoolName: s, + Attr_Capacity: flattenMax(sp.Capacity), + Attr_CoreMemoryRatio: sp.CoreMemoryRatio, + Attr_MaxAvailable: flattenMax(sp.MaxAvailable), + Attr_MaxCoresAvailable: flattenMax(sp.MaxCoresAvailable), + Attr_MaxMemoryAvailable: flattenMax(sp.MaxMemoryAvailable), + Attr_SharedCoreRatio: flattenSharedCoreRatio(sp.SharedCoreRatio), + Attr_Type: sp.Type, + Attr_Systems: flattenSystems(sp.Systems), } result = append(result, data) } - d.Set(SystemPools, result) + d.Set(Attr_SystemPools, result) return nil } func flattenMax(s *models.System) map[string]string { ret := map[string]interface{}{ - Cores: *s.Cores, - Memory: *s.Memory, + Attr_Cores: *s.Cores, + Attr_Memory: *s.Memory, } return flex.Flatten(ret) } func flattenSystem(s *models.System) map[string]string { ret := map[string]interface{}{ - Cores: *s.Cores, - ID: s.ID, - Memory: *s.Memory, + Attr_Cores: *s.Cores, + Attr_ID: s.ID, + Attr_Memory: *s.Memory, } return flex.Flatten(ret) } @@ -197,9 +176,9 @@ func flattenSystems(sl []*models.System) (systems []map[string]string) { func flattenSharedCoreRatio(scr *models.MinMaxDefault) map[string]string { ret := map[string]interface{}{ - Default: scr.Default, - Max: scr.Max, - Min: scr.Min, + Attr_Default: scr.Default, + Attr_Max: scr.Max, + Attr_Min: scr.Min, } return flex.Flatten(ret) } diff --git a/website/docs/d/pi_storage_pool_capacity.markdown b/website/docs/d/pi_storage_pool_capacity.markdown index a38e01eb79..caa5550c16 100644 --- a/website/docs/d/pi_storage_pool_capacity.markdown +++ b/website/docs/d/pi_storage_pool_capacity.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_storage_pool_capacity" @@ -11,7 +10,6 @@ description: |- Retrieve information about storages capacity for a storage pool in a region. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_storage_pool_capacity" "pool" { pi_cloud_instance_id = "" @@ -20,14 +18,12 @@ data "ibm_pi_storage_pool_capacity" "pool" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -45,6 +41,7 @@ Review the argument references that you can specify for your data source. In addition to all argument reference list, you can access the following attribute references after your data source is created. - `max_allocation_size` - (Integer) Maximum allocation storage size (GB). +- `replication_enabled` - (Boolean) Replication status of the storage pool. - `storage_type` - (String) Storage type of the storage pool. - `total_capacity` - (Integer) Total pool capacity (GB). -- `replication_enabled` - (Boolean) Replication status of the storage pool. + diff --git a/website/docs/d/pi_storage_pools_capacity.markdown b/website/docs/d/pi_storage_pools_capacity.markdown index f85cecb0d3..0a20832207 100644 --- a/website/docs/d/pi_storage_pools_capacity.markdown +++ b/website/docs/d/pi_storage_pools_capacity.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_storage_pools_capacity" @@ -11,7 +10,6 @@ description: |- Retrieve information about storages capacity for all available storage pools in a region. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_storage_pools_capacity" "pools" { pi_cloud_instance_id = "" @@ -19,14 +17,12 @@ data "ibm_pi_storage_pools_capacity" "pools" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" diff --git a/website/docs/d/pi_system_pools.markdown b/website/docs/d/pi_system_pools.markdown index 28ce84b76d..09cb154c97 100644 --- a/website/docs/d/pi_system_pools.markdown +++ b/website/docs/d/pi_system_pools.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_system_pools" @@ -11,7 +10,6 @@ description: |- Retrieve information about list of system pools within a particular data center. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_system_pools" "pools" { pi_cloud_instance_id = "" @@ -19,14 +17,12 @@ data "ibm_pi_system_pools" "pools" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -42,47 +38,46 @@ Review the argument references that you can specify for your data source. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. -- `system_pools` - (List) The available system pools within a particular DataCenter. +- `system_pools` - (List) List of available system pools within a particular Datacenter. Nested scheme for `system_pools`: - - `system_pool_name` - (String) The system pool name. - `capacity` - (Map) Advertised capacity cores and memory (GB). - Nested scheme for `capacity`: - - `cores` - (String) The host available Processor units. - - `memory`- (String) The host available RAM memory in GiB. + Nested scheme for `capacity`: + - `cores` - (String) The host available Processor units. + - `memory`- (String) The host available RAM memory in GiB. - `core_memory_ratio` - (Float) Processor to Memory (GB) Ratio. - `max_available` - (Map) Maximum configurable cores and memory (GB) (aggregated from all hosts). - Nested scheme for `max_available`: - - `cores` - (String) The host available Processor units. - - `memory`- (String) The host available RAM memory in GiB. + Nested scheme for `max_available`: + - `cores` - (String) The host available Processor units. + - `memory`- (String) The host available RAM memory in GiB. - `max_cores_available` - (Map) Maximum configurable cores available combined with available memory of that host. - Nested scheme for `max_cores_available`: - - `cores` - (String) The host available Processor units. - - `memory`- (String) The host available RAM memory in GiB. + Nested scheme for `max_cores_available`: + - `cores` - (String) The host available Processor units. + - `memory`- (String) The host available RAM memory in GiB. - `max_memory_available` - (Map) Maximum configurable memory available combined with available cores of that host. - Nested scheme for `max_memory_available`: - - `cores` - (String) The host available Processor units. - - `memory`- (String) The host available RAM memory in GiB. + Nested scheme for `max_memory_available`: + - `cores` - (String) The host available Processor units. + - `memory`- (String) The host available RAM memory in GiB. - `shared_core_ratio` - (Map) The min-max-default allocation percentage of shared core per vCPU. - Nested scheme for `shared_core_ratio`: - - `default` - (String) The default value. - - `max` - (String) The max value. - - `min`- (String) The min value. - - - `systems` - (List) The DataCenter list of servers and their available resources. + Nested scheme for `shared_core_ratio`: + - `default` - (String) The default value. + - `max` - (String) The max value. + - `min`- (String) The min value. + - `system_pool_name` - (String) The system pool name. + - `systems` - (List) The Datacenter list of servers and their available resources. - Nested scheme for `systems`: - - `cores` - (String) The host available Processor units. - - `id` - (String) The host identifier. - - `memory`- (String) The host available RAM memory in GiB. + Nested scheme for `systems`: + - `cores` - (String) The host available Processor units. + - `id` - (String) The host identifier. + - `memory`- (String) The host available RAM memory in GiB. - `type` - (String) Type of system hardware. From a616e0f72c54c6461998a4b287b44853124c448e Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:34:21 +0530 Subject: [PATCH 24/34] Refactor public-network-pvm-instance-snapshot data source and documentation (#5100) * Refactor public-network-pvm-instance-snapshot data source and documentation * Pull ibm_ pi_constants.go from constant-refactor * Remove space from a line * Update website/docs/d/pi_public_network.html.markdown Co-authored-by: Yussuf Shaikh --------- Co-authored-by: ismirlia <90468712+ismirlia@users.noreply.github.com> Co-authored-by: Yussuf Shaikh --- .../data_source_ibm_pi_public_network.go | 49 ++++---- .../data_source_ibm_pi_public_network_test.go | 7 +- .../power/data_source_ibm_pi_snapshot.go | 113 +++++++++--------- .../power/data_source_ibm_pi_snapshot_test.go | 10 +- .../power/data_source_ibm_pi_snapshots.go | 106 ++++++++-------- .../data_source_ibm_pi_snapshots_test.go | 9 +- .../d/pi_instance_snapshots.html.markdown | 23 ++-- .../docs/d/pi_public_network.html.markdown | 18 ++- website/docs/d/pi_pvm_snapshots.html.markdown | 23 ++-- 9 files changed, 177 insertions(+), 181 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_public_network.go b/ibm/service/power/data_source_ibm_pi_public_network.go index ca5cc380e2..ef8195c964 100644 --- a/ibm/service/power/data_source_ibm_pi_public_network.go +++ b/ibm/service/power/data_source_ibm_pi_public_network.go @@ -4,41 +4,42 @@ package power import ( - //"fmt" "context" + "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - - "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" ) func DataSourceIBMPIPublicNetwork() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPIPublicNetworkRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - "name": { - Type: schema.TypeString, - Computed: true, + // Attributes + Attr_Name: { + Computed: true, + Description: "The name of the network.", + Type: schema.TypeString, }, - "type": { - Type: schema.TypeString, - Computed: true, + Attr_Type: { + Computed: true, + Description: "The type of VLAN that the network is connected to.", + Type: schema.TypeString, }, - "vlan_id": { - Type: schema.TypeInt, - Computed: true, + Attr_VLanID: { + Computed: true, + Description: "The ID of the VLAN that the network is connected to.", + Type: schema.TypeInt, }, }, } @@ -50,7 +51,7 @@ func dataSourceIBMPIPublicNetworkRead(ctx context.Context, d *schema.ResourceDat return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) networkC := instance.NewIBMPINetworkClient(ctx, sess, cloudInstanceID) networkdata, err := networkC.GetAllPublic() @@ -62,14 +63,14 @@ func dataSourceIBMPIPublicNetworkRead(ctx context.Context, d *schema.ResourceDat } d.SetId(*networkdata.Networks[0].NetworkID) - if networkdata.Networks[0].Type != nil { - d.Set("type", networkdata.Networks[0].Type) - } if networkdata.Networks[0].Name != nil { - d.Set("name", networkdata.Networks[0].Name) + d.Set(Attr_Name, networkdata.Networks[0].Name) + } + if networkdata.Networks[0].Type != nil { + d.Set(Attr_Type, networkdata.Networks[0].Type) } if networkdata.Networks[0].VlanID != nil { - d.Set("vlan_id", networkdata.Networks[0].VlanID) + d.Set(Attr_VLanID, networkdata.Networks[0].VlanID) } return nil diff --git a/ibm/service/power/data_source_ibm_pi_public_network_test.go b/ibm/service/power/data_source_ibm_pi_public_network_test.go index f8c3eb1c5b..3ac39c13a6 100644 --- a/ibm/service/power/data_source_ibm_pi_public_network_test.go +++ b/ibm/service/power/data_source_ibm_pi_public_network_test.go @@ -29,8 +29,7 @@ func TestAccIBMPIPublicNetworkDataSource_basic(t *testing.T) { func testAccCheckIBMPIPublicNetworkDataSourceConfig() string { return fmt.Sprintf(` -data "ibm_pi_public_network" "testacc_ds_public_network" { - pi_cloud_instance_id = "%s" -}`, acc.Pi_cloud_instance_id) - + data "ibm_pi_public_network" "testacc_ds_public_network" { + pi_cloud_instance_id = "%s" + }`, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_snapshot.go b/ibm/service/power/data_source_ibm_pi_snapshot.go index b852f1024f..ad454cf521 100644 --- a/ibm/service/power/data_source_ibm_pi_snapshot.go +++ b/ibm/service/power/data_source_ibm_pi_snapshot.go @@ -8,7 +8,6 @@ import ( "log" "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" @@ -18,65 +17,73 @@ import ( ) func DataSourceIBMPISnapshot() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPISnapshotRead, Schema: map[string]*schema.Schema{ - - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - - helpers.PIInstanceName: { - Type: schema.TypeString, + Arg_InstanceName: { + Description: "The unique identifier or name of the instance.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - //Computed Attributes - "pvm_snapshots": { + // Attributes + Attr_PVMSnapshots: { Type: schema.TypeList, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, + Attr_Action: { + Computed: true, + Description: "Action performed on the instance snapshot.", + Type: schema.TypeString, }, - "name": { - Type: schema.TypeString, - Computed: true, + Attr_CreationDate: { + Computed: true, + Description: "Date of snapshot creation.", + Type: schema.TypeString, }, - "percent_complete": { - Type: schema.TypeInt, - Computed: true, + Attr_Description: { + Computed: true, + Description: "The description of the snapshot.", + Type: schema.TypeString, }, - - "description": { - Type: schema.TypeString, - Computed: true, + Attr_ID: { + Computed: true, + Description: "The unique identifier of the Power Virtual Machine instance snapshot.", + Type: schema.TypeString, }, - "action": { - Type: schema.TypeString, - Computed: true, + Attr_LastUpdatedDate: { + Computed: true, + Description: "Date of last update.", + Type: schema.TypeString, }, - "status": { - Type: schema.TypeString, - Computed: true, + Attr_Name: { + Computed: true, + Description: "The name of the Power Virtual Machine instance snapshot.", + Type: schema.TypeString, }, - "creation_date": { - Type: schema.TypeString, - Computed: true, + Attr_PercentComplete: { + Computed: true, + Description: "The snapshot completion percentage.", + Type: schema.TypeInt, }, - "last_updated_date": { - Type: schema.TypeString, - Computed: true, + Attr_Status: { + Computed: true, + Description: "The status of the Power Virtual Machine instance snapshot.", + Type: schema.TypeString, }, - "volume_snapshots": { - Type: schema.TypeMap, - Computed: true, + Attr_VolumeSnapshots: { + Computed: true, + Description: "A map of volume snapshots included in the Power Virtual Machine instance snapshot.", + Type: schema.TypeMap, }, }, }, @@ -86,14 +93,13 @@ func DataSourceIBMPISnapshot() *schema.Resource { } func dataSourceIBMPISnapshotRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - powerinstancename := d.Get(helpers.PIInstanceName).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + powerinstancename := d.Get(Arg_InstanceName).(string) snapshot := instance.NewIBMPIInstanceClient(ctx, sess, cloudInstanceID) snapshotData, err := snapshot.GetSnapShotVM(powerinstancename) @@ -103,30 +109,27 @@ func dataSourceIBMPISnapshotRead(ctx context.Context, d *schema.ResourceData, me var clientgenU, _ = uuid.GenerateUUID() d.SetId(clientgenU) - d.Set("pvm_snapshots", flattenPVMSnapshotInstances(snapshotData.Snapshots)) + d.Set(Attr_PVMSnapshots, flattenPVMSnapshotInstances(snapshotData.Snapshots)) return nil - } func flattenPVMSnapshotInstances(list []*models.Snapshot) []map[string]interface{} { - log.Printf("Calling the flattensnapshotinstances call with list %d", len(list)) + log.Printf("Calling the flattenPVMSnapshotInstances call with list %d", len(list)) result := make([]map[string]interface{}, 0, len(list)) for _, i := range list { l := map[string]interface{}{ - "id": *i.SnapshotID, - "name": *i.Name, - "description": i.Description, - "creation_date": i.CreationDate.String(), - "last_updated_date": i.LastUpdateDate.String(), - "action": i.Action, - "percent_complete": i.PercentComplete, - "status": i.Status, - "volume_snapshots": i.VolumeSnapshots, + Attr_Action: i.Action, + Attr_CreationDate: i.CreationDate.String(), + Attr_Description: i.Description, + Attr_ID: *i.SnapshotID, + Attr_LastUpdatedDate: i.LastUpdateDate.String(), + Attr_Name: *i.Name, + Attr_PercentComplete: i.PercentComplete, + Attr_Status: i.Status, + Attr_VolumeSnapshots: i.VolumeSnapshots, } - result = append(result, l) } - return result } diff --git a/ibm/service/power/data_source_ibm_pi_snapshot_test.go b/ibm/service/power/data_source_ibm_pi_snapshot_test.go index 3636fbf048..e5c502c1cb 100644 --- a/ibm/service/power/data_source_ibm_pi_snapshot_test.go +++ b/ibm/service/power/data_source_ibm_pi_snapshot_test.go @@ -29,10 +29,8 @@ func TestAccIBMPISnapshotDataSource_basic(t *testing.T) { func testAccCheckIBMPISnapshotDataSourceConfig() string { return fmt.Sprintf(` - -data "ibm_pi_pvm_snapshots" "testacc_pi_snapshots" { - pi_instance_name = "%s" - pi_cloud_instance_id = "%s" -}`, acc.Pi_instance_name, acc.Pi_cloud_instance_id) - + data "ibm_pi_pvm_snapshots" "testacc_pi_snapshots" { + pi_instance_name = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_instance_name, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_snapshots.go b/ibm/service/power/data_source_ibm_pi_snapshots.go index 273c0fcef8..6e2ea76e34 100644 --- a/ibm/service/power/data_source_ibm_pi_snapshots.go +++ b/ibm/service/power/data_source_ibm_pi_snapshots.go @@ -8,7 +8,6 @@ import ( "log" "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" @@ -18,60 +17,71 @@ import ( ) func DataSourceIBMPISnapshots() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPISnapshotsRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - //Computed Attributes - "instance_snapshots": { - Type: schema.TypeList, - Computed: true, + // Attributes + Attr_InstanceSnapshots: { + Computed: true, + Description: "List of Power Virtual Machine instance snapshots within the given cloud instance.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, + Attr_Action: { + Computed: true, + Description: "Action performed on the instance snapshot.", + Type: schema.TypeString, }, - "name": { - Type: schema.TypeString, - Computed: true, + Attr_CreationDate: { + Computed: true, + Description: "Date of snapshot creation.", + Type: schema.TypeString, }, - "percent_complete": { - Type: schema.TypeInt, - Computed: true, + Attr_Description: { + Computed: true, + Description: "The description of the snapshot.", + Type: schema.TypeString, }, - "description": { - Type: schema.TypeString, - Computed: true, + Attr_ID: { + Computed: true, + Description: "The unique identifier of the Power Systems Virtual Machine instance snapshot.", + Type: schema.TypeString, }, - "action": { - Type: schema.TypeString, - Computed: true, + Attr_LastUpdatedDate: { + Computed: true, + Description: "Date of last update.", + Type: schema.TypeString, }, - "status": { - Type: schema.TypeString, - Computed: true, + Attr_Name: { + Computed: true, + Description: "The name of the Power Systems Virtual Machine instance snapshot.", + Type: schema.TypeString, }, - "creation_date": { - Type: schema.TypeString, - Computed: true, + Attr_PercentComplete: { + Computed: true, + Description: "The snapshot completion percentage.", + Type: schema.TypeInt, }, - "last_updated_date": { - Type: schema.TypeString, - Computed: true, + Attr_Status: { + Computed: true, + Description: "The status of the Power Virtual Machine instance snapshot.", + Type: schema.TypeString, }, - "volume_snapshots": { - Type: schema.TypeMap, - Computed: true, + Attr_VolumeSnapshots: { + Computed: true, + Description: "A map of volume snapshots included in the Power Virtual Machine instance snapshot.", + Type: schema.TypeMap, }, }, }, + Type: schema.TypeList, }, }, } @@ -83,7 +93,7 @@ func dataSourceIBMPISnapshotsRead(ctx context.Context, d *schema.ResourceData, m return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) snapshot := instance.NewIBMPISnapshotClient(ctx, sess, cloudInstanceID) snapshotData, err := snapshot.GetAll() if err != nil { @@ -92,29 +102,27 @@ func dataSourceIBMPISnapshotsRead(ctx context.Context, d *schema.ResourceData, m var clientgenU, _ = uuid.GenerateUUID() d.SetId(clientgenU) - d.Set("instance_snapshots", flattenSnapshotsInstances(snapshotData.Snapshots)) + d.Set(Attr_InstanceSnapshots, flattenSnapshotsInstances(snapshotData.Snapshots)) return nil } func flattenSnapshotsInstances(list []*models.Snapshot) []map[string]interface{} { - log.Printf("Calling the flattensnapshotsinstances call with list %d", len(list)) + log.Printf("Calling the flattenSnapshotsInstances call with list %d", len(list)) result := make([]map[string]interface{}, 0, len(list)) for _, i := range list { l := map[string]interface{}{ - "id": *i.SnapshotID, - "name": *i.Name, - "description": i.Description, - "creation_date": i.CreationDate.String(), - "last_updated_date": i.LastUpdateDate.String(), - "action": i.Action, - "percent_complete": i.PercentComplete, - "status": i.Status, - "volume_snapshots": i.VolumeSnapshots, + Attr_Action: i.Action, + Attr_CreationDate: i.CreationDate.String(), + Attr_Description: i.Description, + Attr_ID: *i.SnapshotID, + Attr_LastUpdatedDate: i.LastUpdateDate.String(), + Attr_Name: *i.Name, + Attr_PercentComplete: i.PercentComplete, + Attr_Status: i.Status, + Attr_VolumeSnapshots: i.VolumeSnapshots, } - result = append(result, l) } - return result } diff --git a/ibm/service/power/data_source_ibm_pi_snapshots_test.go b/ibm/service/power/data_source_ibm_pi_snapshots_test.go index be8d385d8a..8494e0c9c7 100644 --- a/ibm/service/power/data_source_ibm_pi_snapshots_test.go +++ b/ibm/service/power/data_source_ibm_pi_snapshots_test.go @@ -13,7 +13,6 @@ import ( ) func TestAccIBMPISnapshotsDataSource_basic(t *testing.T) { - resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, Providers: acc.TestAccProviders, @@ -30,9 +29,7 @@ func TestAccIBMPISnapshotsDataSource_basic(t *testing.T) { func testAccCheckIBMPISnapshotsDataSourceConfig() string { return fmt.Sprintf(` - -data "ibm_pi_instance_snapshots" "testacc_ds_snapshots" { - pi_cloud_instance_id = "%s" -}`, acc.Pi_cloud_instance_id) - + data "ibm_pi_instance_snapshots" "testacc_ds_snapshots" { + pi_cloud_instance_id = "%s" + }`, acc.Pi_cloud_instance_id) } diff --git a/website/docs/d/pi_instance_snapshots.html.markdown b/website/docs/d/pi_instance_snapshots.html.markdown index cbe97e86f3..7d39c0d0d5 100644 --- a/website/docs/d/pi_instance_snapshots.html.markdown +++ b/website/docs/d/pi_instance_snapshots.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_instance_snapshots" @@ -11,21 +10,19 @@ description: |- Retrieve information about a Power Systems Virtual Server instance snapshots. For more information, about Power Virtual Server instance snapshots, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_instance_snapshots" "ds_instance_snapshots" { pi_cloud_instance_id = "49fba6c9-23f8-40bc-9899-aca322ee7d5b" } ``` -**Note** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` - Example usage: - +Example usage: ```terraform provider "ibm" { region = "lon" @@ -41,15 +38,15 @@ Review the argument references that you can specify for your data source. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. -- `instance_snapshots` - The list of Power Virtual Machine instance snapshots within the given cloud instance. +- `instance_snapshots` - (List) List of Power Virtual Machine instance snapshots within the given cloud instance. Nested scheme for `instance_snapshots`: - `action` - (String) Action performed on the instance snapshot. - - `creation_date` - (String) The creation date. + - `creation_date` - (String) Date of snapshot creation. - `description` - (String) The description of the snapshot. - `id` - (String) The unique identifier of the Power Systems Virtual Machine instance snapshot. - - `last_updated_date` - (String) The last Update Date. + - `last_updated_date` - (String) Date of last update. - `name` - (String) The name of the Power Systems Virtual Machine instance snapshot. - `percent_complete` - (Integer) The snapshot completion percentage. - `status` - (String) The status of the Power Virtual Machine instance snapshot. - - `volume_snapshots` - (Map) A map of volume snapshots included in the Power Virtual Machine instance snapshot. \ No newline at end of file + - `volume_snapshots` - (Map) A map of volume snapshots included in the Power Virtual Machine instance snapshot. diff --git a/website/docs/d/pi_public_network.html.markdown b/website/docs/d/pi_public_network.html.markdown index 9c00c9d0a3..097d94ce6a 100644 --- a/website/docs/d/pi_public_network.html.markdown +++ b/website/docs/d/pi_public_network.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_public_network" @@ -8,32 +7,29 @@ description: |- --- # ibm_pi_public_network -Retrieve the details about a public network that is used for your Power Systems Virtual Server instance. For more information, about public network in IBM power virutal server, see [adding or removing a public network +Retrieve the details about a public network that is used for your Power Systems Virtual Server instance. For more information, about public network in IBM Power Systems Virtual Server, see [adding or removing a public network ](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-modifying-server#adding-removing-network). ## Example usage - ```terraform data "ibm_pi_public_network" "ds_public_network" { pi_cloud_instance_id = "49fba6c9-23f8-40bc-9899-aca322ee7d5b" } ``` -**Note** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - - Example usage: +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` +Example usage: ```terraform provider "ibm" { region = "lon" zone = "lon04" } ``` - ## Argument reference Review the argument references that you can specify for your data source. diff --git a/website/docs/d/pi_pvm_snapshots.html.markdown b/website/docs/d/pi_pvm_snapshots.html.markdown index 7a2eeaf5e5..3a5fa6571a 100644 --- a/website/docs/d/pi_pvm_snapshots.html.markdown +++ b/website/docs/d/pi_pvm_snapshots.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_pvm_snapshots" @@ -11,7 +10,6 @@ description: |- Retrieve information about a Power Systems Virtual Server instance snapshots. For more information, about Power Virtual Server PVM instance snapshots, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_pvm_snapshots" "ds_pvm_snapshots" { pi_instance_name = "terraform-test-instance" @@ -19,14 +17,13 @@ data "ibm_pi_pvm_snapshots" "ds_pvm_snapshots" { } ``` -**Note** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` - Example usage: - +Example usage: ```terraform provider "ibm" { region = "lon" @@ -37,8 +34,8 @@ data "ibm_pi_pvm_snapshots" "ds_pvm_snapshots" { ## Argument reference Review the argument references that you can specify for your data source. -- `pi_instance_name` - (Required, String) The name of the instance. - `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. +- `pi_instance_name` - (Required, String) The unique identifier or name of the instance. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. @@ -47,11 +44,11 @@ In addition to all argument reference list, you can access the following attribu Nested scheme for `pvm_snapshots`: - `action` - (String) Action performed on the instance snapshot. - - `creation_date` - (String) The creation date. + - `creation_date` - (String) Date of snapshot creation. - `description` - (String) The description of the snapshot. - `id` - (String) The unique identifier of the Power Virtual Machine instance snapshot. - - `last_updated_date` - (String) The last update date. + - `last_updated_date` - (String) Date of last update. - `name` - (String) The name of the Power Virtual Machine instance snapshot. - `percent_complete` - (Integer) The snapshot completion percentage. - `status` - (String) The status of the Power Virtual Machine instance snapshot. - - `volume_snapshots` - (Map) A map of volume snapshots included in the Power Virtual Machine instance snapshot. \ No newline at end of file + - `volume_snapshots` - (Map) A map of volume snapshots included in the Power Virtual Machine instance snapshot. From 04bd70ae6e480c0caf08c86c9d368e34be492641 Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:35:04 +0530 Subject: [PATCH 25/34] Refactor shared processor pool data source and documentation (#5099) * Refactor shared processor pool data source and documentation * Delete comment from ibm_ pi_constants.go * Pull ibm_ pi_constants.go from constant-refactor --- ...ata_source_ibm_pi_shared_processor_pool.go | 196 +++++++++--------- ...ource_ibm_pi_shared_processor_pool_test.go | 9 +- ...ta_source_ibm_pi_shared_processor_pools.go | 105 +++++----- ...urce_ibm_pi_shared_processor_pools_test.go | 3 +- .../d/pi_shared_processor_pool.html.markdown | 19 +- .../d/pi_shared_processor_pools.html.markdown | 14 +- 6 files changed, 168 insertions(+), 178 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_shared_processor_pool.go b/ibm/service/power/data_source_ibm_pi_shared_processor_pool.go index e3fcc1be34..b6c04c4f58 100644 --- a/ibm/service/power/data_source_ibm_pi_shared_processor_pool.go +++ b/ibm/service/power/data_source_ibm_pi_shared_processor_pool.go @@ -6,143 +6,137 @@ package power import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPISharedProcessorPool() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPISharedProcessorPoolRead, Schema: map[string]*schema.Schema{ - Arg_SharedProcessorPoolID: { - Type: schema.TypeString, - Required: true, - }, - + // Arguments Arg_CloudInstanceID: { - Type: schema.TypeString, - Required: true, - Description: "PI cloud instance ID", + Description: "The GUID of the service instance associated with an account.", + Required: true, + Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, }, - - Attr_SharedProcessorPoolName: { - Type: schema.TypeString, - Computed: true, - Description: "Name of the shared processor pool", - }, - - Attr_SharedProcessorPoolHostID: { - Type: schema.TypeInt, - Computed: true, - Description: "The host ID where the shared processor pool resides", - }, - - Attr_SharedProcessorPoolReservedCores: { - Type: schema.TypeInt, - Computed: true, - Description: "The amount of reserved cores for the shared processor pool", + Arg_SharedProcessorPoolID: { + Description: "The ID of the shared processor pool.", + Required: true, + Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, }, - Attr_SharedProcessorPoolAvailableCores: { - Type: schema.TypeFloat, + // Attributes + Attr_AllocatedCores: { Computed: true, - Description: "Shared processor pool available cores", - }, - - Attr_SharedProcessorPoolAllocatedCores: { + Description: "The allocated cores in the shared processor pool.", Type: schema.TypeFloat, - Computed: true, - Description: "Shared processor pool allocated cores", }, - - Attr_SharedProcessorPoolStatus: { - Type: schema.TypeString, + Attr_AvailableCores: { Computed: true, - Description: "The status of the shared processor pool", + Description: "The available cores in the shared processor pool.", + Type: schema.TypeFloat, }, - - Attr_SharedProcessorPoolStatusDetail: { - Type: schema.TypeString, + Attr_HostID: { Computed: true, - Description: "The status details of the shared processor pool", + Description: "The host ID where the shared processor pool resides.", + Type: schema.TypeInt, }, - - Attr_SharedProcessorPoolInstances: { - Type: schema.TypeList, + Attr_Instances: { Computed: true, - Description: "List of server instances deployed in the shared processor pool", + Description: "List of server instances deployed in the shared processor pool.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - Attr_SharedProcessorPoolInstanceCpus: { - Type: schema.TypeInt, - Optional: true, + Attr_AvailabilityZone: { Computed: true, - Description: "The amount of cpus for the server instance", - }, - Attr_SharedProcessorPoolInstanceUncapped: { - Type: schema.TypeBool, + Description: "Availability zone for the server instances.", Optional: true, - Computed: true, - Description: "Identifies if uncapped or not", - }, - Attr_SharedProcessorPoolInstanceAvailabilityZone: { Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "Availability zone for the server instances", }, - Attr_SharedProcessorPoolInstanceId: { - Type: schema.TypeString, - Optional: true, + Attr_CPUs: { Computed: true, - Description: "The server instance ID", - }, - Attr_SharedProcessorPoolInstanceMemory: { - Type: schema.TypeInt, + Description: "The amount of cpus for the server instance.", Optional: true, - Computed: true, - Description: "The amount of memory for the server instance", + Type: schema.TypeInt, }, - Attr_SharedProcessorPoolInstanceName: { - Type: schema.TypeString, + Attr_ID: { + Computed: true, + Description: "The server instance ID.", Optional: true, + Type: schema.TypeString, + }, + Attr_Memory: { Computed: true, - Description: "The server instance name", + Description: "The amount of memory for the server instance.", + Optional: true, + Type: schema.TypeInt, }, - Attr_SharedProcessorPoolInstanceStatus: { - Type: schema.TypeString, + Attr_Name: { + Computed: true, + Description: "The server instance name.", Optional: true, + Type: schema.TypeString, + }, + Attr_Status: { Computed: true, - Description: "Status of the server", + Description: "Status of the instance.", + Optional: true, + Type: schema.TypeString, }, - Attr_SharedProcessorPoolInstanceVcpus: { - Type: schema.TypeFloat, + Attr_Uncapped: { + Computed: true, + Description: "Identifies if uncapped or not.", Optional: true, + Type: schema.TypeBool, + }, + Attr_VCPUs: { Computed: true, - Description: "The amout of vcpus for the server instance", + Description: "The amout of vcpus for the server instance.", + Optional: true, + Type: schema.TypeFloat, }, }, }, + Type: schema.TypeList, + }, + Attr_Name: { + Computed: true, + Description: "The name of the shared processor pool.", + Type: schema.TypeString, + }, + Attr_ReservedCores: { + Computed: true, + Description: "The amount of reserved cores for the shared processor pool.", + Type: schema.TypeInt, + }, + Attr_Status: { + Computed: true, + Description: "The status of the shared processor pool.", + Type: schema.TypeString, + }, + Attr_StatusDetail: { + Computed: true, + Description: "The status details of the shared processor pool.", + Type: schema.TypeString, }, }, } } func dataSourceIBMPISharedProcessorPoolRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) poolID := d.Get(Arg_SharedProcessorPoolID).(string) - client := st.NewIBMPISharedProcessorPoolClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPISharedProcessorPoolClient(ctx, sess, cloudInstanceID) response, err := client.Get(poolID) if err != nil || response == nil { @@ -150,33 +144,33 @@ func dataSourceIBMPISharedProcessorPoolRead(ctx context.Context, d *schema.Resou } d.SetId(*response.SharedProcessorPool.ID) - d.Set(Attr_SharedProcessorPoolName, response.SharedProcessorPool.Name) - d.Set(Attr_SharedProcessorPoolReservedCores, response.SharedProcessorPool.ReservedCores) - d.Set(Attr_SharedProcessorPoolAllocatedCores, response.SharedProcessorPool.AllocatedCores) - d.Set(Attr_SharedProcessorPoolAvailableCores, response.SharedProcessorPool.AvailableCores) - d.Set(Attr_SharedProcessorPoolHostID, response.SharedProcessorPool.HostID) - d.Set(Attr_SharedProcessorPoolStatus, response.SharedProcessorPool.Status) - d.Set(Attr_SharedProcessorPoolStatusDetail, response.SharedProcessorPool.StatusDetail) + d.Set(Attr_AllocatedCores, response.SharedProcessorPool.AllocatedCores) + d.Set(Attr_AvailableCores, response.SharedProcessorPool.AvailableCores) + d.Set(Attr_HostID, response.SharedProcessorPool.HostID) + d.Set(Attr_Name, response.SharedProcessorPool.Name) + d.Set(Attr_ReservedCores, response.SharedProcessorPool.ReservedCores) + d.Set(Attr_Status, response.SharedProcessorPool.Status) + d.Set(Attr_StatusDetail, response.SharedProcessorPool.StatusDetail) serversMap := []map[string]interface{}{} if response.Servers != nil { for _, s := range response.Servers { if s != nil { v := map[string]interface{}{ - Attr_SharedProcessorPoolInstanceCpus: s.Cpus, - Attr_SharedProcessorPoolInstanceUncapped: s.Uncapped, - Attr_SharedProcessorPoolInstanceAvailabilityZone: s.AvailabilityZone, - Attr_SharedProcessorPoolInstanceId: s.ID, - Attr_SharedProcessorPoolInstanceMemory: s.Memory, - Attr_SharedProcessorPoolInstanceName: s.Name, - Attr_SharedProcessorPoolInstanceStatus: s.Status, - Attr_SharedProcessorPoolInstanceVcpus: s.Vcpus, + Attr_AvailabilityZone: s.AvailabilityZone, + Attr_CPUs: s.Cpus, + Attr_ID: s.ID, + Attr_Memory: s.Memory, + Attr_Name: s.Name, + Attr_Status: s.Status, + Attr_Uncapped: s.Uncapped, + Attr_VCPUs: s.Vcpus, } serversMap = append(serversMap, v) } } } - d.Set(Attr_SharedProcessorPoolInstances, serversMap) + d.Set(Attr_Instances, serversMap) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_shared_processor_pool_test.go b/ibm/service/power/data_source_ibm_pi_shared_processor_pool_test.go index a39f509265..17df24c366 100644 --- a/ibm/service/power/data_source_ibm_pi_shared_processor_pool_test.go +++ b/ibm/service/power/data_source_ibm_pi_shared_processor_pool_test.go @@ -28,9 +28,8 @@ func TestAccIBMPIPISharedProcessorPoolDataSource_basic(t *testing.T) { func testAccCheckIBMPIPISharedProcessorPoolDataSourceConfig() string { return fmt.Sprintf(` -data "ibm_pi_shared_processor_pool" "test_pool" { - pi_shared_processor_pool_id = "%s" - pi_cloud_instance_id = "%s" -}`, acc.Pi_shared_processor_pool_id, acc.Pi_cloud_instance_id) - + data "ibm_pi_shared_processor_pool" "test_pool" { + pi_shared_processor_pool_id = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_shared_processor_pool_id, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_shared_processor_pools.go b/ibm/service/power/data_source_ibm_pi_shared_processor_pools.go index e14611d878..74ccf37d22 100644 --- a/ibm/service/power/data_source_ibm_pi_shared_processor_pools.go +++ b/ibm/service/power/data_source_ibm_pi_shared_processor_pools.go @@ -6,70 +6,75 @@ package power import ( "context" + "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" -) - -const ( - PISharedProcessorPools = "shared_processor_pools" ) func DataSourceIBMPISharedProcessorPools() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPISharedProcessorPoolsRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "PI cloud instance ID", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - PISharedProcessorPools: { - Type: schema.TypeList, - Computed: true, + + // Attributes + Attr_SharedProcessorPools: { + Computed: true, + Description: "List of all the shared processor pools.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - Attr_SharedProcessorPoolID: { - Type: schema.TypeString, - Computed: true, + Attr_AllocatedCores: { + Computed: true, + Description: "The allocated cores in the shared processor pool.", + Type: schema.TypeFloat, }, - Attr_SharedProcessorPoolAllocatedCores: { - Type: schema.TypeFloat, - Computed: true, + Attr_AvailableCores: { + Computed: true, + Description: "The available cores in the shared processor pool.", + Type: schema.TypeInt, }, - Attr_SharedProcessorPoolAvailableCores: { - Type: schema.TypeInt, - Computed: true, + Attr_HostID: { + Computed: true, + Description: "The host ID where the shared processor pool resides.", + Type: schema.TypeInt, }, - Attr_SharedProcessorPoolName: { - Type: schema.TypeString, - Computed: true, + Attr_Name: { + Computed: true, + Description: "The name of the shared processor pool.", + Type: schema.TypeString, }, - Attr_SharedProcessorPoolReservedCores: { - Type: schema.TypeInt, - Computed: true, + Attr_ReservedCores: { + Computed: true, + Description: "The amount of reserved cores for the shared processor pool.", + Type: schema.TypeInt, }, - Attr_SharedProcessorPoolHostID: { - Type: schema.TypeInt, - Computed: true, + Attr_SharedProcessorPoolID: { + Computed: true, + Description: "The shared processor pool's unique ID.", + Type: schema.TypeString, }, - Attr_SharedProcessorPoolStatus: { - Type: schema.TypeString, - Computed: true, + Attr_Status: { + Computed: true, + Description: "The status of the shared processor pool.", + Type: schema.TypeString, }, - Attr_SharedProcessorPoolStatusDetail: { - Type: schema.TypeString, - Computed: true, + Attr_StatusDetail: { + Computed: true, + Description: "The status details of the shared processor pool.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, }, }, } @@ -81,9 +86,9 @@ func dataSourceIBMPISharedProcessorPoolsRead(ctx context.Context, d *schema.Reso return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) - client := st.NewIBMPISharedProcessorPoolClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPISharedProcessorPoolClient(ctx, sess, cloudInstanceID) pools, err := client.GetAll() if err != nil || pools == nil { return diag.Errorf("error fetching shared processor pools: %v", err) @@ -92,21 +97,21 @@ func dataSourceIBMPISharedProcessorPoolsRead(ctx context.Context, d *schema.Reso result := make([]map[string]interface{}, 0, len(pools.SharedProcessorPools)) for _, pool := range pools.SharedProcessorPools { key := map[string]interface{}{ - Attr_SharedProcessorPoolID: *pool.ID, - Attr_SharedProcessorPoolName: *pool.Name, - Attr_SharedProcessorPoolAllocatedCores: *pool.AllocatedCores, - Attr_SharedProcessorPoolAvailableCores: *pool.AvailableCores, - Attr_SharedProcessorPoolReservedCores: *pool.ReservedCores, - Attr_SharedProcessorPoolHostID: pool.HostID, - Attr_SharedProcessorPoolStatus: pool.Status, - Attr_SharedProcessorPoolStatusDetail: pool.StatusDetail, + Attr_AllocatedCores: *pool.AllocatedCores, + Attr_AvailableCores: *pool.AvailableCores, + Attr_HostID: pool.HostID, + Attr_Name: *pool.Name, + Attr_ReservedCores: *pool.ReservedCores, + Attr_SharedProcessorPoolID: *pool.ID, + Attr_Status: pool.Status, + Attr_StatusDetail: pool.StatusDetail, } result = append(result, key) } var genID, _ = uuid.GenerateUUID() d.SetId(genID) - d.Set(PISharedProcessorPools, result) + d.Set(Attr_SharedProcessorPools, result) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_shared_processor_pools_test.go b/ibm/service/power/data_source_ibm_pi_shared_processor_pools_test.go index fcbb9c4dbb..1d5367bf85 100644 --- a/ibm/service/power/data_source_ibm_pi_shared_processor_pools_test.go +++ b/ibm/service/power/data_source_ibm_pi_shared_processor_pools_test.go @@ -30,6 +30,5 @@ func testAccCheckIBMPISharedProcessorPoolsDataSourceConfig() string { return fmt.Sprintf(` data "ibm_pi_shared_processor_pools" "test" { pi_cloud_instance_id = "%s" - } - `, acc.Pi_cloud_instance_id) + }`, acc.Pi_cloud_instance_id) } diff --git a/website/docs/d/pi_shared_processor_pool.html.markdown b/website/docs/d/pi_shared_processor_pool.html.markdown index b47e607be6..7918b46199 100644 --- a/website/docs/d/pi_shared_processor_pool.html.markdown +++ b/website/docs/d/pi_shared_processor_pool.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_shared_processor_pool" @@ -11,7 +10,6 @@ description: |- Retrieve information about a shared processor pool. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example Usage - ```terraform data "ibm_pi_shared_processor_pool" "ds_pool" { pi_shared_processor_pool_id = "my-spp" @@ -20,20 +18,18 @@ data "ibm_pi_shared_processor_pool" "ds_pool" { ``` **Notes** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - - Example usage: +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` +Example usage: ```terraform provider "ibm" { region = "lon" zone = "lon04" } - ``` - + ``` ## Argument reference Review the argument references that you can specify for your data source. @@ -48,7 +44,8 @@ In addition to all argument reference list, you can access the following attribu - `available_cores` - (Integer) The available cores in the shared processor pool. - `host_id` - (Integer) The host ID where the shared processor pool resides. - `id` - (String) The shared processor pool's unique ID. -- `instances` - (List of Map) The list of server instances that are deployed in the shared processor pool. +- `instances` - (List) List of server instances deployed in the shared processor pool. + Nested scheme for `instances`: - `availability_zone` - (String) Availability zone for the server instances. - `cpus` - (Integer) The amount of cpus for the server instance. diff --git a/website/docs/d/pi_shared_processor_pools.html.markdown b/website/docs/d/pi_shared_processor_pools.html.markdown index dd9ad6d97e..3586e0437c 100644 --- a/website/docs/d/pi_shared_processor_pools.html.markdown +++ b/website/docs/d/pi_shared_processor_pools.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_shared_processor_pools" @@ -11,7 +10,6 @@ description: |- Retrieve information about all shared processor pools. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_shared_processor_pools" "example" { pi_cloud_instance_id = "" @@ -19,14 +17,12 @@ data "ibm_pi_shared_processor_pools" "example" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -52,4 +48,4 @@ In addition to all argument reference list, you can access the following attribu - `reserved_cores` - (Integer) The amount of reserved cores for the shared processor pool. - `shared_processor_pool_id` - (String) The shared processor pool's unique ID. - `status` - (String) The status of the shared processor pool. - - `status_detail` - (String) The status details of the shared processor pool. \ No newline at end of file + - `status_detail` - (String) The status details of the shared processor pool. From aaa689c80e65207601fe66c0ec784b44b5498e86 Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:36:22 +0530 Subject: [PATCH 26/34] Refactor placement group data source and documentation (#5097) * Refactor placement group data source and documentation * Pull ibm_ pi_constants.go from constant-refactor branch * update master Resolve conflicts --- .../data_source_ibm_pi_placement_group.go | 53 +++++++-------- ...data_source_ibm_pi_placement_group_test.go | 9 ++- .../data_source_ibm_pi_placement_groups.go | 66 +++++++++---------- ...ata_source_ibm_pi_placement_groups_test.go | 3 +- .../docs/d/pi_placement_group.html.markdown | 16 ++--- .../docs/d/pi_placement_groups.html.markdown | 14 ++-- 6 files changed, 76 insertions(+), 85 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_placement_group.go b/ibm/service/power/data_source_ibm_pi_placement_group.go index 9792aa331d..6b90a44f98 100644 --- a/ibm/service/power/data_source_ibm_pi_placement_group.go +++ b/ibm/service/power/data_source_ibm_pi_placement_group.go @@ -7,55 +7,56 @@ import ( "context" "log" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPIPlacementGroup() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPIPlacementGroupRead, Schema: map[string]*schema.Schema{ - helpers.PIPlacementGroupName: { - Type: schema.TypeString, - Required: true, - }, - - "policy": { - Type: schema.TypeString, - Computed: true, - }, - - helpers.PICloudInstanceId: { + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", + Required: true, Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, + }, + Arg_PlacementGroupName: { + Description: "The name of the placement group.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - PIPlacementGroupMembers: { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, + // Attribute + Attr_Members: { + Computed: true, + Description: "List of server instances IDs that are members of the placement group.", + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, + }, + Attr_Policy: { + Computed: true, + Description: "The value of the group's affinity policy. Valid values are affinity and anti-affinity.", + Type: schema.TypeString, }, }, } } func dataSourceIBMPIPlacementGroupRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - placementGroupName := d.Get(helpers.PIPlacementGroupName).(string) - client := st.NewIBMPIPlacementGroupClient(ctx, sess, cloudInstanceID) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + placementGroupName := d.Get(Arg_PlacementGroupName).(string) + client := instance.NewIBMPIPlacementGroupClient(ctx, sess, cloudInstanceID) response, err := client.Get(placementGroupName) if err != nil { @@ -64,8 +65,8 @@ func dataSourceIBMPIPlacementGroupRead(ctx context.Context, d *schema.ResourceDa } d.SetId(*response.ID) - d.Set("policy", response.Policy) - d.Set(PIPlacementGroupMembers, response.Members) + d.Set(Attr_Members, response.Members) + d.Set(Attr_Policy, response.Policy) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_placement_group_test.go b/ibm/service/power/data_source_ibm_pi_placement_group_test.go index 0738266a98..05478cc72a 100644 --- a/ibm/service/power/data_source_ibm_pi_placement_group_test.go +++ b/ibm/service/power/data_source_ibm_pi_placement_group_test.go @@ -28,9 +28,8 @@ func TestAccIBMPIPlacementGroupDataSource_basic(t *testing.T) { func testAccCheckIBMPIPlacementGroupDataSourceConfig() string { return fmt.Sprintf(` -data "ibm_pi_placement_group" "testacc_ds_placement_group" { - pi_placement_group_name = "%s" - pi_cloud_instance_id = "%s" -}`, acc.Pi_placement_group_name, acc.Pi_cloud_instance_id) - + data "ibm_pi_placement_group" "testacc_ds_placement_group" { + pi_placement_group_name = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_placement_group_name, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_placement_groups.go b/ibm/service/power/data_source_ibm_pi_placement_groups.go index 345f2bf05c..6b25ed99ba 100644 --- a/ibm/service/power/data_source_ibm_pi_placement_groups.go +++ b/ibm/service/power/data_source_ibm_pi_placement_groups.go @@ -7,52 +7,52 @@ import ( "context" "log" + "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" -) - -const ( - PIPlacementGroups = "placement_groups" ) func DataSourceIBMPIPlacementGroups() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPIPlacementGroupsRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "PI cloud instance ID", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - PIPlacementGroups: { + + // Attributes + Attr_PlacementGroups: { Type: schema.TypeList, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, + Attr_ID: { + Computed: true, + Description: "The ID of the placement group.", + Type: schema.TypeString, }, - "name": { - Type: schema.TypeString, - Computed: true, + Attr_Members: { + Computed: true, + Description: "List of server instances IDs that are members of the placement group.", + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeList, }, - PIPlacementGroupMembers: { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, + Attr_Name: { + Computed: true, + Description: "User defined name for the placement group.", + Type: schema.TypeString, }, - "policy": { - Type: schema.TypeString, - Computed: true, + Attr_Policy: { + Computed: true, + Description: "The value of the group's affinity policy. Valid values are affinity and anti-affinity.", + Type: schema.TypeString, }, }, }, @@ -67,9 +67,9 @@ func dataSourceIBMPIPlacementGroupsRead(ctx context.Context, d *schema.ResourceD return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) - client := st.NewIBMPIPlacementGroupClient(ctx, sess, cloudInstanceID) + client := instance.NewIBMPIPlacementGroupClient(ctx, sess, cloudInstanceID) groups, err := client.GetAll() if err != nil { log.Printf("[ERROR] get all placement groups failed %v", err) @@ -79,17 +79,17 @@ func dataSourceIBMPIPlacementGroupsRead(ctx context.Context, d *schema.ResourceD result := make([]map[string]interface{}, 0, len(groups.PlacementGroups)) for _, placementGroup := range groups.PlacementGroups { key := map[string]interface{}{ - "id": placementGroup.ID, - "name": placementGroup.Name, - PIPlacementGroupMembers: placementGroup.Members, - "policy": placementGroup.Policy, + Attr_ID: placementGroup.ID, + Attr_Members: placementGroup.Members, + Attr_Name: placementGroup.Name, + Attr_Policy: placementGroup.Policy, } result = append(result, key) } var genID, _ = uuid.GenerateUUID() d.SetId(genID) - d.Set(PIPlacementGroups, result) + d.Set(Attr_PlacementGroups, result) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_placement_groups_test.go b/ibm/service/power/data_source_ibm_pi_placement_groups_test.go index 2f0e8131c8..d520f3f1e0 100644 --- a/ibm/service/power/data_source_ibm_pi_placement_groups_test.go +++ b/ibm/service/power/data_source_ibm_pi_placement_groups_test.go @@ -30,6 +30,5 @@ func testAccCheckIBMPIPlacementGrousDataSourceConfig() string { return fmt.Sprintf(` data "ibm_pi_placement_groups" "test" { pi_cloud_instance_id = "%s" - } - `, acc.Pi_cloud_instance_id) + }`, acc.Pi_cloud_instance_id) } diff --git a/website/docs/d/pi_placement_group.html.markdown b/website/docs/d/pi_placement_group.html.markdown index d90d4b83f9..0c6aebd4d4 100644 --- a/website/docs/d/pi_placement_group.html.markdown +++ b/website/docs/d/pi_placement_group.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_placement_group" @@ -11,7 +10,6 @@ description: |- Retrieve information about a placement group. For more information, about placement groups, see [Managing server placement groups](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-placement-groups). ## Example Usage - ```terraform data "ibm_pi_placement_group" "ds_placement_group" { pi_placement_group_name = "my-pg" @@ -20,20 +18,18 @@ data "ibm_pi_placement_group" "ds_placement_group" { ``` **Notes** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - - Example usage: +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` +Example usage: ```terraform provider "ibm" { region = "lon" zone = "lon04" } ``` - ## Argument reference Review the argument references that you can specify for your data source. @@ -45,5 +41,5 @@ Review the argument references that you can specify for your data source. In addition to all argument reference list, you can access the following attribute references after your data source is created. - `id` - (String) The ID of the placement group. -- `members` - (List of strings) The list of server instances IDs that are members of the placement group. +- `members` - (List) List of server instances IDs that are members of the placement group. - `policy` - (String) The value of the group's affinity policy. Valid values are affinity and anti-affinity. diff --git a/website/docs/d/pi_placement_groups.html.markdown b/website/docs/d/pi_placement_groups.html.markdown index c4ef5d7946..a1e11659bf 100644 --- a/website/docs/d/pi_placement_groups.html.markdown +++ b/website/docs/d/pi_placement_groups.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_placement_groups" @@ -11,7 +10,6 @@ description: |- Retrieve information about all placement groups. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_placement_groups" "example" { pi_cloud_instance_id = "" @@ -19,14 +17,12 @@ data "ibm_pi_placement_groups" "example" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -46,6 +42,6 @@ In addition to all argument reference list, you can access the following attribu Nested scheme for `placement_groups`: - `id` - (String) The ID of the placement group. + - `members` - (List) List of server instances IDs that are members of the placement group. - `name` - (String) User defined name for the placement group. - - `members` - (List of strings) The list of server instances IDs that are members of the placement group. - `policy` - (String) The value of the group's affinity policy. Valid values are affinity and anti-affinity. From d01940c68444d87602eb8cff0a88f61a6344c67e Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:37:25 +0530 Subject: [PATCH 27/34] Refactor network port data source and documentation (#5096) * refactor network port data source and documentation * network data source and documentation * Pull ibm_ pi_constants.go from constant-refactor branch * Replace bool with Boolean --- .../power/data_source_ibm_pi_network.go | 152 ++++++++++-------- .../power/data_source_ibm_pi_network_port.go | 93 ++++++----- .../data_source_ibm_pi_network_port_test.go | 36 +++++ .../power/data_source_ibm_pi_network_test.go | 9 +- website/docs/d/pi_network.html.markdown | 24 ++- website/docs/d/pi_network_port.html.markdown | 52 ++++++ 6 files changed, 232 insertions(+), 134 deletions(-) create mode 100644 ibm/service/power/data_source_ibm_pi_network_port_test.go create mode 100644 website/docs/d/pi_network_port.html.markdown diff --git a/ibm/service/power/data_source_ibm_pi_network.go b/ibm/service/power/data_source_ibm_pi_network.go index 3a04453ca7..2835514f90 100644 --- a/ibm/service/power/data_source_ibm_pi_network.go +++ b/ibm/service/power/data_source_ibm_pi_network.go @@ -4,86 +4,97 @@ package power import ( - //"fmt" - "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPINetwork() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPINetworkRead, Schema: map[string]*schema.Schema{ - helpers.PINetworkName: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "Network Name to be used for pvminstances", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - helpers.PICloudInstanceId: { - Type: schema.TypeString, + Arg_NetworkName: { + Description: "The unique identifier or name of a network.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - "cidr": { - Type: schema.TypeString, - Computed: true, + // Attributes + Attr_AccessConfig: { + Computed: true, + Description: "The network communication configuration option of the network (for satellite locations only).", + Type: schema.TypeString, }, - "type": { - Type: schema.TypeString, - Computed: true, + Attr_AvailableIPCount: { + Computed: true, + Description: "The total number of IP addresses that you have in your network.", + Type: schema.TypeFloat, }, - "vlan_id": { - Type: schema.TypeInt, - Computed: true, + Attr_CIDR: { + Computed: true, + Description: "The CIDR of the network.", + Type: schema.TypeString, }, - "gateway": { - Type: schema.TypeString, - Computed: true, + Attr_DNS: { + Computed: true, + Description: "The DNS Servers for the network.", + Elem: &schema.Schema{Type: schema.TypeString}, + Type: schema.TypeSet, }, - "available_ip_count": { - Type: schema.TypeFloat, - Computed: true, + Attr_Gateway: { + Computed: true, + Description: "The network gateway that is attached to your network.", + Type: schema.TypeString, }, - "used_ip_count": { - Type: schema.TypeFloat, - Computed: true, + Attr_Jumbo: { + Computed: true, + Deprecated: "This field is deprecated, use mtu instead.", + Description: "MTU Jumbo option of the network (for multi-zone locations only).", + Type: schema.TypeBool, }, - "used_ip_percent": { - Type: schema.TypeFloat, - Computed: true, + Attr_MTU: { + Computed: true, + Description: "Maximum Transmission Unit option of the network.", + Type: schema.TypeInt, }, - "name": { - Type: schema.TypeString, - Computed: true, - Deprecated: "This value is deprecated in favor of" + helpers.PINetworkName, + Attr_Name: { + Computed: true, + Deprecated: "This field is deprecated, use pi_network_name instead.", + Description: "The unique identifier or name of a network.", + Type: schema.TypeString, }, - "dns": { - Type: schema.TypeSet, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Attr_Type: { + Computed: true, + Description: "The type of network.", + Type: schema.TypeString, }, - "jumbo": { - Type: schema.TypeBool, - Computed: true, + Attr_UsedIPCount: { + Computed: true, + Description: "The number of used IP addresses.", + Type: schema.TypeFloat, }, - "mtu": { - Type: schema.TypeInt, - Computed: true, + Attr_UsedIPPercent: { + Computed: true, + Description: "The percentage of IP addresses used.", + Type: schema.TypeFloat, }, - "access_config": { - Type: schema.TypeString, - Computed: true, + Attr_VLanID: { + Computed: true, + Description: "The VLAN ID that the network is connected to.", + Type: schema.TypeInt, }, }, } @@ -95,7 +106,7 @@ func dataSourceIBMPINetworkRead(ctx context.Context, d *schema.ResourceData, met return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) networkC := instance.NewIBMPINetworkClient(ctx, sess, cloudInstanceID) networkdata, err := networkC.Get(d.Get(helpers.PINetworkName).(string)) @@ -104,35 +115,34 @@ func dataSourceIBMPINetworkRead(ctx context.Context, d *schema.ResourceData, met } d.SetId(*networkdata.NetworkID) + d.Set(Attr_AccessConfig, networkdata.AccessConfig) + if networkdata.IPAddressMetrics.Available != nil { + d.Set(Attr_AvailableIPCount, networkdata.IPAddressMetrics.Available) + } if networkdata.Cidr != nil { - d.Set("cidr", networkdata.Cidr) + d.Set(Attr_CIDR, networkdata.Cidr) } - if networkdata.Type != nil { - d.Set("type", networkdata.Type) + if len(networkdata.DNSServers) > 0 { + d.Set(Attr_DNS, networkdata.DNSServers) } - d.Set("gateway", networkdata.Gateway) - if networkdata.VlanID != nil { - d.Set("vlan_id", networkdata.VlanID) + d.Set(Attr_Gateway, networkdata.Gateway) + d.Set(Attr_Jumbo, networkdata.Jumbo) + d.Set(Attr_MTU, networkdata.Mtu) + if networkdata.Name != nil { + d.Set(Attr_Name, networkdata.Name) } - if networkdata.IPAddressMetrics.Available != nil { - d.Set("available_ip_count", networkdata.IPAddressMetrics.Available) + if networkdata.Type != nil { + d.Set(Attr_Type, networkdata.Type) } if networkdata.IPAddressMetrics.Used != nil { - d.Set("used_ip_count", networkdata.IPAddressMetrics.Used) + d.Set(Attr_UsedIPCount, networkdata.IPAddressMetrics.Used) } if networkdata.IPAddressMetrics.Utilization != nil { - d.Set("used_ip_percent", networkdata.IPAddressMetrics.Utilization) - } - if networkdata.Name != nil { - d.Set("name", networkdata.Name) + d.Set(Attr_UsedIPPercent, networkdata.IPAddressMetrics.Utilization) } - if len(networkdata.DNSServers) > 0 { - d.Set("dns", networkdata.DNSServers) + if networkdata.VlanID != nil { + d.Set(Attr_VLanID, networkdata.VlanID) } - d.Set("jumbo", networkdata.Jumbo) - d.Set("mtu", networkdata.Mtu) - d.Set("access_config", networkdata.AccessConfig) return nil - } diff --git a/ibm/service/power/data_source_ibm_pi_network_port.go b/ibm/service/power/data_source_ibm_pi_network_port.go index e98a9c3b1b..5fef77e7af 100644 --- a/ibm/service/power/data_source_ibm_pi_network_port.go +++ b/ibm/service/power/data_source_ibm_pi_network_port.go @@ -7,69 +7,74 @@ import ( "context" "log" + "github.com/IBM-Cloud/power-go-client/clients/instance" + "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - //"fmt" - "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPINetworkPort() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPINetworkPortsRead, Schema: map[string]*schema.Schema{ - helpers.PINetworkName: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "Network Name to be used for pvminstances", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - helpers.PICloudInstanceId: { - Type: schema.TypeString, + Arg_NetworkName: { + Description: "The unique identifier or name of a network.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - "network_ports": { + // Attributes + Attr_NetworkPorts: { Type: schema.TypeList, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "ipaddress": { - Type: schema.TypeString, - Optional: true, - Computed: true, + Attr_Description: { + Computed: true, + Description: "The description for the network port.", + Type: schema.TypeString, }, - "macaddress": { - Type: schema.TypeString, - Computed: true, + Attr_Href: { + Computed: true, + Description: "Network port href.", + Type: schema.TypeString, }, - "portid": { - Type: schema.TypeString, - Computed: true, + Attr_IPAddress: { + Computed: true, + Description: "The IP address of the port.", + Type: schema.TypeString, }, - "status": { - Type: schema.TypeString, - Computed: true, + Attr_MacAddress: { + Computed: true, + Description: "The MAC address of the port.", + Type: schema.TypeString, }, - "href": { - Type: schema.TypeString, - Computed: true, + Attr_PortID: { + Computed: true, + Description: "The ID of the port.", + Type: schema.TypeString, }, - "description": { - Type: schema.TypeString, - Required: true, + Attr_PublicIP: { + Computed: true, + Description: "The public IP associated with the port.", + Type: schema.TypeString, }, - "public_ip": { - Type: schema.TypeString, - Computed: true, + Attr_Status: { + Computed: true, + Description: "The status of the port.", + Type: schema.TypeString, }, }, }, @@ -84,7 +89,8 @@ func dataSourceIBMPINetworkPortsRead(ctx context.Context, d *schema.ResourceData return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + networkportC := instance.NewIBMPINetworkClient(ctx, sess, cloudInstanceID) networkportdata, err := networkportC.GetAllPorts(d.Get(helpers.PINetworkName).(string)) if err != nil { @@ -93,10 +99,9 @@ func dataSourceIBMPINetworkPortsRead(ctx context.Context, d *schema.ResourceData var clientgenU, _ = uuid.GenerateUUID() d.SetId(clientgenU) - d.Set("network_ports", flattenNetworkPorts(networkportdata.Ports)) + d.Set(Attr_NetworkPorts, flattenNetworkPorts(networkportdata.Ports)) return nil - } func flattenNetworkPorts(networkPorts []*models.NetworkPort) interface{} { @@ -104,14 +109,14 @@ func flattenNetworkPorts(networkPorts []*models.NetworkPort) interface{} { log.Printf("the number of ports is %d", len(networkPorts)) for _, i := range networkPorts { l := map[string]interface{}{ - "portid": *i.PortID, - "status": *i.Status, - "href": i.Href, - "ipaddress": *i.IPAddress, - "macaddress": *i.MacAddress, - "public_ip": i.ExternalIP, + Attr_Description: i.Description, + Attr_Href: i.Href, + Attr_IPAddress: *i.IPAddress, + Attr_MacAddress: *i.MacAddress, + Attr_PortID: *i.PortID, + Attr_PublicIP: i.ExternalIP, + Attr_Status: *i.Status, } - result = append(result, l) } return result diff --git a/ibm/service/power/data_source_ibm_pi_network_port_test.go b/ibm/service/power/data_source_ibm_pi_network_port_test.go new file mode 100644 index 0000000000..24a386af2d --- /dev/null +++ b/ibm/service/power/data_source_ibm_pi_network_port_test.go @@ -0,0 +1,36 @@ +// Copyright IBM Corp. 2017, 2021 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package power_test + +import ( + "fmt" + "testing" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccIBMPINetworkPortDataSource_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMPINetworkPortDataSourceConfig(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_pi_network_port.testacc_ds_network_port", "id"), + ), + }, + }, + }) +} + +func testAccCheckIBMPINetworkPortDataSourceConfig() string { + return fmt.Sprintf(` + data "ibm_pi_network_port" "testacc_ds_network_port" { + pi_network_name = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_network_name, acc.Pi_cloud_instance_id) +} diff --git a/ibm/service/power/data_source_ibm_pi_network_test.go b/ibm/service/power/data_source_ibm_pi_network_test.go index 873681869a..c4c09fa58c 100644 --- a/ibm/service/power/data_source_ibm_pi_network_test.go +++ b/ibm/service/power/data_source_ibm_pi_network_test.go @@ -29,9 +29,8 @@ func TestAccIBMPINetworkDataSource_basic(t *testing.T) { func testAccCheckIBMPINetworkDataSourceConfig() string { return fmt.Sprintf(` -data "ibm_pi_network" "testacc_ds_network" { - pi_network_name = "%s" - pi_cloud_instance_id = "%s" -}`, acc.Pi_network_name, acc.Pi_cloud_instance_id) - + data "ibm_pi_network" "testacc_ds_network" { + pi_network_name = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_network_name, acc.Pi_cloud_instance_id) } diff --git a/website/docs/d/pi_network.html.markdown b/website/docs/d/pi_network.html.markdown index c4f03cb824..30635fd315 100644 --- a/website/docs/d/pi_network.html.markdown +++ b/website/docs/d/pi_network.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_network" @@ -11,7 +10,6 @@ description: |- Retrieve information about the network that your Power Systems Virtual Server instance is connected to. For more information, about power virtual server instance network, see [setting up an IBM network install server](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-configuring-subnet). ## Example usage - ```terraform data "ibm_pi_network" "ds_network" { pi_network_name = "APP" @@ -19,15 +17,13 @@ data "ibm_pi_network" "ds_network" { } ``` -**Note** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` - Example usage: - +Example usage: ```terraform provider "ibm" { region = "lon" @@ -44,15 +40,15 @@ Review the argument references that you can specify for your data source. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. +- `access_config` - (String) The network communication configuration option of the network (for satellite locations only). - `available_ip_count` - (Float) The total number of IP addresses that you have in your network. - `cidr` - (String) The CIDR of the network. -- `dns`- (Set of String) The DNS Servers for the network. +- `dns`- (Set) The DNS Servers for the network. - `gateway` - (String) The network gateway that is attached to your network. - `id` - (String) The ID of the network. +- `jumbo` - (Deprecated, Boolean) MTU Jumbo option of the network (for multi-zone locations only). +- `mtu` - (Boolean) Maximum Transmission Unit option of the network. - `type` - (String) The type of network. - `used_ip_count` - (Float) The number of used IP addresses. - `used_ip_percent` - (Float) The percentage of IP addresses used. - `vlan_id` - (String) The VLAN ID that the network is connected to. -- `jumbo` - (Bool) MTU Jumbo option of the network (for multi-zone locations only). `deprecated` -- `mtu` - (Bool) Maximum Transmission Unit option of the network. -- `access_config` - (String) The network communication configuration option of the network (for satellite locations only). \ No newline at end of file diff --git a/website/docs/d/pi_network_port.html.markdown b/website/docs/d/pi_network_port.html.markdown new file mode 100644 index 0000000000..9d46bee2d0 --- /dev/null +++ b/website/docs/d/pi_network_port.html.markdown @@ -0,0 +1,52 @@ +--- +subcategory: "Power Systems" +layout: "ibm" +page_title: "IBM: pi_network_port" +description: |- + Manages an Network Port in the Power Virtual Server Cloud. +--- + +# ibm_pi_network_port +Retrieve information about a network port in the Power Virtual Server Cloud. For more information, about networks in IBM power virtual server, see [adding or removing a public network](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-modifying-server#adding-removing-network). + +## Example usage +```terraform +data "ibm_pi_network_port" "test-network-port" { + pi_network_name = "Zone1-CFN" + pi_cloud_instance_id = "51e1879c-bcbe-4ee1-a008-49cdba0eaf60" +} +``` + +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` + +Example usage: + ```terraform + provider "ibm" { + region = "lon" + zone = "lon04" + } + ``` + +## Argument reference +Review the argument references that you can specify for your data source. + +- `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. +- `pi_network_name` - (Required, String) The unique identifier or name of a network. + +## Attribute reference +In addition to all argument reference list, you can access the following attribute reference after your data source is created. + +- `network_ports` - (List) List of all in use network ports for a network. + + Nested scheme for `network_ports`: + - `description` - (String) The description for the network port. + - `href` - (String) Network port href. + - `ipaddress` - (String) The IP address of the port. + - `macaddress` - (String) The MAC address of the port. + - `portid` - (String) The ID of the port. + - `public_ip`- (String) The public IP associated with the port. + - `status` - (String) The status of the port. From 0a8634522c2587b20054c6f54e527bf455aa713e Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:44:43 +0530 Subject: [PATCH 28/34] Refactor ssh key data source and documentation (#5095) * Refactor ssh key data source and documentation * Pull ibm_ pi_constants.go from constant-refactor * Pull ibm_ pi_constants.go from constant-refactor branch * Remove extraspace from pi_keys_test.go * Remove duplicate creation_date constant --------- Co-authored-by: Axel Ismirlian --- ibm/service/power/data_source_ibm_pi_key.go | 52 +++++++------------ .../power/data_source_ibm_pi_key_test.go | 10 ++-- ibm/service/power/data_source_ibm_pi_keys.go | 41 ++++++--------- .../power/data_source_ibm_pi_keys_test.go | 3 +- ibm/service/power/ibm_pi_constants.go | 1 - ibm/service/power/resource_ibm_pi_key.go | 4 +- website/docs/d/pi_key.html.markdown | 40 +++++++------- website/docs/d/pi_keys.html.markdown | 38 ++++++-------- 8 files changed, 78 insertions(+), 111 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_key.go b/ibm/service/power/data_source_ibm_pi_key.go index 70ab96ba7c..b7f928828f 100644 --- a/ibm/service/power/data_source_ibm_pi_key.go +++ b/ibm/service/power/data_source_ibm_pi_key.go @@ -6,79 +6,65 @@ package power import ( "context" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" - "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPIKey() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPIKeyRead, Schema: map[string]*schema.Schema{ - // Arguments - Arg_KeyName: { - Type: schema.TypeString, + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "SSH key name for a pcloud tenant", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - Arg_CloudInstanceID: { - Type: schema.TypeString, + Arg_KeyName: { Required: true, + Description: "User defined name for the SSH key.", ValidateFunc: validation.NoZeroValues, + Type: schema.TypeString, }, // Attributes - Attr_KeyCreationDate: { - Type: schema.TypeString, + Attr_CreationDate: { Computed: true, - Description: "Date of sshkey creation", - }, - Attr_Key: { + Description: "Date of SSH Key creation.", Type: schema.TypeString, - Sensitive: true, - Computed: true, - Description: "SSH RSA key", }, - "sshkey": { - Type: schema.TypeString, - Sensitive: true, - Computed: true, - Deprecated: "This field is deprecated, use ssh_key instead", + Attr_SSHKey: { + Computed: true, + Description: "SSH RSA key.", + Sensitive: true, + Type: schema.TypeString, }, }, } } func dataSourceIBMPIKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - - // session sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - // arguments - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) - // get key sshkeyC := instance.NewIBMPIKeyClient(ctx, sess, cloudInstanceID) sshkeydata, err := sshkeyC.Get(d.Get(helpers.PIKeyName).(string)) if err != nil { return diag.FromErr(err) } - // set attributes d.SetId(*sshkeydata.Name) - d.Set(Attr_KeyCreationDate, sshkeydata.CreationDate.String()) - d.Set(Attr_Key, sshkeydata.SSHKey) - d.Set("sshkey", sshkeydata.SSHKey) // TODO: deprecated, to remove + d.Set(Attr_CreationDate, sshkeydata.CreationDate.String()) + d.Set(Attr_SSHKey, sshkeydata.SSHKey) return nil } diff --git a/ibm/service/power/data_source_ibm_pi_key_test.go b/ibm/service/power/data_source_ibm_pi_key_test.go index 184b74a0ec..a4fb373339 100644 --- a/ibm/service/power/data_source_ibm_pi_key_test.go +++ b/ibm/service/power/data_source_ibm_pi_key_test.go @@ -13,7 +13,6 @@ import ( ) func TestAccIBMPIKeyDataSource_basic(t *testing.T) { - resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, Providers: acc.TestAccProviders, @@ -30,9 +29,8 @@ func TestAccIBMPIKeyDataSource_basic(t *testing.T) { func testAccCheckIBMPIKeyDataSourceConfig() string { return fmt.Sprintf(` -data "ibm_pi_key" "testacc_ds_key" { - pi_key_name = "%s" - pi_cloud_instance_id = "%s" -}`, acc.Pi_key_name, acc.Pi_cloud_instance_id) - + data "ibm_pi_key" "testacc_ds_key" { + pi_key_name = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_key_name, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_keys.go b/ibm/service/power/data_source_ibm_pi_keys.go index 0f78a9ab4e..91bf669e1f 100644 --- a/ibm/service/power/data_source_ibm_pi_keys.go +++ b/ibm/service/power/data_source_ibm_pi_keys.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" ) @@ -21,56 +20,51 @@ func DataSourceIBMPIKeys() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPIKeysRead, Schema: map[string]*schema.Schema{ - // Arguments Arg_CloudInstanceID: { - Type: schema.TypeString, + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "PI cloud instance ID", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, // Attributes Attr_Keys: { - Type: schema.TypeList, Computed: true, - Description: "SSH Keys", + Description: "List of all the SSH keys.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - Attr_KeyName: { - Type: schema.TypeString, + Attr_CreationDate: { Computed: true, - Description: "User defined name for the SSH key", - }, - Attr_Key: { + Description: "Date of SSH key creation.", Type: schema.TypeString, - Computed: true, - Description: "SSH RSA key", }, - Attr_KeyCreationDate: { + Attr_Name: { + Computed: true, + Description: "User defined name for the SSH key.", Type: schema.TypeString, + }, + Attr_SSHKey: { Computed: true, - Description: "Date of SSH key creation", + Description: "SSH RSA key.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, }, }, } } func dataSourceIBMPIKeysRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - - // session sess, err := meta.(conns.ClientSession).IBMPISession() if err != nil { return diag.FromErr(err) } - // arguments - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) - // get keys client := st.NewIBMPIKeyClient(ctx, sess, cloudInstanceID) sshKeys, err := client.GetAll() if err != nil { @@ -78,13 +72,12 @@ func dataSourceIBMPIKeysRead(ctx context.Context, d *schema.ResourceData, meta i return diag.FromErr(err) } - // set attributes result := make([]map[string]interface{}, 0, len(sshKeys.SSHKeys)) for _, sshKey := range sshKeys.SSHKeys { key := map[string]interface{}{ - Attr_KeyName: sshKey.Name, - Attr_Key: sshKey.SSHKey, - Attr_KeyCreationDate: sshKey.CreationDate.String(), + Attr_CreationDate: sshKey.CreationDate.String(), + Attr_Name: sshKey.Name, + Attr_SSHKey: sshKey.SSHKey, } result = append(result, key) } diff --git a/ibm/service/power/data_source_ibm_pi_keys_test.go b/ibm/service/power/data_source_ibm_pi_keys_test.go index f45dfc7fce..66bb6c4596 100644 --- a/ibm/service/power/data_source_ibm_pi_keys_test.go +++ b/ibm/service/power/data_source_ibm_pi_keys_test.go @@ -31,6 +31,5 @@ func testAccCheckIBMPIKeysDataSourceConfig() string { return fmt.Sprintf(` data "ibm_pi_keys" "test" { pi_cloud_instance_id = "%s" - } - `, acc.Pi_cloud_instance_id) + }`, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/ibm_pi_constants.go b/ibm/service/power/ibm_pi_constants.go index db553ec77d..ab78b5d7b4 100644 --- a/ibm/service/power/ibm_pi_constants.go +++ b/ibm/service/power/ibm_pi_constants.go @@ -108,7 +108,6 @@ const ( Attr_IsActive = "is_active" Attr_Jumbo = "jumbo" Attr_Key = "key" - Attr_KeyCreationDate = "creation_date" Attr_KeyID = "key_id" Attr_KeyName = "name" Attr_Keys = "keys" diff --git a/ibm/service/power/resource_ibm_pi_key.go b/ibm/service/power/resource_ibm_pi_key.go index 3f305e4da2..be0c542be2 100644 --- a/ibm/service/power/resource_ibm_pi_key.go +++ b/ibm/service/power/resource_ibm_pi_key.go @@ -50,7 +50,7 @@ func ResourceIBMPIKey() *schema.Resource { }, // Attributes - Attr_KeyCreationDate: { + Attr_CreationDate: { Type: schema.TypeString, Computed: true, Description: "Date of SSH Key creation", @@ -129,7 +129,7 @@ func resourceIBMPIKeyRead(ctx context.Context, d *schema.ResourceData, meta inte d.Set(Attr_KeyName, sshkeydata.Name) d.Set(Attr_KeyID, sshkeydata.Name) d.Set(Attr_Key, sshkeydata.SSHKey) - d.Set(Attr_KeyCreationDate, sshkeydata.CreationDate.String()) + d.Set(Attr_CreationDate, sshkeydata.CreationDate.String()) return nil } diff --git a/website/docs/d/pi_key.html.markdown b/website/docs/d/pi_key.html.markdown index 19b824e44c..69eda7ca5b 100644 --- a/website/docs/d/pi_key.html.markdown +++ b/website/docs/d/pi_key.html.markdown @@ -1,28 +1,40 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_key" description: |- - Manages an key in the Power Virtual Server cloud. + Manages an SSH key in the Power Virtual Server cloud. --- # ibm_pi_key -Retrieve information about the SSH key that is used for your Power Systems Virtual Server instance. The SSH key is used to access the instance after it is created. For more information, about [configuring your IBM virtual machine (VM)](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-creating-ssh-key). +Retrieve information about the SSH key that is used for your Power Systems Virtual Server instance. The SSH key is used to access the instance after it is created. For more information, about [generating and using SSH Keys](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-creating-ssh-key). ## Example usage - ```terraform data "ibm_pi_key" "ds_instance" { pi_key_name = "terraform-test-key" pi_cloud_instance_id = "49fba6c9-23f8-40bc-9899-aca322ee7d5b" } ``` - + +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` + +Example usage: + ```terraform + provider "ibm" { + region = "lon" + zone = "lon04" + } + ``` + ## Argument reference Review the argument references that you can specify for your data source. -- `pi_cloud_instance_id` - (Required, String) Cloud Instance ID of a PCloud Instance. +- `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. - `pi_key_name` - (Required, String) User defined name for the SSH key. ## Attribute reference @@ -31,19 +43,3 @@ In addition to all argument reference list, you can access the following attribu - `id` - (String) User defined name for the SSH key - `creation_date` - (String) Date of SSH Key creation. - `ssh_key` - (String) SSH RSA key. - -**Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - -Example usage: - - ```terraform - provider "ibm" { - region = "lon" - zone = "lon04" - } - ``` \ No newline at end of file diff --git a/website/docs/d/pi_keys.html.markdown b/website/docs/d/pi_keys.html.markdown index 305c0f4a9d..dd5dac4d13 100644 --- a/website/docs/d/pi_keys.html.markdown +++ b/website/docs/d/pi_keys.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_keys" @@ -8,20 +7,33 @@ description: |- --- # ibm_pi_keys -Retrieve information about all SSH keys. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). +Retrieve information about all SSH keys. For more information, about [generating and using SSH Keys](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-creating-ssh-key). ## Example usage - ```terraform data "ibm_pi_keys" "example" { pi_cloud_instance_id = "" } ``` - + +**Notes** +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` + +Example usage: + ```terraform + provider "ibm" { + region = "lon" + zone = "lon04" + } + ``` + ## Argument reference Review the argument references that you can specify for your data source. -- `pi_cloud_instance_id` - (Required, String) Cloud Instance ID of a PCloud Instance. +- `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. @@ -32,19 +44,3 @@ In addition to all argument reference list, you can access the following attribu - `name` - (String) User defined name for the SSH key - `creation_date` - (String) Date of SSH Key creation. - `ssh_key` - (String) SSH RSA key. - -**Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - -Example usage: - - ```terraform - provider "ibm" { - region = "lon" - zone = "lon04" - } - ``` \ No newline at end of file From 0048ef5dbe408a395cf0d570592d2a41da340a7e Mon Sep 17 00:00:00 2001 From: Diptipowervs <152427968+Diptipowervs@users.noreply.github.com> Date: Tue, 6 Feb 2024 18:45:37 +0530 Subject: [PATCH 29/34] Refactor instance console languages-ip-volumes data source and documentation (#5093) * refactor instance console languages-ip-volumes data source and documnetation * Catalog refactor instance console languages-ip-volumes data source and documentation * Pull ibm_ pi_constants.go from constant-refactor * Add constant PIConsoleLanguage to pi_constants.go * Remove ConsoleLanguageCode from pi_instance_console.go * Replace bool with Boolean * update branch * remove duplicates in pi_constants --- ...ource_ibm_pi_instance_console_languages.go | 57 ++++---- ..._ibm_pi_instance_console_languages_test.go | 8 +- .../power/data_source_ibm_pi_instance_ip.go | 80 +++++------ .../data_source_ibm_pi_instance_ip_test.go | 11 +- .../data_source_ibm_pi_instance_volumes.go | 124 ++++++++++-------- ...ata_source_ibm_pi_instance_volumes_test.go | 9 +- ibm/service/power/ibm_pi_constants.go | 9 +- ...source_ibm_pi_instance_console_language.go | 6 +- .../docs/d/pi_console_languages.html.markdown | 15 +-- website/docs/d/pi_instance_ip.html.markdown | 16 +-- .../docs/d/pi_instance_volumes.html.markdown | 26 ++-- 11 files changed, 177 insertions(+), 184 deletions(-) diff --git a/ibm/service/power/data_source_ibm_pi_instance_console_languages.go b/ibm/service/power/data_source_ibm_pi_instance_console_languages.go index e5cb5b344d..d34dad28fb 100644 --- a/ibm/service/power/data_source_ibm_pi_instance_console_languages.go +++ b/ibm/service/power/data_source_ibm_pi_instance_console_languages.go @@ -6,59 +6,52 @@ package power import ( "context" - "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -const ( - ConsoleLanguages = "console_languages" - ConsoleLanguageCode = "code" - ConsoleLanguageDesc = "language" -) - -/* -Datasource to get the list of available console languages for an instance -*/ +// Datasource to list available console languages for an instance func DataSourceIBMPIInstanceConsoleLanguages() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceIBMPIInstanceConsoleLanguagesRead, Schema: map[string]*schema.Schema{ - helpers.PICloudInstanceId: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - helpers.PIInstanceName: { - Type: schema.TypeString, + Arg_InstanceName: { + Description: "The unique identifier or name of the instance.", Required: true, - Description: "The unique identifier or name of the instance", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - // Computed Attributes - ConsoleLanguages: { - Type: schema.TypeList, - Computed: true, + // Attributes + Attr_ConsoleLanguages: { + Computed: true, + Description: "List of all the Console Languages.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - ConsoleLanguageCode: { - Type: schema.TypeString, + Attr_Code: { Computed: true, - Description: "language code", - }, - ConsoleLanguageDesc: { + Description: "Language code.", Type: schema.TypeString, + }, + Attr_Language: { Computed: true, - Description: "language description", + Description: "Language description.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, }, }, } @@ -70,8 +63,8 @@ func dataSourceIBMPIInstanceConsoleLanguagesRead(ctx context.Context, d *schema. return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - instanceName := d.Get(helpers.PIInstanceName).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + instanceName := d.Get(Arg_InstanceName).(string) client := instance.NewIBMPIInstanceClient(ctx, sess, cloudInstanceID) languages, err := client.GetConsoleLanguages(instanceName) @@ -86,12 +79,12 @@ func dataSourceIBMPIInstanceConsoleLanguagesRead(ctx context.Context, d *schema. result := make([]map[string]interface{}, 0, len(languages.ConsoleLanguages)) for _, language := range languages.ConsoleLanguages { l := map[string]interface{}{ - ConsoleLanguageCode: *language.Code, - ConsoleLanguageDesc: language.Language, + Attr_Code: *language.Code, + Attr_Language: language.Language, } result = append(result, l) } - d.Set(ConsoleLanguages, result) + d.Set(Attr_ConsoleLanguages, result) } return nil diff --git a/ibm/service/power/data_source_ibm_pi_instance_console_languages_test.go b/ibm/service/power/data_source_ibm_pi_instance_console_languages_test.go index acadb056e0..9d52aa963f 100644 --- a/ibm/service/power/data_source_ibm_pi_instance_console_languages_test.go +++ b/ibm/service/power/data_source_ibm_pi_instance_console_languages_test.go @@ -30,8 +30,8 @@ func TestAccIBMPIInstanceConsoleLanguages(t *testing.T) { func testAccCheckIBMPIInstanceConsoleLanguagesConfig() string { return fmt.Sprintf(` - data "ibm_pi_console_languages" "example" { - pi_cloud_instance_id = "%s" - pi_instance_name = "%s" - }`, acc.Pi_cloud_instance_id, acc.Pi_instance_name) + data "ibm_pi_console_languages" "example" { + pi_cloud_instance_id = "%s" + pi_instance_name = "%s" + }`, acc.Pi_cloud_instance_id, acc.Pi_instance_name) } diff --git a/ibm/service/power/data_source_ibm_pi_instance_ip.go b/ibm/service/power/data_source_ibm_pi_instance_ip.go index 4d57021d36..60cac39d42 100644 --- a/ibm/service/power/data_source_ibm_pi_instance_ip.go +++ b/ibm/service/power/data_source_ibm_pi_instance_ip.go @@ -10,7 +10,6 @@ import ( "strconv" "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -18,51 +17,59 @@ import ( ) func DataSourceIBMPIInstanceIP() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPIInstancesIPRead, Schema: map[string]*schema.Schema{ - helpers.PIInstanceName: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "Server Name to be used for pvminstances", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - helpers.PICloudInstanceId: { - Type: schema.TypeString, + Arg_InstanceName: { + Description: "The unique identifier or name of the instance.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - helpers.PINetworkName: { + Arg_NetworkName: { + Description: "The subnet that the instance belongs to.", Type: schema.TypeString, Required: true, ValidateFunc: validation.NoZeroValues, }, - // Computed attributes - "ip": { - Type: schema.TypeString, - Computed: true, + // Attributes + Attr_ExternalIP: { + Computed: true, + Description: "The external IP of the network that is attached to this instance.", + Type: schema.TypeString, }, - "ipoctet": { - Type: schema.TypeString, - Computed: true, + Attr_IP: { + Computed: true, + Description: "The IP address that is attached to this instance from the subnet.", + Type: schema.TypeString, }, - "macaddress": { - Type: schema.TypeString, - Computed: true, + Attr_IPOctet: { + Computed: true, + Description: "The IP octet of the network that is attached to this instance.", + Type: schema.TypeString, }, - "network_id": { - Type: schema.TypeString, - Computed: true, + Attr_MacAddress: { + Computed: true, + Description: "The MAC address of the network that is attached to this instance.", + Type: schema.TypeString, }, - "type": { - Type: schema.TypeString, - Computed: true, + Attr_NetworkID: { + Computed: true, + Description: "ID of the network.", + Type: schema.TypeString, }, - "external_ip": { - Type: schema.TypeString, - Computed: true, + Attr_Type: { + Computed: true, + Description: "The type of the network that is attached to this instance.", + Type: schema.TypeString, }, }, } @@ -74,11 +81,11 @@ func dataSourceIBMPIInstancesIPRead(ctx context.Context, d *schema.ResourceData, return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - networkName := d.Get(helpers.PINetworkName).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) + networkName := d.Get(Arg_NetworkName).(string) powerC := instance.NewIBMPIInstanceClient(ctx, sess, cloudInstanceID) - powervmdata, err := powerC.Get(d.Get(helpers.PIInstanceName).(string)) + powervmdata, err := powerC.Get(d.Get(Arg_InstanceName).(string)) if err != nil { return diag.FromErr(err) } @@ -87,17 +94,16 @@ func dataSourceIBMPIInstancesIPRead(ctx context.Context, d *schema.ResourceData, if network.NetworkName == networkName { log.Printf("Printing the ip %s", network.IPAddress) d.SetId(network.NetworkID) - d.Set("ip", network.IPAddress) - d.Set("network_id", network.NetworkID) - d.Set("macaddress", network.MacAddress) - d.Set("external_ip", network.ExternalIP) - d.Set("type", network.Type) + d.Set(Attr_ExternalIP, network.ExternalIP) + d.Set(Attr_IP, network.IPAddress) + d.Set(Attr_MacAddress, network.MacAddress) + d.Set(Attr_NetworkID, network.NetworkID) + d.Set(Attr_Type, network.Type) IPObject := net.ParseIP(network.IPAddress).To4() if len(IPObject) > 0 { - d.Set("ipoctet", strconv.Itoa(int(IPObject[3]))) + d.Set(Attr_IPOctet, strconv.Itoa(int(IPObject[3]))) } - return nil } } diff --git a/ibm/service/power/data_source_ibm_pi_instance_ip_test.go b/ibm/service/power/data_source_ibm_pi_instance_ip_test.go index 36362776a8..b8963ee639 100644 --- a/ibm/service/power/data_source_ibm_pi_instance_ip_test.go +++ b/ibm/service/power/data_source_ibm_pi_instance_ip_test.go @@ -29,10 +29,9 @@ func TestAccIBMPIInstanceIPDataSource_basic(t *testing.T) { func testAccCheckIBMPIInstanceIPDataSourceConfig() string { return fmt.Sprintf(` - data "ibm_pi_instance_ip" "testacc_ds_instance_ip" { - pi_network_name = "%[1]s" - pi_instance_name = "%[2]s" - pi_cloud_instance_id = "%[3]s" - } - `, acc.Pi_network_name, acc.Pi_instance_name, acc.Pi_cloud_instance_id) + data "ibm_pi_instance_ip" "testacc_ds_instance_ip" { + pi_network_name = "%[1]s" + pi_instance_name = "%[2]s" + pi_cloud_instance_id = "%[3]s" + }`, acc.Pi_network_name, acc.Pi_instance_name, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/data_source_ibm_pi_instance_volumes.go b/ibm/service/power/data_source_ibm_pi_instance_volumes.go index 611ef5cf62..0bd9b2a09e 100644 --- a/ibm/service/power/data_source_ibm_pi_instance_volumes.go +++ b/ibm/service/power/data_source_ibm_pi_instance_volumes.go @@ -6,82 +6,92 @@ package power import ( "context" - "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM-Cloud/power-go-client/clients/instance" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func DataSourceIBMPIInstanceVolumes() *schema.Resource { - return &schema.Resource{ ReadContext: dataSourceIBMPIInstanceVolumesRead, Schema: map[string]*schema.Schema{ - helpers.PIInstanceName: { - Type: schema.TypeString, + // Arguments + Arg_CloudInstanceID: { + Description: "The GUID of the service instance associated with an account.", Required: true, - Description: "Instance Name to be used for pvminstances", + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - helpers.PICloudInstanceId: { - Type: schema.TypeString, + Arg_InstanceName: { + Description: "The unique identifier or name of the instance.", Required: true, + Type: schema.TypeString, ValidateFunc: validation.NoZeroValues, }, - //Computed Attributes - "boot_volume_id": { - Type: schema.TypeString, - Computed: true, + // Attribute + Attr_BootVolumeID: { + Computed: true, + Description: "The unique identifier of the boot volume.", + Type: schema.TypeString, }, - "instance_volumes": { - Type: schema.TypeList, - Computed: true, + Attr_InstanceVolumes: { + Computed: true, + Description: "List of volumes attached to instance.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, + Attr_Bootable: { + Computed: true, + Description: "Indicates if the volume is boot capable.", + Type: schema.TypeBool, }, - "size": { - Type: schema.TypeFloat, - Computed: true, + Attr_Href: { + Computed: true, + Description: "The hyper link of the volume.", + Type: schema.TypeString, }, - "href": { - Type: schema.TypeString, - Computed: true, + Attr_ID: { + Computed: true, + Description: "The unique identifier of the volume.", + Type: schema.TypeString, }, - "name": { - Type: schema.TypeString, - Computed: true, + Attr_Name: { + Computed: true, + Description: "The name of the volume.", + Type: schema.TypeString, }, - "state": { - Type: schema.TypeString, - Computed: true, + Attr_Pool: { + Computed: true, + Description: "Volume pool, name of storage pool where the volume is located.", + Type: schema.TypeString, }, - "type": { - Type: schema.TypeString, - Computed: true, + Attr_Shareable: { + Computed: true, + Description: "Indicates if the volume is shareable between VMs.", + Type: schema.TypeBool, }, - "pool": { - Type: schema.TypeString, - Computed: true, + Attr_Size: { + Computed: true, + Description: "The size of this volume in gigabytes.", + Type: schema.TypeFloat, }, - "shareable": { - Type: schema.TypeBool, - Computed: true, + Attr_State: { + Computed: true, + Description: "The state of the volume.", + Type: schema.TypeString, }, - "bootable": { - Type: schema.TypeBool, - Computed: true, + Attr_Type: { + Computed: true, + Description: "The disk type that is used for this volume.", + Type: schema.TypeString, }, }, }, + Type: schema.TypeList, }, }, } @@ -93,38 +103,36 @@ func dataSourceIBMPIInstanceVolumesRead(ctx context.Context, d *schema.ResourceD return diag.FromErr(err) } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) + cloudInstanceID := d.Get(Arg_CloudInstanceID).(string) volumeC := instance.NewIBMPIVolumeClient(ctx, sess, cloudInstanceID) - volumedata, err := volumeC.GetAllInstanceVolumes(d.Get(helpers.PIInstanceName).(string)) + volumedata, err := volumeC.GetAllInstanceVolumes(d.Get(Arg_InstanceName).(string)) if err != nil { return diag.FromErr(err) } var clientgenU, _ = uuid.GenerateUUID() d.SetId(clientgenU) - d.Set("boot_volume_id", *volumedata.Volumes[0].VolumeID) - d.Set("instance_volumes", flattenVolumesInstances(volumedata.Volumes)) + d.Set(Attr_BootVolumeID, *volumedata.Volumes[0].VolumeID) + d.Set(Attr_InstanceVolumes, flattenVolumesInstances(volumedata.Volumes)) return nil - } func flattenVolumesInstances(list []*models.VolumeReference) []map[string]interface{} { result := make([]map[string]interface{}, 0, len(list)) for _, i := range list { l := map[string]interface{}{ - "id": *i.VolumeID, - "state": *i.State, - "href": *i.Href, - "name": *i.Name, - "size": *i.Size, - "type": *i.DiskType, - "pool": i.VolumePool, - "shareable": *i.Shareable, - "bootable": *i.Bootable, + Attr_Bootable: *i.Bootable, + Attr_Href: *i.Href, + Attr_ID: *i.VolumeID, + Attr_Name: *i.Name, + Attr_Pool: i.VolumePool, + Attr_Shareable: *i.Shareable, + Attr_Size: *i.Size, + Attr_State: *i.State, + Attr_Type: *i.DiskType, } - result = append(result, l) } return result diff --git a/ibm/service/power/data_source_ibm_pi_instance_volumes_test.go b/ibm/service/power/data_source_ibm_pi_instance_volumes_test.go index 211c17b9e7..10543c5a66 100644 --- a/ibm/service/power/data_source_ibm_pi_instance_volumes_test.go +++ b/ibm/service/power/data_source_ibm_pi_instance_volumes_test.go @@ -31,9 +31,8 @@ func TestAccIBMPIVolumesDataSource_basic(t *testing.T) { func testAccCheckIBMPIVolumesDataSourceConfig(name string) string { return fmt.Sprintf(` -data "ibm_pi_instance_volumes" "testacc_ds_volumes" { - pi_instance_name = "%s" - pi_cloud_instance_id = "%s" -}`, acc.Pi_instance_name, acc.Pi_cloud_instance_id) - + data "ibm_pi_instance_volumes" "testacc_ds_volumes" { + pi_instance_name = "%s" + pi_cloud_instance_id = "%s" + }`, acc.Pi_instance_name, acc.Pi_cloud_instance_id) } diff --git a/ibm/service/power/ibm_pi_constants.go b/ibm/service/power/ibm_pi_constants.go index ab78b5d7b4..c790851491 100644 --- a/ibm/service/power/ibm_pi_constants.go +++ b/ibm/service/power/ibm_pi_constants.go @@ -277,9 +277,10 @@ const ( Attr_DhcpStatus = "status" // Instance - Arg_PVMInstanceId = "pi_instance_id" - Arg_PVMInstanceActionType = "pi_action" - Arg_PVMInstanceHealthStatus = "pi_health_status" + Arg_PVMInstanceId = "pi_instance_id" + Arg_PVMInstanceActionType = "pi_action" + Arg_PVMInstanceHealthStatus = "pi_health_status" + Arg_PIInstanceSharedProcessorPool = "pi_shared_processor_pool" PVMInstanceHealthOk = "OK" PVMInstanceHealthWarning = "WARNING" @@ -290,6 +291,7 @@ const ( // power service instance capabilities CUSTOM_VIRTUAL_CORES = "custom-virtualcores" + PIConsoleLanguageCode = "pi_language_code" PICloudConnectionId = "cloud_connection_id" PICloudConnectionStatus = "status" PICloudConnectionIBMIPAddress = "ibm_ip_address" @@ -314,7 +316,6 @@ const ( Attr_PIInstanceSharedProcessorPool = "shared_processor_pool" Attr_PIInstanceSharedProcessorPoolID = "shared_processor_pool_id" - Arg_PIInstanceSharedProcessorPool = "pi_shared_processor_pool" // Placement Group PIPlacementGroupID = "placement_group_id" diff --git a/ibm/service/power/resource_ibm_pi_instance_console_language.go b/ibm/service/power/resource_ibm_pi_instance_console_language.go index a825760d04..4f065a0a36 100644 --- a/ibm/service/power/resource_ibm_pi_instance_console_language.go +++ b/ibm/service/power/resource_ibm_pi_instance_console_language.go @@ -18,10 +18,6 @@ import ( "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" ) -const ( - PIConsoleLanguageCode = "pi_language_code" -) - func ResourceIBMPIInstanceConsoleLanguage() *schema.Resource { return &schema.Resource{ CreateContext: resourceIBMPIInstanceConsoleLanguageCreate, @@ -93,7 +89,7 @@ func resourceIBMPIInstanceConsoleLanguageUpdate(ctx context.Context, d *schema.R return diag.FromErr(err) } - if d.HasChange(ConsoleLanguageCode) { + if d.HasChange(PIConsoleLanguageCode) { cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) instanceName := d.Get(helpers.PIInstanceName).(string) code := d.Get(PIConsoleLanguageCode).(string) diff --git a/website/docs/d/pi_console_languages.html.markdown b/website/docs/d/pi_console_languages.html.markdown index d5f7f36afd..e679fedd62 100644 --- a/website/docs/d/pi_console_languages.html.markdown +++ b/website/docs/d/pi_console_languages.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_console_languages" @@ -8,11 +7,9 @@ description: |- --- # ibm_pi_console_languages - Retrieve information about all the available Console Languages for an Instance. For more information, see [getting started with IBM Power Systems Virtual Servers](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-getting-started). ## Example usage - ```terraform data "ibm_pi_console_languages" "example" { pi_cloud_instance_id = "" @@ -21,14 +18,12 @@ data "ibm_pi_console_languages" "example" { ``` **Notes** - -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` Example usage: - ```terraform provider "ibm" { region = "lon" @@ -37,14 +32,12 @@ Example usage: ``` ## Argument reference - Review the argument references that you can specify for your data source. - `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. - `pi_instance_name` - (Required, String) The unique identifier or name of the instance. ## Attribute reference - In addition to all argument reference list, you can access the following attribute references after your data source is created. - `console_languages` - (List) List of all the Console Languages. diff --git a/website/docs/d/pi_instance_ip.html.markdown b/website/docs/d/pi_instance_ip.html.markdown index 541891d09c..8f1942cc83 100644 --- a/website/docs/d/pi_instance_ip.html.markdown +++ b/website/docs/d/pi_instance_ip.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_instance_ip" @@ -11,7 +10,6 @@ description: |- Retrieve information about a Power Systems Virtual Server instance IP address. For more information, about Power Systems Virtual Server instance IP address, see [configuring and adding a private network subnet](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-configuring-subnet). ## Example usage - ```terraform data "ibm_pi_instance_ip" "ds_instance_ip" { pi_instance_name = "terraform-test-instance" @@ -19,12 +17,14 @@ data "ibm_pi_instance_ip" "ds_instance_ip" { pi_cloud_instance_id = "49fba6c9-23f8-40bc-9899-aca322ee7d5b" } ``` + **Notes** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - Example usage: +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` + +Example usage: ```terraform provider "ibm" { region = "lon" @@ -36,7 +36,7 @@ data "ibm_pi_instance_ip" "ds_instance_ip" { Review the argument references that you can specify for your data source. - `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. -- `pi_instance_name` - (Required, String) The name of the instance. +- `pi_instance_name` - (Required, String) The unique identifier or name of the instance. - `pi_network_name` - (Required, String) The subnet that the instance belongs to. diff --git a/website/docs/d/pi_instance_volumes.html.markdown b/website/docs/d/pi_instance_volumes.html.markdown index 1fc2583b2b..6c17530538 100644 --- a/website/docs/d/pi_instance_volumes.html.markdown +++ b/website/docs/d/pi_instance_volumes.html.markdown @@ -1,5 +1,4 @@ --- - subcategory: "Power Systems" layout: "ibm" page_title: "IBM: pi_instance_volumes" @@ -8,26 +7,25 @@ description: |- --- # ibm_pi_instance_volumes -Retrieves information about a persistent storage volume that is mounted to a Power Systems Virtual Server instance. For more information, about power instance volume, see [snapshotting, cloning, and restoring](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-volume-snapshot-clone). +Retrieves information about the persistent storage volumes that are mounted to a Power Systems Virtual Server instance. For more information, about power instance volume, see [snapshotting, cloning, and restoring](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-volume-snapshot-clone). ## Example usage -The following example retrieves information about the `volume_1` volume that is mounted to the Power Systems Virtual Server instance with the ID. +The following example retrieves information about the volumes attached to the `terraform-test-instance` instance. ```terraform data "ibm_pi_instance_volumes" "ds_volumes" { - pi_instance_name = "volume_1" + pi_instance_name = "terraform-test-instance" pi_cloud_instance_id = "49fba6c9-23f8-40bc-9899-aca322ee7d5b" } ``` **Notes** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - - Example usage: +- Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. +- If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: + - `region` - `lon` + - `zone` - `lon04` +Example usage: ```terraform provider "ibm" { region = "lon" @@ -39,21 +37,21 @@ data "ibm_pi_instance_volumes" "ds_volumes" { Review the argument references that you can specify for your data source. - `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. -- `pi_volume_name` - (Required, String) The name of the volume for which you want to retrieve detailed information. +- `pi_instance_name` - (Required, String) The unique identifier or name of the instance. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. - `boot_volume_id` - (String) The unique identifier of the boot volume. -- `instance_volumes` - List of volumes - List of volumes attached to instance. +- `instance_volumes` - (List) List of volumes attached to instance. Nested scheme for `instance_volumes`: - - `bootable`- (Bool) Indicates if the volume is boot capable. + - `bootable`- (Boolean) Indicates if the volume is boot capable. - `href` - (String) The hyper link of the volume. - `id` - (String) The unique identifier of the volume. - `name` - (String) The name of the volume. - `pool` - (String) Volume pool, name of storage pool where the volume is located. - - `shareable` - (Bool) Indicates if the volume is shareable between VMs. + - `shareable` - (Boolean) Indicates if the volume is shareable between VMs. - `size` - (Integer) The size of this volume in gigabytes. - `state` - (String) The state of the volume. - `type` - (String) The disk type that is used for this volume. From 134c7bd28276fdd8ae4b766f5e13e518414b0d5b Mon Sep 17 00:00:00 2001 From: Deepak Selvakumar <77007253+deepaksibm@users.noreply.github.com> Date: Thu, 1 Feb 2024 15:35:25 +0530 Subject: [PATCH 30/34] docs(is-vpn-gateways): Remove status attribute from docs for vpngateway resources and data sources status field is removed from the API post API version 2023-10-10 --- website/docs/d/is_vpn_gateway.html.markdown | 2 -- website/docs/d/is_vpn_gateways.html.markdown | 2 -- website/docs/r/is_vpn_gateway.html.markdown | 2 -- 3 files changed, 6 deletions(-) diff --git a/website/docs/d/is_vpn_gateway.html.markdown b/website/docs/d/is_vpn_gateway.html.markdown index da67f40b90..12ee7f6fcf 100644 --- a/website/docs/d/is_vpn_gateway.html.markdown +++ b/website/docs/d/is_vpn_gateway.html.markdown @@ -65,7 +65,6 @@ In addition to all argument references listed, you can access the following attr - `private_ip_address` - (String) The private IP address assigned to the VPN gateway member. This property will be present only when the VPN gateway status is `available`. This property may add support for IPv6 addresses in the future. When processing a value in this property, verify that the address is in an expected format. If it is not, log an error. Optionally halt processing and surface the error, or bypass the resource on which the unexpected IP address format was encountered. Same as `primary_ip.0.address` - `public_ip_address` - (String) The public IP address assigned to the VPN gateway member. This property may add support for IPv6 addresses in the future. When processing a value in this property, verify that the address is in an expected format. If it is not, log an error. Optionally halt processing and surface the error, or bypass the resource on which the unexpected IP address format was encountered. - `role` - (String) The high availability role assigned to the VPN gateway member. - - `status` - (String) The status of the VPN gateway member. - `mode` - (String) Route mode VPN gateway. @@ -79,7 +78,6 @@ In addition to all argument references listed, you can access the following attr - `resource_type` - (String) The resource type. -- `status` - (String) The status of the VPN gateway. - `health_reasons` - (List) The reasons for the current health_state (if any). Nested scheme for `health_reasons`: diff --git a/website/docs/d/is_vpn_gateways.html.markdown b/website/docs/d/is_vpn_gateways.html.markdown index 8c7a66df30..457edbcfc7 100644 --- a/website/docs/d/is_vpn_gateways.html.markdown +++ b/website/docs/d/is_vpn_gateways.html.markdown @@ -56,11 +56,9 @@ In addition to all argument reference list, you can access the following attribu Nested scheme for `private_ip`: - `address` - (String) The IP address. If the address has not yet been selected, the value will be 0.0.0.0. This property may add support for IPv6 addresses in the future. When processing a value in this property, verify that the address is in an expected format. If it is not, log an error. Optionally halt processing and surface the error, or bypass the resource on which the unexpected IP address format was encountered. - `private_address` - (String) The private IP address assigned to the VPN gateway member. Same as `private_ip.0.address`.
- - `status` - (String) The status of the VPN gateway member. - `resource_type` - (String) The resource type, supported value is `vpn_gateway`. - - `status` - (String) The status of the VPN gateway, supported values are **available**, **deleting**, **failed**, **pending**. - `health_reasons` - (List) The reasons for the current health_state (if any). Nested scheme for `health_reasons`: diff --git a/website/docs/r/is_vpn_gateway.html.markdown b/website/docs/r/is_vpn_gateway.html.markdown index e5b632a5a9..a0e030c34d 100644 --- a/website/docs/r/is_vpn_gateway.html.markdown +++ b/website/docs/r/is_vpn_gateway.html.markdown @@ -74,12 +74,10 @@ In addition to all argument reference list, you can access the following attribu - `address` - (String) The public IP address assigned to the VPN gateway member. - `private_address` - (String) The private IP address assigned to the VPN gateway member. - `role` - (String) The high availability role assigned to the VPN gateway member. - - `status` - (String) The status of the VPN gateway member. - `public_ip_address` - (String) The IP address assigned to this VPN gateway. - `public_ip_address2` - (String) The Second Public IP address assigned to this VPN gateway member. - `private_ip_address` - (String) The Private IP address assigned to this VPN gateway member. - `private_ip_address2` - (String) The Second Private IP address assigned to this VPN gateway. -- `status` - (String) The status of the VPN gateway. Supported values are **available**, **deleting**, **failed**, or **pending**. - `health_reasons` - (List) The reasons for the current health_state (if any). Nested scheme for `health_reasons`: From d24bb7286600d53b846fb13b273509e5f60b0b2c Mon Sep 17 00:00:00 2001 From: davedcosta Date: Mon, 12 Feb 2024 03:49:56 -0500 Subject: [PATCH 31/34] Adding OpenPages as part of UX030 (#5051) * add openpages service * fix comments and add sample data parameter * fix readme sample data example --- examples/ibm-openpages/README.md | 58 +++++++++++++++++++ examples/ibm-openpages/main.tf | 23 ++++++++ examples/ibm-openpages/provider.tf | 4 ++ examples/ibm-openpages/terraform.tfvars | 4 ++ examples/ibm-openpages/variables.tf | 10 ++++ examples/ibm-openpages/versions.tf | 7 +++ .../docs/r/resource_instance.html.markdown | 27 +++++++++ 7 files changed, 133 insertions(+) create mode 100644 examples/ibm-openpages/README.md create mode 100644 examples/ibm-openpages/main.tf create mode 100644 examples/ibm-openpages/provider.tf create mode 100644 examples/ibm-openpages/terraform.tfvars create mode 100644 examples/ibm-openpages/variables.tf create mode 100644 examples/ibm-openpages/versions.tf diff --git a/examples/ibm-openpages/README.md b/examples/ibm-openpages/README.md new file mode 100644 index 0000000000..4372bfdf17 --- /dev/null +++ b/examples/ibm-openpages/README.md @@ -0,0 +1,58 @@ +# OpenPages example + +This example shows 1 usage scenario. + +#### Scenario 1: Create an OpenPages service instance. + +```terraform +resource "ibm_resource_instance" "openpages_instance" { + name = "terraform-automation" + service = "openpages" + plan = "essentials" + location = "global" + resource_group_id = data.ibm_resource_group.default_group.id + parameters_json = < Date: Tue, 13 Feb 2024 14:44:05 +0530 Subject: [PATCH 32/34] fix: add vpe_service_endpoint_url output --- .../data_source_ibm_container_vpc_cluster.go | 6 +++++- .../kubernetes/resource_ibm_container_vpc_cluster.go | 6 ++++++ metadata/provider_metadata.json | 10 ++++++++++ website/docs/d/container_vpc_cluster.html.markdown | 1 + website/docs/r/container_vpc_cluster.html.markdown | 1 + 5 files changed, 23 insertions(+), 1 deletion(-) diff --git a/ibm/service/kubernetes/data_source_ibm_container_vpc_cluster.go b/ibm/service/kubernetes/data_source_ibm_container_vpc_cluster.go index fe7e3edff9..ae7629020d 100644 --- a/ibm/service/kubernetes/data_source_ibm_container_vpc_cluster.go +++ b/ibm/service/kubernetes/data_source_ibm_container_vpc_cluster.go @@ -252,7 +252,10 @@ func DataSourceIBMContainerVPCCluster() *schema.Resource { Type: schema.TypeString, Computed: true, }, - + "vpe_service_endpoint_url": { + Type: schema.TypeString, + Computed: true, + }, "crn": { Type: schema.TypeString, Computed: true, @@ -395,6 +398,7 @@ func dataSourceIBMContainerClusterVPCRead(d *schema.ResourceData, meta interface d.Set("resource_group_id", cls.ResourceGroupID) d.Set("public_service_endpoint_url", cls.ServiceEndpoints.PublicServiceEndpointURL) d.Set("private_service_endpoint_url", cls.ServiceEndpoints.PrivateServiceEndpointURL) + d.Set("vpe_service_endpoint_url", cls.VirtualPrivateEndpointURL) d.Set("public_service_endpoint", cls.ServiceEndpoints.PublicServiceEndpointEnabled) d.Set("private_service_endpoint", cls.ServiceEndpoints.PrivateServiceEndpointEnabled) d.Set("ingress_hostname", cls.Ingress.HostName) diff --git a/ibm/service/kubernetes/resource_ibm_container_vpc_cluster.go b/ibm/service/kubernetes/resource_ibm_container_vpc_cluster.go index 3371e491ab..b1221f5572 100644 --- a/ibm/service/kubernetes/resource_ibm_container_vpc_cluster.go +++ b/ibm/service/kubernetes/resource_ibm_container_vpc_cluster.go @@ -415,6 +415,11 @@ func ResourceIBMContainerVpcCluster() *schema.Resource { Computed: true, }, + "vpe_service_endpoint_url": { + Type: schema.TypeString, + Computed: true, + }, + "crn": { Type: schema.TypeString, Computed: true, @@ -984,6 +989,7 @@ func resourceIBMContainerVpcClusterRead(d *schema.ResourceData, meta interface{} d.Set("resource_group_id", cls.ResourceGroupID) d.Set("public_service_endpoint_url", cls.ServiceEndpoints.PublicServiceEndpointURL) d.Set("private_service_endpoint_url", cls.ServiceEndpoints.PrivateServiceEndpointURL) + d.Set("vpe_service_endpoint_url", cls.VirtualPrivateEndpointURL) if cls.ServiceEndpoints.PublicServiceEndpointEnabled { d.Set("disable_public_service_endpoint", false) } else { diff --git a/metadata/provider_metadata.json b/metadata/provider_metadata.json index 35b141da83..0265de7132 100644 --- a/metadata/provider_metadata.json +++ b/metadata/provider_metadata.json @@ -19792,6 +19792,11 @@ "type": "TypeString", "computed": true }, + { + "name": "vpe_service_endpoint_url", + "type": "TypeString", + "computed": true + }, { "name": "tags", "type": "TypeSet", @@ -107563,6 +107568,11 @@ "type": "TypeString", "computed": true }, + { + "name": "vpe_service_endpoint_url", + "type": "TypeString", + "computed": true + }, { "name": "disable_public_service_endpoint", "type": "TypeBool", diff --git a/website/docs/d/container_vpc_cluster.html.markdown b/website/docs/d/container_vpc_cluster.html.markdown index 8408a34c0c..4cc27d261d 100644 --- a/website/docs/d/container_vpc_cluster.html.markdown +++ b/website/docs/d/container_vpc_cluster.html.markdown @@ -56,6 +56,7 @@ In addition to all argument reference list, you can access the following attribu - `public_service_endpoint_url` - (String) The URL of the public service endpoint for your cluster. - `private_service_endpoint` - (Bool) Indicates if the private service endpoint is enabled (**true**) or disabled (**false**) for a cluster. - `private_service_endpoint_url` - (String) The URL of the private service endpoint for your cluster. +- `vpe_service_endpoint_url` - (String) The URL of the virtual private endpoint for your cluster. - `status` - (String) The status of the cluster master. - `worker_count` - (Integer) The number of worker nodes per zone in the default worker pool. Default value ‘1’. - `workers` - List of objects - A list of worker nodes that belong to the cluster. diff --git a/website/docs/r/container_vpc_cluster.html.markdown b/website/docs/r/container_vpc_cluster.html.markdown index 921964b348..fc6c17109e 100644 --- a/website/docs/r/container_vpc_cluster.html.markdown +++ b/website/docs/r/container_vpc_cluster.html.markdown @@ -246,6 +246,7 @@ In addition to all argument reference list, you can access the following attribu - `master_status` - (String) The status of the Kubernetes master. - `master_url` - (String) The URL of the Kubernetes master. - `private_service_endpoint_url` - (String) The private service endpoint URL. +- `vpe_service_endpoint_url` - (String) The virtual private endpoint URL. - `public_service_endpoint_url` - (String) The public service endpoint URL. - `state` - (String) The state of the VPC cluster. From 4871a8c7735e18974f2e1de3d0f80cf5962799ec Mon Sep 17 00:00:00 2001 From: ismirlia <90468712+ismirlia@users.noreply.github.com> Date: Tue, 13 Feb 2024 07:32:59 -0600 Subject: [PATCH 33/34] Remove old deprecated features from terraform (#5049) * Refactor deprecated fields and messages Deprecated fields and messages are wildly inconsistent. Several deprecated fields are not marked as such and the documention is not laid out consistently. This commit should bring them all in line. * Remove deprecated fields from dhcp(s) data source and resource * Remove deprecated fields for instance data source and resource * Remove deprecated fields for key data source and resource * Update deprecated field for network data source and resource * Remove deprecated field for network port attach data resource * Remove deprecated fields for snapshot resource * Remove deprecated ibm_pi_network_port resource * Remove deprecated network port resource from provider --- ibm/provider/provider.go | 1 - ibm/service/power/data_source_ibm_pi_dhcp.go | 6 - ibm/service/power/data_source_ibm_pi_dhcps.go | 6 - .../power/data_source_ibm_pi_instance.go | 48 ---- ibm/service/power/resource_ibm_pi_dhcp.go | 6 - ibm/service/power/resource_ibm_pi_instance.go | 29 +-- ibm/service/power/resource_ibm_pi_key.go | 6 - ibm/service/power/resource_ibm_pi_network.go | 12 +- .../power/resource_ibm_pi_network_port.go | 211 ------------------ .../resource_ibm_pi_network_port_attach.go | 6 - .../resource_ibm_pi_network_port_test.go | 109 --------- ibm/service/power/resource_ibm_pi_snapshot.go | 16 -- website/docs/d/pi_dhcp.html.markdown | 1 - website/docs/d/pi_dhcps.html.markdown | 1 - website/docs/d/pi_instance.html.markdown | 9 - website/docs/r/pi_dhcp.html.markdown | 1 - website/docs/r/pi_instance.html.markdown | 1 - website/docs/r/pi_key.html.markdown | 1 - website/docs/r/pi_network.html.markdown | 2 +- website/docs/r/pi_network_port.html.markdown | 75 ------- .../r/pi_network_port_attach.html.markdown | 3 +- website/docs/r/pi_snapshot.html.markdown | 4 +- 22 files changed, 11 insertions(+), 543 deletions(-) delete mode 100644 ibm/service/power/resource_ibm_pi_network_port.go delete mode 100644 ibm/service/power/resource_ibm_pi_network_port_test.go delete mode 100644 website/docs/r/pi_network_port.html.markdown diff --git a/ibm/provider/provider.go b/ibm/provider/provider.go index 9f5ff9a6e8..2b6d711a14 100644 --- a/ibm/provider/provider.go +++ b/ibm/provider/provider.go @@ -1174,7 +1174,6 @@ func Provider() *schema.Provider { "ibm_pi_capture": power.ResourceIBMPICapture(), "ibm_pi_image": power.ResourceIBMPIImage(), "ibm_pi_image_export": power.ResourceIBMPIImageExport(), - "ibm_pi_network_port": power.ResourceIBMPINetworkPort(), "ibm_pi_snapshot": power.ResourceIBMPISnapshot(), "ibm_pi_network_port_attach": power.ResourceIBMPINetworkPortAttach(), "ibm_pi_dhcp": power.ResourceIBMPIDhcp(), diff --git a/ibm/service/power/data_source_ibm_pi_dhcp.go b/ibm/service/power/data_source_ibm_pi_dhcp.go index c6e716c020..b42bbc98dc 100644 --- a/ibm/service/power/data_source_ibm_pi_dhcp.go +++ b/ibm/service/power/data_source_ibm_pi_dhcp.go @@ -60,11 +60,6 @@ func DataSourceIBMPIDhcp() *schema.Resource { }, }, }, - Attr_DhcpNetworkDeprecated: { - Type: schema.TypeString, - Computed: true, - Description: "The ID of the DHCP Server private network (deprecated - replaced by network_id)", - }, Attr_DhcpNetworkID: { Type: schema.TypeString, Computed: true, @@ -114,7 +109,6 @@ func dataSourceIBMPIDhcpRead(ctx context.Context, d *schema.ResourceData, meta i if dhcpServer.Network != nil { dhcpNetwork := dhcpServer.Network if dhcpNetwork.ID != nil { - d.Set(Attr_DhcpNetworkDeprecated, *dhcpNetwork.ID) d.Set(Attr_DhcpNetworkID, *dhcpNetwork.ID) } if dhcpNetwork.Name != nil { diff --git a/ibm/service/power/data_source_ibm_pi_dhcps.go b/ibm/service/power/data_source_ibm_pi_dhcps.go index a95f1935b5..79c2586dae 100644 --- a/ibm/service/power/data_source_ibm_pi_dhcps.go +++ b/ibm/service/power/data_source_ibm_pi_dhcps.go @@ -45,11 +45,6 @@ func DataSourceIBMPIDhcps() *schema.Resource { Computed: true, Description: "The ID of the DHCP Server", }, - Attr_DhcpNetworkDeprecated: { - Type: schema.TypeString, - Computed: true, - Description: "The ID of the DHCP Server private network (deprecated - replaced by network_id)", - }, Attr_DhcpNetworkID: { Type: schema.TypeString, Computed: true, @@ -103,7 +98,6 @@ func dataSourceIBMPIDhcpServersRead(ctx context.Context, d *schema.ResourceData, if dhcpServer.Network != nil { dhcpNetwork := dhcpServer.Network if dhcpNetwork.ID != nil { - d.Set(Attr_DhcpNetworkDeprecated, *dhcpNetwork.ID) d.Set(Attr_DhcpNetworkID, *dhcpNetwork.ID) } if dhcpNetwork.Name != nil { diff --git a/ibm/service/power/data_source_ibm_pi_instance.go b/ibm/service/power/data_source_ibm_pi_instance.go index 354cfe951b..31317b561f 100644 --- a/ibm/service/power/data_source_ibm_pi_instance.go +++ b/ibm/service/power/data_source_ibm_pi_instance.go @@ -52,39 +52,6 @@ func DataSourceIBMPIInstance() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "addresses": { - Type: schema.TypeList, - Computed: true, - Deprecated: "This field is deprecated, use networks instead", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ip": { - Type: schema.TypeString, - Computed: true, - }, - "macaddress": { - Type: schema.TypeString, - Computed: true, - }, - "network_id": { - Type: schema.TypeString, - Computed: true, - }, - "network_name": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - "external_ip": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, "networks": { Type: schema.TypeList, Computed: true, @@ -243,21 +210,6 @@ func dataSourceIBMPIInstancesRead(ctx context.Context, d *schema.ResourceData, m d.Set(Attr_PIInstanceSharedProcessorPool, powervmdata.SharedProcessorPool) d.Set(Attr_PIInstanceSharedProcessorPoolID, powervmdata.SharedProcessorPoolID) - if powervmdata.Addresses != nil { - pvmaddress := make([]map[string]interface{}, len(powervmdata.Addresses)) - for i, pvmip := range powervmdata.Addresses { - p := make(map[string]interface{}) - p["ip"] = pvmip.IPAddress - p["network_name"] = pvmip.NetworkName - p["network_id"] = pvmip.NetworkID - p["macaddress"] = pvmip.MacAddress - p["type"] = pvmip.Type - p["external_ip"] = pvmip.ExternalIP - pvmaddress[i] = p - } - d.Set("addresses", pvmaddress) - } - if powervmdata.Health != nil { d.Set("health_status", powervmdata.Health.Status) } diff --git a/ibm/service/power/resource_ibm_pi_dhcp.go b/ibm/service/power/resource_ibm_pi_dhcp.go index c4d1d96532..071b3d80ad 100644 --- a/ibm/service/power/resource_ibm_pi_dhcp.go +++ b/ibm/service/power/resource_ibm_pi_dhcp.go @@ -98,11 +98,6 @@ func ResourceIBMPIDhcp() *schema.Resource { }, }, }, - Attr_DhcpNetworkDeprecated: { - Type: schema.TypeString, - Computed: true, - Description: "The ID of the DHCP Server private network (deprecated - replaced by network_id)", - }, Attr_DhcpNetworkID: { Type: schema.TypeString, Computed: true, @@ -210,7 +205,6 @@ func resourceIBMPIDhcpRead(ctx context.Context, d *schema.ResourceData, meta int if dhcpServer.Network != nil { dhcpNetwork := dhcpServer.Network if dhcpNetwork.ID != nil { - d.Set(Attr_DhcpNetworkDeprecated, *dhcpNetwork.ID) d.Set(Attr_DhcpNetworkID, *dhcpNetwork.ID) } if dhcpNetwork.Name != nil { diff --git a/ibm/service/power/resource_ibm_pi_instance.go b/ibm/service/power/resource_ibm_pi_instance.go index d48834dc25..882583b071 100644 --- a/ibm/service/power/resource_ibm_pi_instance.go +++ b/ibm/service/power/resource_ibm_pi_instance.go @@ -56,12 +56,6 @@ func ResourceIBMPIInstance() *schema.Resource { Computed: true, Description: "PI instance status", }, - "pi_migratable": { - Type: schema.TypeBool, - Optional: true, - Computed: true, - Description: "set to true to enable migration of the PI instance", - }, "min_processors": { Type: schema.TypeFloat, Computed: true, @@ -319,12 +313,6 @@ func ResourceIBMPIInstance() *schema.Resource { Default: "none", ValidateFunc: validate.ValidateAllowedStringValues([]string{"none", "soft", "hard"}), }, - - // "reboot_for_resource_change": { - // Type: schema.TypeString, - // Optional: true, - // Description: "Flag to be passed for CPU/Memory changes that require a reboot to take effect", - // }, "operating_system": { Type: schema.TypeString, Computed: true, @@ -441,9 +429,6 @@ func resourceIBMPIInstanceRead(ctx context.Context, d *schema.ResourceData, meta d.Set("status", powervmdata.Status) } d.Set(helpers.PIInstanceProcType, powervmdata.ProcType) - if powervmdata.Migratable != nil { - d.Set("pi_migratable", powervmdata.Migratable) - } d.Set("min_processors", powervmdata.Minproc) d.Set(helpers.PIInstanceProgress, powervmdata.Progress) if powervmdata.StorageType != nil { @@ -604,7 +589,7 @@ func resourceIBMPIInstanceUpdate(ctx context.Context, d *schema.ResourceData, me } // Start of the change for Memory and Processors - if d.HasChange(helpers.PIInstanceMemory) || d.HasChange(helpers.PIInstanceProcessors) || d.HasChange("pi_migratable") { + if d.HasChange(helpers.PIInstanceMemory) || d.HasChange(helpers.PIInstanceProcessors) { maxMemLpar := d.Get("max_memory").(float64) maxCPULpar := d.Get("max_processors").(float64) @@ -633,10 +618,6 @@ func resourceIBMPIInstanceUpdate(ctx context.Context, d *schema.ResourceData, me Memory: mem, Processors: procs, } - if m, ok := d.GetOk("pi_migratable"); ok { - migratable := m.(bool) - body.Migratable = &migratable - } if cores_enabled { log.Printf("support for %s is enabled", CUSTOM_VIRTUAL_CORES) body.VirtualCores = &models.VirtualCores{Assigned: &assignedVirtualCores} @@ -1190,11 +1171,6 @@ func createPVMInstance(d *schema.ResourceData, client *st.IBMPIInstanceClient, i if r, ok := d.GetOk(helpers.PIInstanceReplicationScheme); ok { replicationNamingScheme = r.(string) } - var migratable bool - if m, ok := d.GetOk("pi_migratable"); ok { - migratable = m.(bool) - } - var pinpolicy string if p, ok := d.GetOk(helpers.PIInstancePinPolicy); ok { pinpolicy = p.(string) @@ -1208,9 +1184,7 @@ func createPVMInstance(d *schema.ResourceData, client *st.IBMPIInstanceClient, i userData = u.(string) } - //publicinterface := d.Get(helpers.PIInstancePublicNetwork).(bool) body := &models.PVMInstanceCreate{ - //NetworkIds: networks, Processors: &procs, Memory: &mem, ServerName: flex.PtrToString(name), @@ -1222,7 +1196,6 @@ func createPVMInstance(d *schema.ResourceData, client *st.IBMPIInstanceClient, i ReplicantNamingScheme: flex.PtrToString(replicationNamingScheme), ReplicantAffinityPolicy: flex.PtrToString(replicationpolicy), Networks: pvmNetworks, - Migratable: &migratable, } if s, ok := d.GetOk(helpers.PIInstanceSSHKeyName); ok { sshkey := s.(string) diff --git a/ibm/service/power/resource_ibm_pi_key.go b/ibm/service/power/resource_ibm_pi_key.go index be0c542be2..0b691bb0f6 100644 --- a/ibm/service/power/resource_ibm_pi_key.go +++ b/ibm/service/power/resource_ibm_pi_key.go @@ -55,11 +55,6 @@ func ResourceIBMPIKey() *schema.Resource { Computed: true, Description: "Date of SSH Key creation", }, - Attr_KeyID: { - Type: schema.TypeString, - Computed: true, - Deprecated: "User defined name for the SSH key (deprecated - replaced by name)", - }, Attr_KeyName: { Type: schema.TypeString, Computed: true, @@ -127,7 +122,6 @@ func resourceIBMPIKeyRead(ctx context.Context, d *schema.ResourceData, meta inte // set attributes d.Set(Attr_KeyName, sshkeydata.Name) - d.Set(Attr_KeyID, sshkeydata.Name) d.Set(Attr_Key, sshkeydata.SSHKey) d.Set(Attr_CreationDate, sshkeydata.CreationDate.String()) diff --git a/ibm/service/power/resource_ibm_pi_network.go b/ibm/service/power/resource_ibm_pi_network.go index d6ad8826c6..941731b8fe 100644 --- a/ibm/service/power/resource_ibm_pi_network.go +++ b/ibm/service/power/resource_ibm_pi_network.go @@ -75,12 +75,12 @@ func ResourceIBMPINetwork() *schema.Resource { Description: "PI network gateway", }, helpers.PINetworkJumbo: { - Type: schema.TypeBool, - Optional: true, - Computed: true, - Deprecated: "deprecated use pi_network_mtu instead", - ConflictsWith: []string{helpers.PINetworkMtu}, - Description: "PI network enable MTU Jumbo option", + Type: schema.TypeBool, + Optional: true, + Computed: true, + Deprecated: "This field is deprecated, use pi_network_mtu instead.", + ConflictsWith: []string{helpers.PINetworkMtu, helpers.PINetworkJumbo}, + Description: "PI network enable MTU Jumbo option", }, helpers.PINetworkMtu: { Type: schema.TypeInt, diff --git a/ibm/service/power/resource_ibm_pi_network_port.go b/ibm/service/power/resource_ibm_pi_network_port.go deleted file mode 100644 index 6b1ffb0cf7..0000000000 --- a/ibm/service/power/resource_ibm_pi_network_port.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright IBM Corp. 2017, 2021 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package power - -import ( - "context" - "fmt" - "log" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" - "github.com/IBM-Cloud/power-go-client/helpers" - "github.com/IBM-Cloud/power-go-client/power/models" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" -) - -func ResourceIBMPINetworkPort() *schema.Resource { - return &schema.Resource{ - CreateContext: resourceIBMPINetworkPortCreate, - ReadContext: resourceIBMPINetworkPortRead, - UpdateContext: resourceIBMPINetworkPortUpdate, - DeleteContext: resourceIBMPINetworkPortDelete, - Importer: &schema.ResourceImporter{}, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(60 * time.Minute), - Delete: schema.DefaultTimeout(60 * time.Minute), - }, - - Schema: map[string]*schema.Schema{ - helpers.PINetworkName: { - Type: schema.TypeString, - Required: true, - }, - helpers.PICloudInstanceId: { - Type: schema.TypeString, - Required: true, - }, - helpers.PINetworkPortDescription: { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - helpers.PINetworkPortIPAddress: { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - //Computed Attributes - "macaddress": { - Type: schema.TypeString, - Computed: true, - }, - "portid": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "public_ip": { - Type: schema.TypeString, - Computed: true, - }, - }, - DeprecationMessage: "Resource ibm_pi_network_port is deprecated. Use ibm_pi_network_port_attach to create & attach a network port to a pvm instance", - } -} - -func resourceIBMPINetworkPortCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - sess, err := meta.(conns.ClientSession).IBMPISession() - if err != nil { - return diag.FromErr(err) - } - cloudInstanceID := d.Get(helpers.PICloudInstanceId).(string) - networkname := d.Get(helpers.PINetworkName).(string) - description := d.Get(helpers.PINetworkPortDescription).(string) - - ipaddress := d.Get(helpers.PINetworkPortIPAddress).(string) - - nwportBody := &models.NetworkPortCreate{Description: description} - - if ipaddress != "" { - log.Printf("IP address provided. ") - nwportBody.IPAddress = ipaddress - } - - client := st.NewIBMPINetworkClient(ctx, sess, cloudInstanceID) - - networkPortResponse, err := client.CreatePort(networkname, nwportBody) - if err != nil { - return diag.FromErr(err) - } - - log.Printf("Printing the networkresponse %+v", &networkPortResponse) - - IBMPINetworkPortID := *networkPortResponse.PortID - - d.SetId(fmt.Sprintf("%s/%s/%s", cloudInstanceID, networkname, IBMPINetworkPortID)) - - _, err = isWaitForIBMPINetworkPortAvailable(ctx, client, IBMPINetworkPortID, networkname, d.Timeout(schema.TimeoutCreate)) - if err != nil { - return diag.FromErr(err) - } - - return resourceIBMPINetworkPortRead(ctx, d, meta) -} - -func resourceIBMPINetworkPortRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - sess, err := meta.(conns.ClientSession).IBMPISession() - if err != nil { - return diag.FromErr(err) - } - - parts, err := flex.IdParts(d.Id()) - if err != nil { - return diag.FromErr(err) - } - cloudInstanceID := parts[0] - networkname := parts[1] - portID := parts[2] - - networkC := st.NewIBMPINetworkClient(ctx, sess, cloudInstanceID) - networkdata, err := networkC.GetPort(networkname, portID) - if err != nil { - return diag.FromErr(err) - } - - d.Set(helpers.PINetworkPortIPAddress, networkdata.IPAddress) - d.Set(helpers.PINetworkPortDescription, networkdata.Description) - d.Set("macaddress", networkdata.MacAddress) - d.Set("status", networkdata.Status) - d.Set("portid", networkdata.PortID) - d.Set("public_ip", networkdata.ExternalIP) - - return nil -} - -func resourceIBMPINetworkPortUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - return nil -} - -func resourceIBMPINetworkPortDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - - log.Printf("Calling the network delete functions. ") - sess, err := meta.(conns.ClientSession).IBMPISession() - if err != nil { - return diag.FromErr(err) - } - - parts, err := flex.IdParts(d.Id()) - if err != nil { - return diag.FromErr(err) - } - cloudInstanceID := parts[0] - networkname := parts[1] - portID := parts[2] - - client := st.NewIBMPINetworkClient(ctx, sess, cloudInstanceID) - - log.Printf("Calling the delete with the following params delete with cloud instance (%s) and networkid (%s) and portid (%s) ", cloudInstanceID, networkname, portID) - err = client.DeletePort(networkname, portID) - if err != nil { - return diag.FromErr(err) - } - - d.SetId("") - return nil -} - -func isWaitForIBMPINetworkPortAvailable(ctx context.Context, client *st.IBMPINetworkClient, id string, networkname string, timeout time.Duration) (interface{}, error) { - log.Printf("Waiting for Power Network (%s) that was created for Network Zone (%s) to be available.", id, networkname) - - stateConf := &resource.StateChangeConf{ - Pending: []string{"retry", helpers.PINetworkProvisioning}, - Target: []string{"DOWN"}, - Refresh: isIBMPINetworkPortRefreshFunc(client, id, networkname), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 10 * time.Minute, - } - - return stateConf.WaitForStateContext(ctx) -} - -func isIBMPINetworkPortRefreshFunc(client *st.IBMPINetworkClient, id, networkname string) resource.StateRefreshFunc { - - log.Printf("Calling the IsIBMPINetwork Refresh Function....with the following id (%s) for network port and following id (%s) for network name and waiting for network to be READY", id, networkname) - return func() (interface{}, string, error) { - network, err := client.GetPort(networkname, id) - if err != nil { - return nil, "", err - } - - if network.PortID != nil { - //if network.State == "available" { - log.Printf(" The port has been created with the following ip address and attached to an instance ") - return network, "DOWN", nil - } - - return network, helpers.PINetworkProvisioning, nil - } -} diff --git a/ibm/service/power/resource_ibm_pi_network_port_attach.go b/ibm/service/power/resource_ibm_pi_network_port_attach.go index b6dd305763..e0e342e15a 100644 --- a/ibm/service/power/resource_ibm_pi_network_port_attach.go +++ b/ibm/service/power/resource_ibm_pi_network_port_attach.go @@ -69,11 +69,6 @@ func ResourceIBMPINetworkPortAttach() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "port_id": { - Type: schema.TypeString, - Computed: true, - Deprecated: "port_id attribute is deprecated, use network_port_id instead.", - }, "network_port_id": { Type: schema.TypeString, Computed: true, @@ -169,7 +164,6 @@ func resourceIBMPINetworkPortAttachRead(ctx context.Context, d *schema.ResourceD d.Set("macaddress", networkdata.MacAddress) d.Set("status", networkdata.Status) d.Set("network_port_id", networkdata.PortID) - d.Set("port_id", networkdata.PortID) d.Set("public_ip", networkdata.ExternalIP) return nil diff --git a/ibm/service/power/resource_ibm_pi_network_port_test.go b/ibm/service/power/resource_ibm_pi_network_port_test.go deleted file mode 100644 index 65f72d7168..0000000000 --- a/ibm/service/power/resource_ibm_pi_network_port_test.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright IBM Corp. 2017, 2021 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package power_test - -import ( - "context" - "errors" - "fmt" - "testing" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - - st "github.com/IBM-Cloud/power-go-client/clients/instance" -) - -func TestAccIBMPINetworkPortbasic(t *testing.T) { - name := fmt.Sprintf("tf-pi-network-port-%d", acctest.RandIntRange(10, 100)) - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - CheckDestroy: testAccCheckIBMPINetworkPortDestroy, - Steps: []resource.TestStep{ - { - Config: testAccCheckIBMPINetworkPortConfig(name), - Check: resource.ComposeTestCheckFunc( - testAccCheckIBMPINetworkPortExists("ibm_pi_network_port.power_network_port"), - resource.TestCheckResourceAttr( - "ibm_pi_network_port.power_network_port", "pi_network_name", name), - ), - }, - }, - }) -} -func testAccCheckIBMPINetworkPortDestroy(s *terraform.State) error { - sess, err := acc.TestAccProvider.Meta().(conns.ClientSession).IBMPISession() - if err != nil { - return err - } - for _, rs := range s.RootModule().Resources { - if rs.Type != "ibm_pi_network_port" { - continue - } - parts, err := flex.IdParts(rs.Primary.ID) - if err != nil { - return err - } - cloudInstanceID := parts[0] - networkname := parts[1] - portID := parts[2] - networkC := st.NewIBMPINetworkClient(context.Background(), sess, cloudInstanceID) - _, err = networkC.GetPort(networkname, portID) - if err == nil { - return fmt.Errorf("PI Network Port still exists: %s", rs.Primary.ID) - } - } - - return nil -} -func testAccCheckIBMPINetworkPortExists(n string) resource.TestCheckFunc { - return func(s *terraform.State) error { - - rs, ok := s.RootModule().Resources[n] - - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - if rs.Primary.ID == "" { - return errors.New("No Record ID is set") - } - - sess, err := acc.TestAccProvider.Meta().(conns.ClientSession).IBMPISession() - if err != nil { - return err - } - parts, err := flex.IdParts(rs.Primary.ID) - if err != nil { - return err - } - cloudInstanceID := parts[0] - networkname := parts[1] - portID := parts[2] - client := st.NewIBMPINetworkClient(context.Background(), sess, cloudInstanceID) - - _, err = client.GetPort(networkname, portID) - if err != nil { - return err - } - return nil - - } -} - -func testAccCheckIBMPINetworkPortConfig(name string) string { - return testAccCheckIBMPINetworkConfig(name) + fmt.Sprintf(` - resource "ibm_pi_network_port" "power_network_port" { - pi_cloud_instance_id = "%s" - pi_network_name = ibm_pi_network.power_networks.pi_network_name - pi_network_port_description = "IP Reserved for Test UAT" - } - `, acc.Pi_cloud_instance_id) -} diff --git a/ibm/service/power/resource_ibm_pi_snapshot.go b/ibm/service/power/resource_ibm_pi_snapshot.go index 2372e889ed..17b75a371e 100644 --- a/ibm/service/power/resource_ibm_pi_snapshot.go +++ b/ibm/service/power/resource_ibm_pi_snapshot.go @@ -63,20 +63,8 @@ func ResourceIBMPISnapshot() *schema.Resource { Optional: true, Description: "Description of the PVM instance snapshot", }, - "description": { - Type: schema.TypeString, - Optional: true, - Description: "Snapshot description", - Deprecated: "This field is deprecated, use pi_description instead", - }, // Computed Attributes - helpers.PISnapshot: { - Type: schema.TypeString, - Computed: true, - Description: "Id of the snapshot", - Deprecated: "This field is deprecated, use snapshot_id instead", - }, "snapshot_id": { Type: schema.TypeString, Computed: true, @@ -114,9 +102,6 @@ func resourceIBMPISnapshotCreate(ctx context.Context, d *schema.ResourceData, me name := d.Get(helpers.PISnapshotName).(string) var description string - if v, ok := d.GetOk("description"); ok { - description = v.(string) - } if v, ok := d.GetOk("pi_description"); ok { description = v.(string) } @@ -167,7 +152,6 @@ func resourceIBMPISnapshotRead(ctx context.Context, d *schema.ResourceData, meta } d.Set(helpers.PISnapshotName, snapshotdata.Name) - d.Set(helpers.PISnapshot, *snapshotdata.SnapshotID) d.Set("snapshot_id", *snapshotdata.SnapshotID) d.Set("status", snapshotdata.Status) d.Set("creation_date", snapshotdata.CreationDate.String()) diff --git a/website/docs/d/pi_dhcp.html.markdown b/website/docs/d/pi_dhcp.html.markdown index cf6f1221d5..74a73de098 100644 --- a/website/docs/d/pi_dhcp.html.markdown +++ b/website/docs/d/pi_dhcp.html.markdown @@ -34,7 +34,6 @@ In addition to all argument reference list, you can access the following attribu Nested scheme for `leases`: - `instance_ip` - (String) The IP of the PVM Instance. - `instance_mac` - (String) The MAC Address of the PVM Instance. -- `network` - (String) The ID of the DHCP Server private network (deprecated - replaced by `network_id`). - `network_id`- (String) The ID of the DHCP Server private network. - `network_name` - The name of the DHCP Server private network. - `status` - (String) The status of the DHCP Server. diff --git a/website/docs/d/pi_dhcps.html.markdown b/website/docs/d/pi_dhcps.html.markdown index edc89f2dd5..1f0095f1d7 100644 --- a/website/docs/d/pi_dhcps.html.markdown +++ b/website/docs/d/pi_dhcps.html.markdown @@ -33,7 +33,6 @@ In addition to all argument reference list, you can access the following attribu Nested scheme for `servers`: - `dhcp_id` - (String) The ID of the DHCP Server. - - `network` - (String) The ID of the DHCP Server private network (deprecated - replaced by `network_id`). - `network_id`- (String) The ID of the DHCP Server private network. - `network_name` - The name of the DHCP Server private network. - `status` - (String) The status of the DHCP Server. diff --git a/website/docs/d/pi_instance.html.markdown b/website/docs/d/pi_instance.html.markdown index 75fecd8d53..bfef179346 100644 --- a/website/docs/d/pi_instance.html.markdown +++ b/website/docs/d/pi_instance.html.markdown @@ -44,15 +44,6 @@ Review the argument references that you can specify for your data source. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. -- `addresses` - (Deprecated, List of objects) - The address associated with this instance. - - Nested scheme for `addresses`: - - `ip` - (String) The IP address of the instance. - - `external_ip` - (String) The external IP address of the instance. - - `macaddress` - (String) The MAC address of the instance. - - `network_id` - (String) The network ID of the instance. - - `network_name` - (String) The network name of the instance. - - `type` - (String) The type of the network. - `deployment_type` - (String) The custom deployment type. - `health_status` - (String) The health of the instance. - `id` - (String) The unique identifier of the instance. diff --git a/website/docs/r/pi_dhcp.html.markdown b/website/docs/r/pi_dhcp.html.markdown index b39b0b9c83..4681c2d289 100644 --- a/website/docs/r/pi_dhcp.html.markdown +++ b/website/docs/r/pi_dhcp.html.markdown @@ -40,7 +40,6 @@ In addition to all argument reference list, you can access the following attribu Nested scheme for `leases`: - `instance_ip` - (String) The IP of the PVM Instance. - `instance_mac` - (String) The MAC Address of the PVM Instance. -- `network` - (String) The ID of the DHCP Server private network (deprecated - replaced by `network_id`). - `network_id`- (String) The ID of the DHCP Server private network. - `network_name` - The name of the DHCP Server private network. - `status` - (String) The status of the DHCP Server. diff --git a/website/docs/r/pi_instance.html.markdown b/website/docs/r/pi_instance.html.markdown index 429320d53d..90635be058 100644 --- a/website/docs/r/pi_instance.html.markdown +++ b/website/docs/r/pi_instance.html.markdown @@ -74,7 +74,6 @@ Review the argument references that you can specify for your resource. - **Note**: Provisioning VTL instances is temporarily disabled. - `pi_memory` - (Optional, Float) The amount of memory that you want to assign to your instance in gigabytes. - Required when not creating SAP instances. Conflicts with `pi_sap_profile_id`. -- `pi_migratable`- (Optional, Bool) Indicates the VM is migrated or not. - `pi_network` - (Required, List of Map) List of one or more networks to attach to the instance. The `pi_network` block supports: diff --git a/website/docs/r/pi_key.html.markdown b/website/docs/r/pi_key.html.markdown index d43ef988cc..49ac710353 100644 --- a/website/docs/r/pi_key.html.markdown +++ b/website/docs/r/pi_key.html.markdown @@ -32,7 +32,6 @@ Review the argument references that you can specify for your resource. In addition to all argument reference list, you can access the following attribute reference after your resource is created. - `id` - (String) The unique identifier of the key. The ID is composed of `/`. -- `key_id` - (String) User defined name for the SSH key (deprecated - replaced by `name`). - `name` - (String) User defined name for the SSH key - `creation_date` - (String) Date of SSH Key creation. - `ssh_key` - (String) SSH RSA key. diff --git a/website/docs/r/pi_network.html.markdown b/website/docs/r/pi_network.html.markdown index 4abefe7694..a48ce11c10 100644 --- a/website/docs/r/pi_network.html.markdown +++ b/website/docs/r/pi_network.html.markdown @@ -69,7 +69,7 @@ Review the argument references that you can specify for your resource. The `pi_ipaddress_range` block supports: - `pi_ending_ip_address` - (Required, String) The ending ip address. - `pi_starting_ip_address` - (Required, String) The staring ip address. **Note** if the `pi_gateway` or `pi_ipaddress_range` is not provided, it will calculate the value based on CIDR respectively. -- `pi_network_jumbo` - (Optional, Bool) MTU Jumbo option of the network (for multi-zone locations only). `deprecated` use `pi_network_mtu` instead. +- `pi_network_jumbo` - (Deprecated, Optional, Bool) MTU Jumbo option of the network (for multi-zone locations only). - `pi_network_mtu` - (Optional, Integer) Maximum Transmission Unit option of the network, min size = 1450 & max size = 9000. - `pi_network_access_config` - (Optional, String) The network communication configuration option of the network (for satellite locations only). diff --git a/website/docs/r/pi_network_port.html.markdown b/website/docs/r/pi_network_port.html.markdown deleted file mode 100644 index afcb10662e..0000000000 --- a/website/docs/r/pi_network_port.html.markdown +++ /dev/null @@ -1,75 +0,0 @@ ---- - -subcategory: "Power Systems" -layout: "ibm" -page_title: "IBM: pi_network_port" -description: |- - Manages an Network Port in the Power Virtual Server Cloud. A network port is equivalent to reserving an IP in the subnet. - When the port is created the status will be "DOWN". This network port however is not attached to an instance. ---- - -# ibm_pi_network_port -Creates or updates network port in the Power Virtual Server Cloud. For more information, about network in IBM power virutal server, see [adding or removing a public network -](https://cloud.ibm.com/docs/power-iaas?topic=power-iaas-modifying-server#adding-removing-network).. - -## Example usage - -In the following example, you can create an network_port: - -```terraform -resource "ibm_pi_network_port" "test-network-port" { - pi_network_name = "Zone1-CFN" - pi_cloud_instance_id = "51e1879c-bcbe-4ee1-a008-49cdba0eaf60" - pi_network_port_description = "IP Reserved for Oracle RAC " -} -``` - -**Note** -* Please find [supported Regions](https://cloud.ibm.com/apidocs/power-cloud#endpoint) for endpoints. -* If a Power cloud instance is provisioned at `lon04`, The provider level attributes should be as follows: - * `region` - `lon` - * `zone` - `lon04` - - Example usage: - - ```terraform - provider "ibm" { - region = "lon" - zone = "lon04" - } - ``` - -## Timeouts - -ibm_pi_network_port provides the following [timeouts](https://www.terraform.io/docs/language/resources/syntax.html) configuration options: - -- **create** - (Default 60 minutes) Used for creating a network_port. -- **delete** - (Default 60 minutes) Used for deleting a network_port. - -## Argument reference -Review the argument references that you can specify for your resource. - -- `pi_cloud_instance_id` - (Required, String) The GUID of the service instance associated with an account. -- `pi_network_name` - (Required, String) Network ID or name. -- `pi_network_port_description` - (Optional, String) The description for the Network Port. -- `pi_network_port_ipaddress` - (Optional, String) The requested ip address of this port. - -## Attribute reference -In addition to all argument reference list, you can access the following attribute reference after your resource is created. - -- `id` - (String) The unique identifier of the instance. The ID is composed of `//`. -- `macaddress` - (String) The MAC address of the port. -- `portid` - (String) The ID of the port. -- `public_ip` - (String) The public IP associated with the port. -- `status` - (String) The status of the port. - - -## Import - -The `ibm_pi_network_port` resource can be imported by using `power_instance_id`, `port_id` and `pi_network_name`. - -**Example** - -``` -$ terraform import ibm_pi_network_port.example d7bec597-4726-451f-8a63-e62e6f19c32c/cea6651a-bc0a-4438-9f8a-a0770bbf3ebb/network-name -``` diff --git a/website/docs/r/pi_network_port_attach.html.markdown b/website/docs/r/pi_network_port_attach.html.markdown index de0c14dfa5..b12d5b2a7f 100644 --- a/website/docs/r/pi_network_port_attach.html.markdown +++ b/website/docs/r/pi_network_port_attach.html.markdown @@ -61,14 +61,13 @@ In addition to all argument reference list, you can access the following attribu - `id` - (String) The unique identifier of the instance. The ID is composed of `//`. - `macaddress` - (String) The MAC address of the port. - `network_port_id` - (String) The ID of the port. -- `portid` - (Deprecated, String) The ID of the port. - `public_ip` - (String) The public IP associated with the port. - `status` - (String) The status of the port. ## Import -The `ibm_pi_network_port` resource can be imported by using `power_instance_id`, `pi_network_name` and `port_id`. +The `ibm_pi_network_port` resource can be imported by using `power_instance_id`, `pi_network_name` and `network_port_id`. **Example** diff --git a/website/docs/r/pi_snapshot.html.markdown b/website/docs/r/pi_snapshot.html.markdown index 59d4885f29..e16eac403f 100644 --- a/website/docs/r/pi_snapshot.html.markdown +++ b/website/docs/r/pi_snapshot.html.markdown @@ -58,7 +58,7 @@ Review the argument references that you can specify for your resource. ## Attribute reference In addition to all argument reference list, you can access the following attribute reference after your resource is created. -- `id` - (String) The unique identifier of the snapshot. The ID is composed of /. +- `id` - (String) The unique identifier of the snapshot. The ID is composed of /. - `snapshot_id` - (String) ID of the PVM instance snapshot. - `status` - (String) Status of the PVM instance snapshot. - `creation_date` - (String) Creation Date. @@ -67,7 +67,7 @@ In addition to all argument reference list, you can access the following attribu ## Import -The `ibm_pi_snapshot` resource can be imported by using `power_instance_id` and `pi_snap_shot_id`. +The `ibm_pi_snapshot` resource can be imported by using `power_instance_id` and `snapshot_id`. **Example** From 458df8e9a7d925d3cd7e3f848fd08d422a4e898a Mon Sep 17 00:00:00 2001 From: Haim Date: Mon, 12 Feb 2024 17:16:15 +0200 Subject: [PATCH 34/34] Remove deprecated Secrets Manager data sources --- .secrets.baseline | 104 +--- examples/ibm-secrets-manager/main.tf | 14 - examples/ibm-secrets-manager/variables.tf | 18 - ibm/acctest/acctest.go | 12 - ibm/conns/config.go | 26 - ibm/provider/provider.go | 7 - .../data_source_ibm_secrets_manager_secret.go | 432 --------------- ..._source_ibm_secrets_manager_secret_test.go | 42 -- ...data_source_ibm_secrets_manager_secrets.go | 499 ------------------ ...source_ibm_secrets_manager_secrets_test.go | 45 -- .../d/secrets_manager_secret.html.markdown | 9 - .../d/secrets_manager_secrets.html.markdown | 10 - 12 files changed, 15 insertions(+), 1203 deletions(-) delete mode 100644 ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret.go delete mode 100644 ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret_test.go delete mode 100644 ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets.go delete mode 100644 ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets_test.go delete mode 100644 website/docs/d/secrets_manager_secret.html.markdown delete mode 100644 website/docs/d/secrets_manager_secrets.html.markdown diff --git a/.secrets.baseline b/.secrets.baseline index 0cd34d7245..c17a30a0c8 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,11 +3,8 @@ "files": "go.mod|go.sum|.*.map|^.secrets.baseline$", "lines": null }, - "generated_at": "2024-01-29T11:06:53Z", + "generated_at": "2024-02-12T15:12:54Z", "plugins_used": [ - { - "name": "AWSKeyDetector" - }, { "name": "ArtifactoryDetector" }, @@ -21,12 +18,6 @@ { "name": "BasicAuthDetector" }, - { - "name": "BoxDetector" - }, - { - "name": "CloudantDetector" - }, { "ghe_instance": "github.ibm.com", "name": "GheDetector" @@ -51,9 +42,6 @@ "keyword_exclude": null, "name": "KeywordDetector" }, - { - "name": "MailchimpDetector" - }, { "name": "NpmDetector" }, @@ -68,12 +56,6 @@ }, { "name": "SquareOAuthDetector" - }, - { - "name": "StripeDetector" - }, - { - "name": "TwilioKeyDetector" } ], "results": { @@ -786,7 +768,7 @@ "hashed_secret": "9184b0c38101bf24d78b2bb0d044deb1d33696fc", "is_secret": false, "is_verified": false, - "line_number": 132, + "line_number": 131, "type": "Secret Keyword", "verified_result": null }, @@ -794,7 +776,7 @@ "hashed_secret": "c427f185ddcb2440be9b77c8e45f1cd487a2e790", "is_secret": false, "is_verified": false, - "line_number": 1454, + "line_number": 1446, "type": "Base64 High Entropy String", "verified_result": null }, @@ -802,7 +784,7 @@ "hashed_secret": "1f7e33de15e22de9d2eaf502df284ed25ca40018", "is_secret": false, "is_verified": false, - "line_number": 1521, + "line_number": 1513, "type": "Secret Keyword", "verified_result": null }, @@ -810,7 +792,7 @@ "hashed_secret": "1f614c2eb6b3da22d89bd1b9fd47d7cb7c8fc670", "is_secret": false, "is_verified": false, - "line_number": 3342, + "line_number": 3319, "type": "Secret Keyword", "verified_result": null }, @@ -818,7 +800,7 @@ "hashed_secret": "7abfce65b8504403afc25c9790f358d513dfbcc6", "is_secret": false, "is_verified": false, - "line_number": 3355, + "line_number": 3332, "type": "Secret Keyword", "verified_result": null }, @@ -826,7 +808,7 @@ "hashed_secret": "0c2d85bf9a9b1579b16f220a4ea8c3d62b2e24b1", "is_secret": false, "is_verified": false, - "line_number": 3396, + "line_number": 3373, "type": "Secret Keyword", "verified_result": null } @@ -846,7 +828,7 @@ "hashed_secret": "da8cae6284528565678de15e03d461e23fe22538", "is_secret": false, "is_verified": false, - "line_number": 1895, + "line_number": 1899, "type": "Secret Keyword", "verified_result": null }, @@ -854,7 +836,7 @@ "hashed_secret": "1a0334cfa65f4be58b9d914b8e96e9d9478bfbac", "is_secret": false, "is_verified": false, - "line_number": 3276, + "line_number": 3280, "type": "Secret Keyword", "verified_result": null } @@ -864,7 +846,7 @@ "hashed_secret": "c8b6f5ef11b9223ac35a5663975a466ebe7ebba9", "is_secret": false, "is_verified": false, - "line_number": 1842, + "line_number": 1835, "type": "Secret Keyword", "verified_result": null }, @@ -872,7 +854,7 @@ "hashed_secret": "8abf4899c01104241510ba87685ad4de76b0c437", "is_secret": false, "is_verified": false, - "line_number": 1848, + "line_number": 1841, "type": "Secret Keyword", "verified_result": null } @@ -1928,57 +1910,19 @@ } ], "ibm/service/contextbasedrestrictions/data_source_ibm_cbr_rule_test.go": [ - { - "hashed_secret": "9b6e9b736d5aad4455eee13c6b2741e2271fb6c9", - "is_secret": false, - "is_verified": false, - "line_number": 107, - "type": "Hex High Entropy String", - "verified_result": null - }, { "hashed_secret": "ca8b3e9d1445b3218e3512da63b05c8f26f181e5", "is_secret": false, "is_verified": false, - "line_number": 113, - "type": "Hex High Entropy String", - "verified_result": null - } - ], - "ibm/service/contextbasedrestrictions/data_source_ibm_cbr_zone_test.go": [ - { - "hashed_secret": "ca8b3e9d1445b3218e3512da63b05c8f26f181e5", - "is_secret": false, - "is_verified": false, - "line_number": 89, - "type": "Hex High Entropy String", - "verified_result": null - } - ], - "ibm/service/contextbasedrestrictions/resource_ibm_cbr_rule_test.go": [ - { - "hashed_secret": "9b6e9b736d5aad4455eee13c6b2741e2271fb6c9", - "is_secret": false, - "is_verified": false, - "line_number": 111, + "line_number": 17, "type": "Hex High Entropy String", "verified_result": null }, { - "hashed_secret": "ca8b3e9d1445b3218e3512da63b05c8f26f181e5", - "is_secret": false, - "is_verified": false, - "line_number": 117, - "type": "Hex High Entropy String", - "verified_result": null - } - ], - "ibm/service/contextbasedrestrictions/resource_ibm_cbr_zone_test.go": [ - { - "hashed_secret": "ca8b3e9d1445b3218e3512da63b05c8f26f181e5", + "hashed_secret": "9b6e9b736d5aad4455eee13c6b2741e2271fb6c9", "is_secret": false, "is_verified": false, - "line_number": 82, + "line_number": 18, "type": "Hex High Entropy String", "verified_result": null } @@ -1998,7 +1942,7 @@ "hashed_secret": "884a58e4c2c5d195d3876787bdc63af6c5af2924", "is_secret": false, "is_verified": false, - "line_number": 1595, + "line_number": 1615, "type": "Secret Keyword", "verified_result": null } @@ -3133,24 +3077,6 @@ "verified_result": null } ], - "ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets.go": [ - { - "hashed_secret": "09c0dfbba1f2b2576cfbac116e13b0258bc26bfa", - "is_secret": false, - "is_verified": false, - "line_number": 470, - "type": "Secret Keyword", - "verified_result": null - }, - { - "hashed_secret": "d282ab8a33d987146dda0381b4effdf2d91c0d65", - "is_secret": false, - "is_verified": false, - "line_number": 476, - "type": "Secret Keyword", - "verified_result": null - } - ], "ibm/service/secretsmanager/data_source_ibm_sm_configurations_test.go": [ { "hashed_secret": "347cd9c53ff77d41a7b22aa56c7b4efaf54658e3", diff --git a/examples/ibm-secrets-manager/main.tf b/examples/ibm-secrets-manager/main.tf index 5823fb3fa6..03053de022 100644 --- a/examples/ibm-secrets-manager/main.tf +++ b/examples/ibm-secrets-manager/main.tf @@ -488,17 +488,3 @@ data "ibm_sm_en_registration" "sm_en_registration_instance" { region = var.region endpoint_type = var.endpoint_type } - - -// Create secrets_manager_secrets data source -data "ibm_secrets_manager_secrets" "secrets_manager_secrets_instance" { - instance_id = var.secrets_manager_instance_id - secret_type = var.secrets_manager_secrets_secret_type -} - -// Create secrets_manager_secret data source -data "ibm_secrets_manager_secret" "secrets_manager_secret_instance" { - instance_id = var.secrets_manager_instance_id - secret_type = var.secrets_manager_secret_secret_type - secret_id = var.secrets_manager_secret_id -} \ No newline at end of file diff --git a/examples/ibm-secrets-manager/variables.tf b/examples/ibm-secrets-manager/variables.tf index fba28a2af8..a0a123adde 100644 --- a/examples/ibm-secrets-manager/variables.tf +++ b/examples/ibm-secrets-manager/variables.tf @@ -19,24 +19,6 @@ variable "endpoint_type" { default = "private" } -// Data source arguments for secrets_manager_secrets -variable "secrets_manager_secrets_secret_type" { - description = "The secret type." - type = string - default = null -} - -// Data source arguments for secrets_manager_secret -variable "secrets_manager_secret_secret_type" { - description = "The secret type. Supported options include: arbitrary, iam_credentials, username_password." - type = string - default = "arbitrary" -} -variable "secrets_manager_secret_id" { - description = "The v4 UUID that uniquely identifies the secret." - type = string -} - // Resource arguments for sm_secret_group variable "sm_secret_group_description" { description = "An extended description of your secret group.To protect your privacy, do not use personal data, such as your name or location, as a description for your secret group." diff --git a/ibm/acctest/acctest.go b/ibm/acctest/acctest.go index 3066238605..8ad66c1874 100644 --- a/ibm/acctest/acctest.go +++ b/ibm/acctest/acctest.go @@ -1269,18 +1269,6 @@ func init() { fmt.Println("[INFO] Set the environment variable SECRETS_MANAGER_SERVICE_CREDENTIALS_COS_CRN for testing service credentials' tests, else tests fail if not set correctly") } - SecretsManagerSecretType = os.Getenv("SECRETS_MANAGER_SECRET_TYPE") - if SecretsManagerSecretType == "" { - SecretsManagerSecretType = "username_password" - fmt.Println("[INFO] Set the environment variable SECRETS_MANAGER_SECRET_TYPE for testing data_source_ibm_secrets_manager_secrets_test, else it is set to default value. For data_source_ibm_secrets_manager_secret_test, tests will fail if this is not set correctly") - } - - SecretsManagerSecretID = os.Getenv("SECRETS_MANAGER_SECRET_ID") - if SecretsManagerSecretID == "" { - // SecretsManagerSecretID = "644f4a69-0d17-198f-3b58-23f2746c706d" - fmt.Println("[WARN] Set the environment variable SECRETS_MANAGER_SECRET_ID for testing data_source_ibm_secrets_manager_secret_test else tests will fail if this is not set correctly") - } - Tg_cross_network_account_api_key = os.Getenv("IBM_TG_CROSS_ACCOUNT_API_KEY") if Tg_cross_network_account_api_key == "" { fmt.Println("[INFO] Set the environment variable IBM_TG_CROSS_ACCOUNT_API_KEY for testing ibm_tg_connection resource else tests will fail if this is not set correctly") diff --git a/ibm/conns/config.go b/ibm/conns/config.go index 7b9a05a556..8af1576c92 100644 --- a/ibm/conns/config.go +++ b/ibm/conns/config.go @@ -119,7 +119,6 @@ import ( "github.com/IBM/eventstreams-go-sdk/pkg/schemaregistryv1" "github.com/IBM/ibm-hpcs-uko-sdk/ukov4" scc "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" - "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv1" "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv2" ) @@ -283,7 +282,6 @@ type ClientSession interface { CatalogManagementV1() (*catalogmanagementv1.CatalogManagementV1, error) EnterpriseManagementV1() (*enterprisemanagementv1.EnterpriseManagementV1, error) ResourceControllerV2API() (*resourcecontroller.ResourceControllerV2, error) - SecretsManagerV1() (*secretsmanagerv1.SecretsManagerV1, error) SecretsManagerV2() (*secretsmanagerv2.SecretsManagerV2, error) SchematicsV1() (*schematicsv1.SchematicsV1, error) SatelliteClientSession() (*kubernetesserviceapiv1.KubernetesServiceApiV1, error) @@ -540,7 +538,6 @@ type clientSession struct { // Resource Controller Option resourceControllerErr error resourceControllerAPI *resourcecontroller.ResourceControllerV2 - secretsManagerClientV1 *secretsmanagerv1.SecretsManagerV1 secretsManagerClient *secretsmanagerv2.SecretsManagerV2 secretsManagerClientErr error @@ -1086,11 +1083,6 @@ func (sess clientSession) ResourceControllerV2API() (*resourcecontroller.Resourc return sess.resourceControllerAPI, sess.resourceControllerErr } -// IBM Cloud Secrets Manager V1 Basic API -func (session clientSession) SecretsManagerV1() (*secretsmanagerv1.SecretsManagerV1, error) { - return session.secretsManagerClientV1, session.secretsManagerClientErr -} - // IBM Cloud Secrets Manager V2 Basic API func (session clientSession) SecretsManagerV2() (*secretsmanagerv2.SecretsManagerV2, error) { return session.secretsManagerClient, session.secretsManagerClientErr @@ -3087,24 +3079,6 @@ func (c *Config) ClientSession() (interface{}, error) { } session.resourceControllerAPI = resourceControllerClient - // SECRETS MANAGER Service - secretsManagerClientOptions := &secretsmanagerv1.SecretsManagerV1Options{ - Authenticator: authenticator, - } - /// Construct the service client. - session.secretsManagerClientV1, err = secretsmanagerv1.NewSecretsManagerV1(secretsManagerClientOptions) - if err != nil { - session.secretsManagerClientErr = fmt.Errorf("[ERROR] Error occurred while configuring IBM Cloud Secrets Manager API service: %q", err) - } - if session.secretsManagerClient != nil && session.secretsManagerClient.Service != nil { - // Enable retries for API calls - session.secretsManagerClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) - // Add custom header for analytics - session.secretsManagerClient.SetDefaultHeaders(gohttp.Header{ - "X-Original-User-Agent": {fmt.Sprintf("terraform-provider-ibm/%s", version.Version)}, - }) - } - // SECRETS MANAGER Service V2 // Construct an "options" struct for creating the service client. var smBaseUrl string diff --git a/ibm/provider/provider.go b/ibm/provider/provider.go index 2b6d711a14..817cc22ec8 100644 --- a/ibm/provider/provider.go +++ b/ibm/provider/provider.go @@ -684,11 +684,6 @@ func Provider() *schema.Provider { "ibm_billing_snapshot_list": usagereports.DataSourceIBMBillingSnapshotList(), // Added for Secrets Manager - // V1 data sources: - "ibm_secrets_manager_secrets": secretsmanager.DataSourceIBMSecretsManagerSecrets(), - "ibm_secrets_manager_secret": secretsmanager.DataSourceIBMSecretsManagerSecret(), - - // V2 data sources "ibm_sm_secret_group": secretsmanager.AddInstanceFields(secretsmanager.DataSourceIbmSmSecretGroup()), "ibm_sm_secret_groups": secretsmanager.AddInstanceFields(secretsmanager.DataSourceIbmSmSecretGroups()), "ibm_sm_private_certificate_configuration_intermediate_ca": secretsmanager.AddInstanceFields(secretsmanager.DataSourceIbmSmPrivateCertificateConfigurationIntermediateCA()), @@ -1686,8 +1681,6 @@ func Validator() validate.ValidatorDict { "ibm_is_vpc": vpc.DataSourceIBMISVpcValidator(), "ibm_is_volume": vpc.DataSourceIBMISVolumeValidator(), - "ibm_secrets_manager_secret": secretsmanager.DataSourceIBMSecretsManagerSecretValidator(), - "ibm_secrets_manager_secrets": secretsmanager.DataSourceIBMSecretsManagerSecretsValidator(), "ibm_cis_webhooks": cis.DataSourceIBMCISAlertWebhooksValidator(), "ibm_cis_alerts": cis.DataSourceIBMCISAlertsValidator(), "ibm_cis_bot_managements": cis.DataSourceIBMCISBotManagementValidator(), diff --git a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret.go b/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret.go deleted file mode 100644 index 27dcd545e8..0000000000 --- a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret.go +++ /dev/null @@ -1,432 +0,0 @@ -// Copyright IBM Corp. 2017, 2021 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package secretsmanager - -import ( - "context" - "fmt" - "log" - "strings" - "time" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" - rc "github.com/IBM/platform-services-go-sdk/resourcecontrollerv2" - "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv1" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func DataSourceIBMSecretsManagerSecret() *schema.Resource { - return &schema.Resource{ - ReadContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - return diag.Errorf("Data Source Removal: Data Source ibm_secrets_manager_secret is removed. Use ibm_sm__secret for managing secret of a specific type") - }, - DeprecationMessage: "Data Source Removal: Data Source ibm_secrets_manager_secret is removed. Use ibm_sm__secret for managing secret of a specific type.", - Schema: map[string]*schema.Schema{ - "instance_id": { - Type: schema.TypeString, - Required: true, - Description: "Secrets Manager instance GUID", - }, - "secret_type": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validate.InvokeDataSourceValidator("ibm_secrets_manager_secret", "secret_type"), - Description: "The secret type. Supported options include: arbitrary, iam_credentials, username_password.", - }, - "secret_id": { - Type: schema.TypeString, - Required: true, - Description: "The v4 UUID that uniquely identifies the secret.", - }, - "endpoint_type": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeDataSourceValidator("ibm_secrets_manager_secret", "endpoint_type"), - Description: "Endpoint Type. 'public' or 'private'", - Default: "public", - }, - "metadata": { - Type: schema.TypeList, - Computed: true, - Description: "The metadata that describes the resource array.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "collection_type": { - Type: schema.TypeString, - Computed: true, - Description: "The type of resources in the resource array.", - }, - "collection_total": { - Type: schema.TypeInt, - Computed: true, - Description: "The number of elements in the resource array.", - }, - }, - }, - }, - "type": { - Type: schema.TypeString, - Computed: true, - Description: "The MIME type that represents the secret.", - }, - "name": { - Type: schema.TypeString, - Computed: true, - Description: "A human-readable alias to assign to your secret.To protect your privacy, do not use personal data, such as your name or location, as an alias for your secret.", - }, - "description": { - Type: schema.TypeString, - Computed: true, - Description: "An extended description of your secret.To protect your privacy, do not use personal data, such as your name or location, as a description for your secret.", - }, - "secret_group_id": { - Type: schema.TypeString, - Computed: true, - Description: "The v4 UUID that uniquely identifies the secret group to assign to this secret.If you omit this parameter, your secret is assigned to the `default` secret group.", - }, - "labels": { - Type: schema.TypeList, - Computed: true, - Description: "Labels that you can use to filter for secrets in your instance.Up to 30 labels can be created. Labels can be between 2-30 characters, including spaces. Special characters not permitted include the angled bracket, comma, colon, ampersand, and vertical pipe character (|).To protect your privacy, do not use personal data, such as your name or location, as a label for your secret.", - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "state": { - Type: schema.TypeInt, - Computed: true, - Description: "The secret state based on NIST SP 800-57. States are integers and correspond to the Pre-activation = 0, Active = 1, Suspended = 2, Deactivated = 3, and Destroyed = 5 values.", - }, - "state_description": { - Type: schema.TypeString, - Computed: true, - Description: "A text representation of the secret state.", - }, - "crn": { - Type: schema.TypeString, - Computed: true, - Description: "The Cloud Resource Name (CRN) that uniquely identifies your Secrets Manager resource.", - }, - "creation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date the secret was created. The date format follows RFC 3339.", - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the entity that created the secret.", - }, - "last_update_date": { - Type: schema.TypeString, - Computed: true, - Description: "Updates when the actual secret is modified. The date format follows RFC 3339.", - }, - "versions": { - Type: schema.TypeList, - Computed: true, - Description: "An array that contains metadata for each secret version.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - Description: "The ID of the secret version.", - }, - "creation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date that the version of the secret was created.", - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the entity that created the secret.", - }, - "auto_rotated": { - Type: schema.TypeBool, - Computed: true, - Description: "Indicates whether the version of the secret was created by automatic rotation.", - }, - }, - }, - }, - "expiration_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date the secret material expires. The date format follows RFC 3339.You can set an expiration date on supported secret types at their creation. If you create a secret without specifying an expiration date, the secret does not expire. The `expiration_date` field is supported for the following secret types:- `arbitrary`- `username_password`.", - }, - "payload": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The new secret data to assign to an `arbitrary` secret.", - }, - "secret_data": { - Type: schema.TypeMap, - Sensitive: true, - Computed: true, - Description: "The secret data object", - }, - "username": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The username to assign to this secret.", - }, - "password": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The password to assign to this secret.", - }, - "next_rotation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date that the secret is scheduled for automatic rotation.The service automatically creates a new version of the secret on its next rotation date. This field exists only for secrets that can be auto-rotated and have an existing rotation policy.", - }, - "ttl": { - Type: schema.TypeString, - Computed: true, - Description: "The time-to-live (TTL) or lease duration to assign to generated credentials.For `iam_credentials` secrets, the TTL defines for how long each generated API key remains valid. The value can be either an integer that specifies the number of seconds, or the string representation of a duration, such as `120m` or `24h`.", - }, - "access_groups": { - Type: schema.TypeList, - Computed: true, - Description: "The access groups that define the capabilities of the service ID and API key that are generated for an`iam_credentials` secret.**Tip:** To find the ID of an access group, go to **Manage > Access (IAM) > Access groups** in the IBM Cloud console. Select the access group to inspect, and click **Details** to view its ID.", - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "api_key": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The API key that is generated for this secret.After the secret reaches the end of its lease (see the `ttl` field), the API key is deleted automatically. If you want to continue to use the same API key for future read operations, see the `reuse_api_key` field.", - }, - "service_id": { - Type: schema.TypeString, - Computed: true, - Description: "The service ID under which the API key (see the `api_key` field) is created. This service ID is added to the access groups that you assign for this secret.", - }, - "reuse_api_key": { - Type: schema.TypeBool, - Computed: true, - Description: "(IAM credentials) Reuse the service ID and API key for future read operations.", - }, - }, - } -} - -func DataSourceIBMSecretsManagerSecretValidator() *validate.ResourceValidator { - - validateSchema := make([]validate.ValidateSchema, 0) - secretType := "arbitrary,iam_credentials,imported_cert,public_cert,private_cert,username_password,kv" - endpointType := "public, private" - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "secret_type", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Required: true, - AllowedValues: secretType}) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "endpoint_type", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Optional: true, - AllowedValues: endpointType}) - - ibmSecretsManagerSecretdatasourceValidator := validate.ResourceValidator{ResourceName: "ibm_secrets_manager_secret", Schema: validateSchema} - return &ibmSecretsManagerSecretdatasourceValidator -} - -func dataSourceIBMSecretsManagerSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - bluemixSession, err := meta.(conns.ClientSession).BluemixSession() - if err != nil { - return diag.FromErr(err) - } - region := bluemixSession.Config.Region - - secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV1() - if err != nil { - return diag.FromErr(err) - } - rsConClient, err := meta.(conns.ClientSession).ResourceControllerV2API() - if err != nil { - return diag.FromErr(err) - } - instanceID := d.Get("instance_id").(string) - endpointType := d.Get("endpoint_type").(string) - var smEndpointURL string - resourceInstanceOptions := rc.GetResourceInstanceOptions{ - ID: &instanceID, - } - instanceData, resp, err := rsConClient.GetResourceInstance(&resourceInstanceOptions) - if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error:%s Response: %s", err, resp)) - } - instanceCRN := instanceData.CRN - - crnData := strings.Split(*instanceCRN, ":") - - if crnData[4] == "secrets-manager" { - if endpointType == "private" { - smEndpointURL = "https://" + instanceID + ".private." + region + ".secrets-manager.appdomain.cloud" - } else { - smEndpointURL = "https://" + instanceID + "." + region + ".secrets-manager.appdomain.cloud" - } - smUrl := conns.EnvFallBack([]string{"IBMCLOUD_SECRETS_MANAGER_API_ENDPOINT"}, smEndpointURL) - secretsManagerClient.Service.Options.URL = smUrl - } else { - return diag.FromErr(fmt.Errorf("[ERROR] Invalid or unsupported service Instance")) - } - - secretType := d.Get("secret_type").(string) - secretID := d.Get("secret_id").(string) - getSecretOptions := &secretsmanagerv1.GetSecretOptions{ - SecretType: &secretType, - ID: &secretID, - } - - getSecret, response, err := secretsManagerClient.GetSecret(getSecretOptions) - if err != nil { - log.Printf("[DEBUG] GetSecret failed %s\n%s", err, response) - return diag.FromErr(err) - } - - d.SetId(dataSourceIBMSecretsManagerSecretID(d)) - - if getSecret.Metadata != nil { - err = d.Set("metadata", dataSourceGetSecretFlattenMetadata(*getSecret.Metadata)) - if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting metadata %s", err)) - } - } - - if getSecret.Resources != nil { - for _, resourcesItem := range getSecret.Resources { - if ritem, ok := resourcesItem.(*secretsmanagerv1.SecretResource); ok { - //if ritem.Type != nil { - // d.Set("type", *ritem.Type) - //} - if ritem.Name != nil { - d.Set("name", *ritem.Name) - } - if ritem.Description != nil { - d.Set("description", *ritem.Description) - } - if ritem.SecretGroupID != nil { - d.Set("secret_group_id", *ritem.SecretGroupID) - } - if ritem.Labels != nil { - d.Set("labels", ritem.Labels) - } - if ritem.State != nil { - d.Set("state", *ritem.State) - } - if ritem.StateDescription != nil { - d.Set("state_description", *ritem.StateDescription) - } - if ritem.CRN != nil { - d.Set("crn", *ritem.CRN) - } - if ritem.CreationDate != nil { - d.Set("creation_date", (*ritem.CreationDate).String()) - } - if ritem.CreatedBy != nil { - d.Set("created_by", *ritem.CreatedBy) - } - if ritem.LastUpdateDate != nil { - d.Set("last_update_date", (*ritem.LastUpdateDate).String()) - } - if ritem.Versions != nil { - versionsList := []map[string]interface{}{} - for _, versionsItem := range ritem.Versions { - versionsList = append(versionsList, dataSourceGetSecretResourcesVersionsToMap(versionsItem)) - } - d.Set("versions", versionsList) - } - if ritem.SecretData != nil { - secretData := ritem.SecretData - d.Set("secret_data", secretData) - if *ritem.SecretType == "username_password" { - d.Set("username", secretData["username"].(string)) - d.Set("password", secretData["password"].(string)) - } else if *ritem.SecretType == "arbitrary" { - d.Set("payload", secretData["payload"].(string)) - } - } - if ritem.NextRotationDate != nil { - d.Set("next_rotation_date", (*ritem.NextRotationDate).String()) - } - if ritem.TTL != nil { - d.Set("ttl", fmt.Sprintf("%v", ritem.TTL)) - } - if ritem.AccessGroups != nil { - d.Set("access_groups", ritem.AccessGroups) - } - if ritem.APIKey != nil { - d.Set("api_key", *ritem.APIKey) - } - if ritem.ServiceID != nil { - d.Set("service_id", *ritem.ServiceID) - } - if ritem.ReuseAPIKey != nil { - d.Set("reuse_api_key", *ritem.ReuseAPIKey) - } - } - } - } - - return nil -} - -// dataSourceIBMSecretsManagerSecretID returns a reasonable ID for the list. -func dataSourceIBMSecretsManagerSecretID(d *schema.ResourceData) string { - return time.Now().UTC().String() -} - -func dataSourceGetSecretFlattenMetadata(result secretsmanagerv1.CollectionMetadata) (finalList []map[string]interface{}) { - finalList = []map[string]interface{}{} - finalMap := dataSourceGetSecretMetadataToMap(result) - finalList = append(finalList, finalMap) - - return finalList -} - -func dataSourceGetSecretMetadataToMap(metadataItem secretsmanagerv1.CollectionMetadata) (metadataMap map[string]interface{}) { - metadataMap = map[string]interface{}{} - - if metadataItem.CollectionType != nil { - metadataMap["collection_type"] = metadataItem.CollectionType - } - if metadataItem.CollectionTotal != nil { - metadataMap["collection_total"] = metadataItem.CollectionTotal - } - - return metadataMap -} - -func dataSourceGetSecretResourcesVersionsToMap(versionsItem map[string]interface{}) (versionsMap map[string]interface{}) { - versionsMap = map[string]interface{}{} - - if id, ok := versionsItem["id"]; ok { - versionsMap["id"] = id - } - if creation_date, ok := versionsItem["creation_date"]; ok { - versionsMap["creation_date"] = creation_date - } - if created_by, ok := versionsItem["created_by"]; ok { - versionsMap["created_by"] = created_by - } - if rotated, ok := versionsItem["auto_rotated"]; ok { - versionsMap["auto_rotated"] = rotated - } - - return versionsMap -} diff --git a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret_test.go b/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret_test.go deleted file mode 100644 index d5cbd1b566..0000000000 --- a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secret_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright IBM Corp. 2017, 2021 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package secretsmanager_test - -import ( - "fmt" - "testing" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -func TestAccIBMSecretsManagerSecretDataSourceBasic(t *testing.T) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckIBMSecretsManagerSecretDataSourceConfigBasic(), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.ibm_secrets_manager_secret.secrets_manager_secret", "secret_type", acc.SecretsManagerSecretType), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secret.secrets_manager_secret", "id"), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secret.secrets_manager_secret", "secret_type"), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secret.secrets_manager_secret", "secret_id"), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secret.secrets_manager_secret", "metadata.#"), - ), - }, - }, - }) -} - -func testAccCheckIBMSecretsManagerSecretDataSourceConfigBasic() string { - return fmt.Sprintf(` - data "ibm_secrets_manager_secret" "secrets_manager_secret" { - instance_id = "%s" - secret_type = "%s" - secret_id = "%s" - } - `, acc.SecretsManagerInstanceID, acc.SecretsManagerSecretType, acc.SecretsManagerSecretID) -} diff --git a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets.go b/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets.go deleted file mode 100644 index 17c7f09f8a..0000000000 --- a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets.go +++ /dev/null @@ -1,499 +0,0 @@ -// Copyright IBM Corp. 2017, 2021 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package secretsmanager - -import ( - "context" - "fmt" - "log" - "strings" - "time" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" - "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv1" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func DataSourceIBMSecretsManagerSecrets() *schema.Resource { - return &schema.Resource{ - ReadContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - return diag.Errorf("Data Source Removal: Data Source ibm_secrets_manager_secrets is removed. Use ibm_sm_secrets for listing secrets") - }, - DeprecationMessage: "Data Source Removal: Data Source ibm_secrets_manager_secrets is removed. Use ibm_sm_secrets for listing secrets", - Schema: map[string]*schema.Schema{ - "instance_id": { - Type: schema.TypeString, - Required: true, - Description: "Secrets Manager instance GUID", - }, - "secret_type": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeDataSourceValidator("ibm_secrets_manager_secrets", "secret_type"), - Description: "The secret type. Supported options include: arbitrary, iam_credentials, username_password.", - }, - "endpoint_type": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeDataSourceValidator("ibm_secrets_manager_secrets", "endpoint_type"), - Description: "Endpoint Type. 'public' or 'private'", - Default: "public", - }, - "metadata": { - Type: schema.TypeList, - Computed: true, - Description: "The metadata that describes the resource array.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "collection_type": { - Type: schema.TypeString, - Computed: true, - Description: "The type of resources in the resource array.", - }, - "collection_total": { - Type: schema.TypeInt, - Computed: true, - Description: "The number of elements in the resource array.", - }, - }, - }, - }, - "secrets": { - Type: schema.TypeList, - Computed: true, - Description: "A collection of secret resources.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "type": { - Type: schema.TypeString, - Computed: true, - Description: "The MIME type that represents the secret.", - }, - "secret_id": { - Type: schema.TypeString, - Computed: true, - Description: "The v4 UUID that uniquely identifies the secret.", - }, - "name": { - Type: schema.TypeString, - Computed: true, - Description: "A human-readable alias to assign to your secret.To protect your privacy, do not use personal data, such as your name or location, as an alias for your secret.", - }, - "description": { - Type: schema.TypeString, - Computed: true, - Description: "An extended description of your secret.To protect your privacy, do not use personal data, such as your name or location, as a description for your secret.", - }, - "secret_group_id": { - Type: schema.TypeString, - Computed: true, - Description: "The v4 UUID that uniquely identifies the secret group to assign to this secret.If you omit this parameter, your secret is assigned to the `default` secret group.", - }, - "labels": { - Type: schema.TypeList, - Computed: true, - Description: "Labels that you can use to filter for secrets in your instance.Up to 30 labels can be created. Labels can be between 2-30 characters, including spaces. Special characters not permitted include the angled bracket, comma, colon, ampersand, and vertical pipe character (|).To protect your privacy, do not use personal data, such as your name or location, as a label for your secret.", - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "state": { - Type: schema.TypeInt, - Computed: true, - Description: "The secret state based on NIST SP 800-57. States are integers and correspond to the Pre-activation = 0, Active = 1, Suspended = 2, Deactivated = 3, and Destroyed = 5 values.", - }, - "state_description": { - Type: schema.TypeString, - Computed: true, - Description: "A text representation of the secret state.", - }, - "secret_type": { - Type: schema.TypeString, - Computed: true, - Description: "The secret type.", - }, - "crn": { - Type: schema.TypeString, - Computed: true, - Description: "The Cloud Resource Name (CRN) that uniquely identifies your Secrets Manager resource.", - }, - "creation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date the secret was created. The date format follows RFC 3339.", - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the entity that created the secret.", - }, - "last_update_date": { - Type: schema.TypeString, - Computed: true, - Description: "Updates when the actual secret is modified. The date format follows RFC 3339.", - }, - "versions": { - Type: schema.TypeList, - Computed: true, - Description: "An array that contains metadata for each secret version.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - Description: "The ID of the secret version.", - }, - "creation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date that the version of the secret was created.", - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - Description: "The unique identifier for the entity that created the secret.", - }, - "auto_rotated": { - Type: schema.TypeBool, - Computed: true, - Description: "Indicates whether the version of the secret was created by automatic rotation.", - }, - }, - }, - }, - "expiration_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date the secret material expires. The date format follows RFC 3339.You can set an expiration date on supported secret types at their creation. If you create a secret without specifying an expiration date, the secret does not expire. The `expiration_date` field is supported for the following secret types:- `arbitrary`- `username_password`.", - }, - "payload": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The new secret data to assign to an `arbitrary` secret.", - }, - "secret_data": { - Type: schema.TypeMap, - Sensitive: true, - Computed: true, - Description: "The secret data object", - }, - "username": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The username to assign to this secret.", - }, - "password": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The password to assign to this secret.", - }, - "next_rotation_date": { - Type: schema.TypeString, - Computed: true, - Description: "The date that the secret is scheduled for automatic rotation.The service automatically creates a new version of the secret on its next rotation date. This field exists only for secrets that can be auto-rotated and have an existing rotation policy.", - }, - "ttl": { - Type: schema.TypeString, - Computed: true, - Description: "The time-to-live (TTL) or lease duration to assign to generated credentials.For `iam_credentials` secrets, the TTL defines for how long each generated API key remains valid. The value can be either an integer that specifies the number of seconds, or the string representation of a duration, such as `120m` or `24h`.", - }, - "access_groups": { - Type: schema.TypeList, - Computed: true, - Description: "The access groups that define the capabilities of the service ID and API key that are generated for an`iam_credentials` secret.**Tip:** To find the ID of an access group, go to **Manage > Access (IAM) > Access groups** in the IBM Cloud console. Select the access group to inspect, and click **Details** to view its ID.", - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "api_key": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Description: "The API key that is generated for this secret.After the secret reaches the end of its lease (see the `ttl` field), the API key is deleted automatically. If you want to continue to use the same API key for future read operations, see the `reuse_api_key` field.", - }, - "service_id": { - Type: schema.TypeString, - Computed: true, - Description: "The service ID under which the API key (see the `api_key` field) is created. This service ID is added to the access groups that you assign for this secret.", - }, - "reuse_api_key": { - Type: schema.TypeBool, - Computed: true, - Description: "(IAM credentials) Reuse the service ID and API key for future read operations.", - }, - }, - }, - }, - }, - } -} - -func DataSourceIBMSecretsManagerSecretsValidator() *validate.ResourceValidator { - - validateSchema := make([]validate.ValidateSchema, 0) - secretType := "arbitrary, iam_credentials, username_password" - endpointType := "public, private" - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "secret_type", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Optional: true, - AllowedValues: secretType}) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "endpoint_type", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Optional: true, - AllowedValues: endpointType}) - - ibmSecretsManagerSecretsdatasourceValidator := validate.ResourceValidator{ResourceName: "ibm_secrets_manager_secrets", Schema: validateSchema} - return &ibmSecretsManagerSecretsdatasourceValidator -} - -func dataSourceIBMSecretsManagerSecretsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - bluemixSession, err := meta.(conns.ClientSession).BluemixSession() - if err != nil { - return diag.FromErr(err) - } - region := bluemixSession.Config.Region - - secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV1() - if err != nil { - return diag.FromErr(err) - } - rContollerClient, err := meta.(conns.ClientSession).ResourceControllerAPIV2() - if err != nil { - return diag.FromErr(err) - } - - instanceID := d.Get("instance_id").(string) - endpointType := d.Get("endpoint_type").(string) - var smEndpointURL string - - rContollerAPI := rContollerClient.ResourceServiceInstanceV2() - - instanceData, err := rContollerAPI.GetInstance(instanceID) - if err != nil { - return diag.FromErr(err) - } - instanceCRN := instanceData.Crn.String() - - crnData := strings.Split(instanceCRN, ":") - - if crnData[4] == "secrets-manager" { - if endpointType == "private" { - smEndpointURL = "https://" + instanceID + ".private." + region + ".secrets-manager.appdomain.cloud" - } else { - smEndpointURL = "https://" + instanceID + "." + region + ".secrets-manager.appdomain.cloud" - } - smUrl := conns.EnvFallBack([]string{"IBMCLOUD_SECRETS_MANAGER_API_ENDPOINT"}, smEndpointURL) - secretsManagerClient.Service.Options.URL = smUrl - } else { - return diag.FromErr(fmt.Errorf("[ERROR] Invalid or unsupported service Instance")) - } - - listAllSecretsOptions := &secretsmanagerv1.ListAllSecretsOptions{} - - listSecrets, response, err := secretsManagerClient.ListAllSecretsWithContext(context, listAllSecretsOptions) - if err != nil { - log.Printf("[DEBUG] ListAllSecretsWithContext failed %s\n%s", err, response) - return diag.FromErr(err) - } - - // Use the provided filter argument and construct a new list with only the requested resource(s) - var matchResources []secretsmanagerv1.SecretResourceIntf - var secretType string - var suppliedFilter bool - - if v, ok := d.GetOk("secret_type"); ok { - secretType = v.(string) - suppliedFilter = true - for _, data := range listSecrets.Resources { - if rdata, ok := data.(*secretsmanagerv1.SecretResource); ok { - if *rdata.SecretType == secretType { - matchResources = append(matchResources, data) - } - } - } - } else { - matchResources = listSecrets.Resources - } - listSecrets.Resources = matchResources - - if len(listSecrets.Resources) == 0 { - return diag.FromErr(fmt.Errorf("no Resources found with secretType %s\nIf not specified, please specify more filters", secretType)) - } - - if suppliedFilter { - d.SetId(secretType) - } else { - d.SetId(dataSourceIBMSecretsManagerSecretsID(d)) - } - - if listSecrets.Metadata != nil { - err = d.Set("metadata", dataSourceListSecretsFlattenMetadata(*listSecrets.Metadata)) - if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting metadata %s", err)) - } - } - - if listSecrets.Resources != nil { - err = d.Set("secrets", dataSourceListSecretsFlattenResources(listSecrets.Resources)) - if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting resources %s", err)) - } - } - - return nil -} - -// dataSourceIBMSecretsManagerSecretsID returns a reasonable ID for the list. -func dataSourceIBMSecretsManagerSecretsID(d *schema.ResourceData) string { - return time.Now().UTC().String() -} - -func dataSourceListSecretsFlattenMetadata(result secretsmanagerv1.CollectionMetadata) (finalList []map[string]interface{}) { - finalList = []map[string]interface{}{} - finalMap := dataSourceListSecretsMetadataToMap(result) - finalList = append(finalList, finalMap) - - return finalList -} - -func dataSourceListSecretsMetadataToMap(metadataItem secretsmanagerv1.CollectionMetadata) (metadataMap map[string]interface{}) { - metadataMap = map[string]interface{}{} - - if metadataItem.CollectionType != nil { - metadataMap["collection_type"] = metadataItem.CollectionType - } - if metadataItem.CollectionTotal != nil { - metadataMap["collection_total"] = metadataItem.CollectionTotal - } - - return metadataMap -} - -func dataSourceListSecretsFlattenResources(result []secretsmanagerv1.SecretResourceIntf) (resources []map[string]interface{}) { - for _, resourcesItem := range result { - if ritem, ok := resourcesItem.(*secretsmanagerv1.SecretResource); ok { - resources = append(resources, dataSourceListSecretsResourcesToMap(*ritem)) - } - } - - return resources -} - -func dataSourceListSecretsResourcesToMap(resourcesItem secretsmanagerv1.SecretResource) (resourcesMap map[string]interface{}) { - resourcesMap = map[string]interface{}{} - - //if resourcesItem.Type != nil { - // resourcesMap["type"] = *resourcesItem.Type - //} - if resourcesItem.ID != nil { - resourcesMap["secret_id"] = *resourcesItem.ID - } - if resourcesItem.Name != nil { - resourcesMap["name"] = *resourcesItem.Name - } - if resourcesItem.Description != nil { - resourcesMap["description"] = *resourcesItem.Description - } - if resourcesItem.SecretGroupID != nil { - resourcesMap["secret_group_id"] = *resourcesItem.SecretGroupID - } - if resourcesItem.Labels != nil { - resourcesMap["labels"] = resourcesItem.Labels - } - if resourcesItem.State != nil { - resourcesMap["state"] = *resourcesItem.State - } - if resourcesItem.StateDescription != nil { - resourcesMap["state_description"] = *resourcesItem.StateDescription - } - if resourcesItem.SecretType != nil { - resourcesMap["secret_type"] = *resourcesItem.SecretType - } - if resourcesItem.CRN != nil { - resourcesMap["crn"] = *resourcesItem.CRN - } - if resourcesItem.CreationDate != nil { - resourcesMap["creation_date"] = (*resourcesItem.CreationDate).String() - } - if resourcesItem.CreatedBy != nil { - resourcesMap["created_by"] = *resourcesItem.CreatedBy - } - if resourcesItem.LastUpdateDate != nil { - resourcesMap["last_update_date"] = (*resourcesItem.LastUpdateDate).String() - } - if resourcesItem.Versions != nil { - versionsList := []map[string]interface{}{} - for _, versionsItem := range resourcesItem.Versions { - versionsList = append(versionsList, dataSourceListSecretsResourcesVersionsToMap(versionsItem)) - } - resourcesMap["versions"] = versionsList - } - if resourcesItem.ExpirationDate != nil { - resourcesMap["expiration_date"] = (*resourcesItem.ExpirationDate).String() - } - // Commented out because the response to list secrets shouldn't include payload - //if resourcesItem.Payload != nil { - // resourcesMap["payload"] = *resourcesItem.Payload - //} - if resourcesItem.SecretData != nil { - secretData := resourcesItem.SecretData - resourcesMap["secret_data"] = secretData - if *resourcesItem.SecretType == "username_password" { - resourcesMap["username"] = secretData["username"].(string) - resourcesMap["password"] = secretData["password"].(string) - } else if *resourcesItem.SecretType == "arbitrary" { - resourcesMap["payload"] = secretData["payload"].(string) - } - } - if resourcesItem.NextRotationDate != nil { - resourcesMap["next_rotation_date"] = (*resourcesItem.NextRotationDate).String() - } - if resourcesItem.TTL != nil { - resourcesMap["ttl"] = fmt.Sprintf("%v", resourcesItem.TTL) - } - if resourcesItem.AccessGroups != nil { - resourcesMap["access_groups"] = resourcesItem.AccessGroups - } - if resourcesItem.APIKey != nil { - resourcesMap["api_key"] = *resourcesItem.APIKey - } - if resourcesItem.ServiceID != nil { - resourcesMap["service_id"] = *resourcesItem.ServiceID - } - if resourcesItem.ReuseAPIKey != nil { - resourcesMap["reuse_api_key"] = *resourcesItem.ReuseAPIKey - } - - return resourcesMap -} - -func dataSourceListSecretsResourcesVersionsToMap(versionsItem map[string]interface{}) (versionsMap map[string]interface{}) { - versionsMap = map[string]interface{}{} - - if id, ok := versionsItem["id"]; ok { - versionsMap["id"] = id - } - if creation_date, ok := versionsItem["creation_date"]; ok { - versionsMap["creation_date"] = creation_date - } - if created_by, ok := versionsItem["created_by"]; ok { - versionsMap["created_by"] = created_by - } - if rotated, ok := versionsItem["auto_rotated"]; ok { - versionsMap["auto_rotated"] = rotated - } - - return versionsMap -} diff --git a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets_test.go b/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets_test.go deleted file mode 100644 index 9849e835bc..0000000000 --- a/ibm/service/secretsmanager/data_source_ibm_secrets_manager_secrets_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright IBM Corp. 2017, 2021 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package secretsmanager_test - -import ( - "fmt" - "testing" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -func TestAccIBMSecretsManagerSecretsDataSourceBasic(t *testing.T) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckIBMSecretsManagerSecretsDataSourceConfigBasic(), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.ibm_secrets_manager_secrets.secrets_manager_secrets", "secret_type", acc.SecretsManagerSecretType), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secrets.secrets_manager_secrets", "id"), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secrets.secrets_manager_secrets", "secret_type"), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secrets.secrets_manager_secrets", "metadata.#"), - resource.TestCheckResourceAttrSet("data.ibm_secrets_manager_secrets.secrets_manager_secrets", "secrets.#"), - ), - }, - }, - }) -} - -func testAccCheckIBMSecretsManagerSecretsDataSourceConfigBasic() string { - return fmt.Sprintf(` - data "ibm_secrets_manager_secrets" "secrets_manager_secrets" { - instance_id = "%s" - secret_type = "%s" - } - - output "WorkSpaceValues" { - value = data.ibm_secrets_manager_secrets.secrets_manager_secrets.secret_type - } - `, acc.SecretsManagerInstanceID, acc.SecretsManagerSecretType) -} diff --git a/website/docs/d/secrets_manager_secret.html.markdown b/website/docs/d/secrets_manager_secret.html.markdown deleted file mode 100644 index 26cda83ab2..0000000000 --- a/website/docs/d/secrets_manager_secret.html.markdown +++ /dev/null @@ -1,9 +0,0 @@ ---- -subcategory: "Secrets Manager" -layout: "ibm" -page_title: "IBM : ibm_secrets_manager_secret" -description: |- - Get information about secrets manager secret ---- - -# ibm_secrets_manager_secret (Removed) \ No newline at end of file diff --git a/website/docs/d/secrets_manager_secrets.html.markdown b/website/docs/d/secrets_manager_secrets.html.markdown deleted file mode 100644 index 27899b85fe..0000000000 --- a/website/docs/d/secrets_manager_secrets.html.markdown +++ /dev/null @@ -1,10 +0,0 @@ ---- -subcategory: "Secrets Manager" -layout: "ibm" -page_title: "IBM : ibm_secrets_manager_secrets" -description: |- - Get information about secrets manager secrets. ---- - -# ibm_secrets_manager_secrets (Removed) -