From 8c80f0704aa0c33495c1e3426f19dfde51097475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20B=C3=A9rot-Armand?= Date: Wed, 23 Nov 2022 15:14:39 +0000 Subject: [PATCH] Move some function to utils --- outscale/data_source_outscale_access_keys.go | 4 +- outscale/data_source_outscale_accounts.go | 2 +- .../data_source_outscale_client_gateways.go | 2 +- outscale/data_source_outscale_dhcp_options.go | 2 +- outscale/data_source_outscale_image.go | 2 +- outscale/data_source_outscale_images.go | 18 +--- .../data_source_outscale_load_balancer.go | 10 +-- ...ce_outscale_load_balancer_listener_rule.go | 2 +- ...e_outscale_load_balancer_listener_rules.go | 2 +- ...data_source_outscale_load_balancer_tags.go | 2 +- .../data_source_outscale_load_balancer_vms.go | 3 +- .../data_source_outscale_load_balancers.go | 7 +- .../data_source_outscale_net_access_point.go | 2 +- .../data_source_outscale_net_access_points.go | 2 +- outscale/data_source_outscale_snapshot.go | 14 +--- outscale/data_source_outscale_snapshots.go | 6 +- outscale/data_source_outscale_vm_states.go | 2 +- outscale/data_source_outscale_volumes.go | 2 +- .../data_source_outscale_vpn_connections.go | 2 +- outscale/resource_outscale_api_access_rule.go | 12 +-- outscale/resource_outscale_dhcp_option.go | 6 +- outscale/resource_outscale_load_balancer.go | 84 +++++-------------- ...ource_outscale_load_balancer_attributes.go | 8 +- ...ce_outscale_load_balancer_listener_rule.go | 4 +- .../resource_outscale_load_balancer_policy.go | 8 +- .../resource_outscale_net_access_point.go | 8 +- outscale/resource_outscale_nic.go | 4 +- outscale/resource_outscale_nic_private_ip.go | 4 +- .../resource_outscale_security_group_rule.go | 8 +- outscale/resource_outscale_vm.go | 12 +-- utils/utils.go | 45 ++++++++++ 31 files changed, 133 insertions(+), 156 deletions(-) diff --git a/outscale/data_source_outscale_access_keys.go b/outscale/data_source_outscale_access_keys.go index 79ffcf200..f938b993b 100644 --- a/outscale/data_source_outscale_access_keys.go +++ b/outscale/data_source_outscale_access_keys.go @@ -83,10 +83,10 @@ func dataSourceAccessKeysRead(d *schema.ResourceData, meta interface{}) error { filterReq = buildDataSourceAccessKeyFilters(filters.(*schema.Set)) } if accessKeyOk { - filterReq.SetAccessKeyIds(expandStringValueList(accessKeyID.([]interface{}))) + filterReq.SetAccessKeyIds(utils.InterfaceSliceToStringSlice(accessKeyID.([]interface{}))) } if stateOk { - filterReq.SetStates(expandStringValueList(state.([]interface{}))) + filterReq.SetStates(utils.InterfaceSliceToStringSlice(state.([]interface{}))) } var resp oscgo.ReadAccessKeysResponse diff --git a/outscale/data_source_outscale_accounts.go b/outscale/data_source_outscale_accounts.go index 4cc421809..c2eeaf21e 100644 --- a/outscale/data_source_outscale_accounts.go +++ b/outscale/data_source_outscale_accounts.go @@ -132,7 +132,7 @@ func flattenAccounts(accounts []oscgo.Account) []map[string]interface{} { for i, account := range accounts { accountsMap[i] = map[string]interface{}{ "account_id": account.GetAccountId(), - "additional_emails": flattenStringList(account.AdditionalEmails), + "additional_emails": utils.StringListToInterfaceSlice(account.AdditionalEmails), "city": account.GetCity(), "company_name": account.GetCompanyName(), "country": account.GetCountry(), diff --git a/outscale/data_source_outscale_client_gateways.go b/outscale/data_source_outscale_client_gateways.go index d2418fc0a..af523513a 100644 --- a/outscale/data_source_outscale_client_gateways.go +++ b/outscale/data_source_outscale_client_gateways.go @@ -75,7 +75,7 @@ func dataSourceClientGatewaysRead(d *schema.ResourceData, meta interface{}) erro if clientGatewayOk { params.Filters = &oscgo.FiltersClientGateway{ - ClientGatewayIds: expandStringValueListPointer(clientGatewayIDs.([]interface{})), + ClientGatewayIds: utils.InterfaceSliceToStringList(clientGatewayIDs.([]interface{})), } } diff --git a/outscale/data_source_outscale_dhcp_options.go b/outscale/data_source_outscale_dhcp_options.go index 37cd944f2..73e3e7d8e 100644 --- a/outscale/data_source_outscale_dhcp_options.go +++ b/outscale/data_source_outscale_dhcp_options.go @@ -87,7 +87,7 @@ func dataSourceDHCPOptionsRead(d *schema.ResourceData, meta interface{}) error { params := oscgo.ReadDhcpOptionsRequest{} if dhcpIDOk { params.Filters = &oscgo.FiltersDhcpOptions{ - DhcpOptionsSetIds: expandStringValueListPointer(dhcpIDs.([]interface{})), + DhcpOptionsSetIds: utils.InterfaceSliceToStringList(dhcpIDs.([]interface{})), } } if filtersOk { diff --git a/outscale/data_source_outscale_image.go b/outscale/data_source_outscale_image.go index 22c679dea..aa41f4b4a 100644 --- a/outscale/data_source_outscale_image.go +++ b/outscale/data_source_outscale_image.go @@ -216,7 +216,7 @@ func dataSourceImageRead(d *schema.ResourceData, meta interface{}) error { filtersReq.SetAccountIds([]string{ai.(string)}) } if executableUsersOk { - filtersReq.SetPermissionsToLaunchAccountIds(expandStringValueList(executableUsers.([]interface{}))) + filtersReq.SetPermissionsToLaunchAccountIds(utils.InterfaceSliceToStringSlice(executableUsers.([]interface{}))) } req := oscgo.ReadImagesRequest{Filters: filtersReq} diff --git a/outscale/data_source_outscale_images.go b/outscale/data_source_outscale_images.go index f290fb7da..c0ebb12c2 100644 --- a/outscale/data_source_outscale_images.go +++ b/outscale/data_source_outscale_images.go @@ -229,7 +229,7 @@ func dataSourceImagesRead(d *schema.ResourceData, meta interface{}) error { filtersReq.SetAccountIds([]string{aids.(string)}) } if executableUsersOk { - filtersReq.SetPermissionsToLaunchAccountIds(expandStringValueList(executableUsers.([]interface{}))) + filtersReq.SetPermissionsToLaunchAccountIds(utils.InterfaceSliceToStringSlice(executableUsers.([]interface{}))) } req := oscgo.ReadImagesRequest{Filters: filtersReq} @@ -344,19 +344,3 @@ func buildDataSourceImagesFilters(set *schema.Set) *oscgo.FiltersImage { } return filters } - -func expandStringValueList(configured []interface{}) []string { - vs := make([]string, 0, len(configured)) - for _, v := range configured { - val, ok := v.(string) - if ok && val != "" { - vs = append(vs, v.(string)) - } - } - return vs -} - -func expandStringValueListPointer(configured []interface{}) *[]string { - res := expandStringValueList(configured) - return &res -} diff --git a/outscale/data_source_outscale_load_balancer.go b/outscale/data_source_outscale_load_balancer.go index 87fbc25fb..86489463d 100644 --- a/outscale/data_source_outscale_load_balancer.go +++ b/outscale/data_source_outscale_load_balancer.go @@ -229,7 +229,7 @@ func readLbs_(conn *oscgo.APIClient, d *schema.ResourceData, t schema.ValueType) } } else { /* assuming typelist */ filter = &oscgo.FiltersLoadBalancer{ - LoadBalancerNames: expandStringList(ename.([]interface{})), + LoadBalancerNames: utils.InterfaceSliceToStringSlicePtr(ename.([]interface{})), } } @@ -286,12 +286,12 @@ func dataSourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error return err } - d.Set("subregion_names", flattenStringList(lb.SubregionNames)) + d.Set("subregion_names", utils.StringListToInterfaceSlice(lb.SubregionNames)) d.Set("dns_name", lb.DnsName) d.Set("health_check", flattenHealthCheck(lb.HealthCheck)) d.Set("access_log", flattenAccessLog(lb.AccessLog)) - d.Set("backend_vm_ids", flattenStringList(lb.BackendVmIds)) + d.Set("backend_vm_ids", utils.StringListToInterfaceSlice(lb.BackendVmIds)) if err := d.Set("listeners", flattenListeners(lb.Listeners)); err != nil { return err } @@ -337,7 +337,7 @@ func dataSourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error } d.Set("load_balancer_type", lb.LoadBalancerType) if lb.SecurityGroups != nil { - d.Set("security_groups", flattenStringList(lb.SecurityGroups)) + d.Set("security_groups", utils.StringListToInterfaceSlice(lb.SecurityGroups)) } else { d.Set("security_groups", make([]map[string]interface{}, 0)) } @@ -351,7 +351,7 @@ func dataSourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error d.Set("secured_cookies", lb.SecuredCookies) d.Set("net_id", lb.NetId) d.Set("source_security_group", ssg) - d.Set("subnets", flattenStringList(lb.Subnets)) + d.Set("subnets", utils.StringListToInterfaceSlice(lb.Subnets)) d.SetId(*lb.LoadBalancerName) return nil diff --git a/outscale/data_source_outscale_load_balancer_listener_rule.go b/outscale/data_source_outscale_load_balancer_listener_rule.go index 3d3162a8e..c7eceb571 100644 --- a/outscale/data_source_outscale_load_balancer_listener_rule.go +++ b/outscale/data_source_outscale_load_balancer_listener_rule.go @@ -153,7 +153,7 @@ func dataSourceLoadBalancerLDRuleRead(d *schema.ResourceData, meta interface{}) } if lr.VmIds != nil { - d.Set("vm_ids", flattenStringList(lr.VmIds)) + d.Set("vm_ids", utils.StringListToInterfaceSlice(lr.VmIds)) } else { fmt.Errorf("Malformated listener rule") } diff --git a/outscale/data_source_outscale_load_balancer_listener_rules.go b/outscale/data_source_outscale_load_balancer_listener_rules.go index 59499721b..fea6e8c0c 100644 --- a/outscale/data_source_outscale_load_balancer_listener_rules.go +++ b/outscale/data_source_outscale_load_balancer_listener_rules.go @@ -166,7 +166,7 @@ func dataSourceLoadBalancerLDRulesRead(d *schema.ResourceData, meta interface{}) } if lr.VmIds != nil { - l["vm_ids"] = flattenStringList(lr.VmIds) + l["vm_ids"] = utils.StringListToInterfaceSlice(lr.VmIds) } else { fmt.Errorf("Malformated listener rule") } diff --git a/outscale/data_source_outscale_load_balancer_tags.go b/outscale/data_source_outscale_load_balancer_tags.go index 109c1bb0f..75264e27a 100644 --- a/outscale/data_source_outscale_load_balancer_tags.go +++ b/outscale/data_source_outscale_load_balancer_tags.go @@ -31,7 +31,7 @@ func dataSourceLBUTagsRead(d *schema.ResourceData, meta interface{}) error { names := ename.([]interface{}) req := oscgo.ReadLoadBalancerTagsRequest{ - LoadBalancerNames: *expandStringList(names), + LoadBalancerNames: utils.InterfaceSliceToStringSlice(names), } var resp oscgo.ReadLoadBalancerTagsResponse diff --git a/outscale/data_source_outscale_load_balancer_vms.go b/outscale/data_source_outscale_load_balancer_vms.go index 296469566..eaa3a26af 100644 --- a/outscale/data_source_outscale_load_balancer_vms.go +++ b/outscale/data_source_outscale_load_balancer_vms.go @@ -2,6 +2,7 @@ package outscale import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/terraform-providers/terraform-provider-outscale/utils" ) func dataSourceLoadBalancerVms() *schema.Resource { @@ -37,6 +38,6 @@ func dataSourceLoadBalancerVmsRead(d *schema.ResourceData, return err } - d.Set("backend_vm_ids", flattenStringList(lb.BackendVmIds)) + d.Set("backend_vm_ids", utils.StringListToInterfaceSlice(lb.BackendVmIds)) return nil } diff --git a/outscale/data_source_outscale_load_balancers.go b/outscale/data_source_outscale_load_balancers.go index 7bc14d7e3..c1516d9c3 100644 --- a/outscale/data_source_outscale_load_balancers.go +++ b/outscale/data_source_outscale_load_balancers.go @@ -3,6 +3,7 @@ package outscale import ( "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/terraform-providers/terraform-provider-outscale/utils" ) func attrLBSchema() map[string]*schema.Schema { @@ -218,7 +219,7 @@ func dataSourceLoadBalancersRead(d *schema.ResourceData, meta interface{}) error l["dns_name"] = *v.DnsName l["access_log"] = flattenAccessLog(v.AccessLog) l["health_check"] = flattenHealthCheck(v.HealthCheck) - l["backend_vm_ids"] = flattenStringList(v.BackendVmIds) + l["backend_vm_ids"] = utils.StringListToInterfaceSlice(v.BackendVmIds) if v.Listeners != nil { l["listeners"] = flattenListeners(v.Listeners) } else { @@ -265,7 +266,7 @@ func dataSourceLoadBalancersRead(d *schema.ResourceData, meta interface{}) error } l["load_balancer_type"] = v.LoadBalancerType - l["security_groups"] = flattenStringList(v.SecurityGroups) + l["security_groups"] = utils.StringListToInterfaceSlice(v.SecurityGroups) ssg := make(map[string]string) if v.SourceSecurityGroup != nil { @@ -273,7 +274,7 @@ func dataSourceLoadBalancersRead(d *schema.ResourceData, meta interface{}) error ssg["security_group_name"] = *v.SourceSecurityGroup.SecurityGroupName } l["source_security_group"] = ssg - l["subnet_id"] = flattenStringList(v.Subnets) + l["subnet_id"] = utils.StringListToInterfaceSlice(v.Subnets) l["public_ip"] = v.PublicIp l["secured_cookies"] = v.SecuredCookies l["net_id"] = v.NetId diff --git a/outscale/data_source_outscale_net_access_point.go b/outscale/data_source_outscale_net_access_point.go index 14171ad5a..68e6bc6c4 100644 --- a/outscale/data_source_outscale_net_access_point.go +++ b/outscale/data_source_outscale_net_access_point.go @@ -112,7 +112,7 @@ func dataSourceNetAccessPointRead(d *schema.ResourceData, meta interface{}) erro nap := resp.GetNetAccessPoints()[0] d.Set("net_access_point_id", nap.NetAccessPointId) - d.Set("route_table_ids", flattenStringList(nap.RouteTableIds)) + d.Set("route_table_ids", utils.StringListToInterfaceSlice(nap.RouteTableIds)) d.Set("net_id", nap.NetId) d.Set("service_name", nap.ServiceName) d.Set("state", nap.State) diff --git a/outscale/data_source_outscale_net_access_points.go b/outscale/data_source_outscale_net_access_points.go index bbf74e24c..90f941797 100644 --- a/outscale/data_source_outscale_net_access_points.go +++ b/outscale/data_source_outscale_net_access_points.go @@ -177,7 +177,7 @@ func dataSourceNetAccessPointsRead(d *schema.ResourceData, meta interface{}) err n := make(map[string]interface{}) n["net_access_point_id"] = v.NetAccessPointId - n["route_table_ids"] = flattenStringList(v.RouteTableIds) + n["route_table_ids"] = utils.StringListToInterfaceSlice(v.RouteTableIds) n["net_id"] = v.NetId n["service_name"] = v.ServiceName n["state"] = v.State diff --git a/outscale/data_source_outscale_snapshot.go b/outscale/data_source_outscale_snapshot.go index d2f9c2019..9ccadb5e0 100644 --- a/outscale/data_source_outscale_snapshot.go +++ b/outscale/data_source_outscale_snapshot.go @@ -104,7 +104,7 @@ func dataSourceSnapshotRead(d *schema.ResourceData, meta interface{}) error { filter := oscgo.FiltersSnapshot{} if restorableUsersOk { - filter.SetPermissionsToCreateVolumeAccountIds(ExpandStringList(restorableUsers.([]interface{}))) + filter.SetPermissionsToCreateVolumeAccountIds(utils.InterfaceSliceToStringSlice(restorableUsers.([]interface{}))) params.SetFilters(filter) } if filtersOk { @@ -245,15 +245,3 @@ func buildSnapshotDataSourceFilters(set *schema.Set, filter *oscgo.FiltersSnapsh } return filter } - -// TODO MOVE To utils -func ExpandStringList(configured []interface{}) []string { - vs := make([]string, 0, len(configured)) - for _, v := range configured { - val, ok := v.(string) - if ok && val != "" { - vs = append(vs, v.(string)) - } - } - return vs -} diff --git a/outscale/data_source_outscale_snapshots.go b/outscale/data_source_outscale_snapshots.go index 279414c3b..844b7a931 100644 --- a/outscale/data_source_outscale_snapshots.go +++ b/outscale/data_source_outscale_snapshots.go @@ -122,18 +122,18 @@ func dataSourceSnapshotsRead(d *schema.ResourceData, meta interface{}) error { } filter := oscgo.FiltersSnapshot{} if restorableUsersOk { - filter.SetPermissionsToCreateVolumeAccountIds(ExpandStringList(restorableUsers.([]interface{}))) + filter.SetPermissionsToCreateVolumeAccountIds(utils.InterfaceSliceToStringSlice(restorableUsers.([]interface{}))) params.SetFilters(filter) } if filtersOk { buildSnapshotDataSourceFilters(filters.(*schema.Set), params.Filters) } if ownersOk { - filter.SetAccountIds(ExpandStringList(owners.([]interface{}))) + filter.SetAccountIds(utils.InterfaceSliceToStringSlice(owners.([]interface{}))) params.SetFilters(filter) } if snapshotIdsOk { - filter.SetSnapshotIds(ExpandStringList(snapshotIds.([]interface{}))) + filter.SetSnapshotIds(utils.InterfaceSliceToStringSlice(snapshotIds.([]interface{}))) params.SetFilters(filter) } diff --git a/outscale/data_source_outscale_vm_states.go b/outscale/data_source_outscale_vm_states.go index 9e62faa5b..d7dd08c06 100644 --- a/outscale/data_source_outscale_vm_states.go +++ b/outscale/data_source_outscale_vm_states.go @@ -60,7 +60,7 @@ func dataSourceVMStatesRead(d *schema.ResourceData, meta interface{}) error { } if instanceIdsOk { filter := oscgo.FiltersVmsState{} - filter.SetVmIds(ExpandStringList(instanceIds.([]interface{}))) + filter.SetVmIds(utils.InterfaceSliceToStringSlice(instanceIds.([]interface{}))) params.SetFilters(filter) } diff --git a/outscale/data_source_outscale_volumes.go b/outscale/data_source_outscale_volumes.go index 4c129ce2e..c2c7b6cd0 100644 --- a/outscale/data_source_outscale_volumes.go +++ b/outscale/data_source_outscale_volumes.go @@ -111,7 +111,7 @@ func datasourceVolumesRead(d *schema.ResourceData, meta interface{}) error { } if volumeIdsOk { - volIDs := expandStringValueList(volumeIds.([]interface{})) + volIDs := utils.InterfaceSliceToStringSlice(volumeIds.([]interface{})) filter := oscgo.FiltersVolume{} filter.SetVolumeIds(volIDs) params.SetFilters(filter) diff --git a/outscale/data_source_outscale_vpn_connections.go b/outscale/data_source_outscale_vpn_connections.go index f6d889409..8212c4b65 100644 --- a/outscale/data_source_outscale_vpn_connections.go +++ b/outscale/data_source_outscale_vpn_connections.go @@ -131,7 +131,7 @@ func dataSourceVPNConnectionsRead(d *schema.ResourceData, meta interface{}) erro if vpnConnectionOk { params.Filters = &oscgo.FiltersVpnConnection{ - VpnConnectionIds: expandStringValueListPointer(vpnConnectionIDs.([]interface{})), + VpnConnectionIds: utils.InterfaceSliceToStringSlicePtr(vpnConnectionIDs.([]interface{})), } } diff --git a/outscale/resource_outscale_api_access_rule.go b/outscale/resource_outscale_api_access_rule.go index 48d95446f..a93aea34d 100644 --- a/outscale/resource_outscale_api_access_rule.go +++ b/outscale/resource_outscale_api_access_rule.go @@ -60,18 +60,18 @@ func resourceApiAccessRuleCreate(d *schema.ResourceData, meta interface{}) error if val, ok := d.GetOk("ca_ids"); ok { checkParam = true - req.CaIds = expandSetStringList(val.(*schema.Set)) + req.CaIds = utils.SetToStringSlicePtr(val.(*schema.Set)) } if val, ok := d.GetOk("ip_ranges"); ok { checkParam = true - req.IpRanges = expandSetStringList(val.(*schema.Set)) + req.IpRanges = utils.SetToStringSlicePtr(val.(*schema.Set)) } if !checkParam { return fmt.Errorf("[DEBUG] Error 'ca_ids' or 'ip_ranges' field is require for API Access Rules creation") } if val, ok := d.GetOk("cns"); ok { - req.Cns = expandSetStringList(val.(*schema.Set)) + req.Cns = utils.SetToStringSlicePtr(val.(*schema.Set)) } if v, ok := d.GetOk("description"); ok { req.SetDescription(v.(string)) @@ -169,11 +169,11 @@ func resourceApiAccessRuleUpdate(d *schema.ResourceData, meta interface{}) error if val, ok := d.GetOk("ca_ids"); ok { checkParam = true - req.CaIds = expandSetStringList(val.(*schema.Set)) + req.CaIds = utils.SetToStringSlicePtr(val.(*schema.Set)) } if val, ok := d.GetOk("ip_ranges"); ok { checkParam = true - req.IpRanges = expandSetStringList(val.(*schema.Set)) + req.IpRanges = utils.SetToStringSlicePtr(val.(*schema.Set)) } if !checkParam { @@ -181,7 +181,7 @@ func resourceApiAccessRuleUpdate(d *schema.ResourceData, meta interface{}) error } if val, ok := d.GetOk("cns"); ok { - req.Cns = expandSetStringList(val.(*schema.Set)) + req.Cns = utils.SetToStringSlicePtr(val.(*schema.Set)) } if v, ok := d.GetOk("description"); ok { req.SetDescription(v.(string)) diff --git a/outscale/resource_outscale_dhcp_option.go b/outscale/resource_outscale_dhcp_option.go index 70fc6789e..102e00757 100644 --- a/outscale/resource_outscale_dhcp_option.go +++ b/outscale/resource_outscale_dhcp_option.go @@ -89,13 +89,13 @@ func resourceDHCPOptionCreate(d *schema.ResourceData, meta interface{}) error { createOpts.SetDomainName(domainName.(string)) } if okDomainNameServers { - createOpts.SetDomainNameServers(expandStringValueList(domainNameServers.([]interface{}))) + createOpts.SetDomainNameServers(utils.InterfaceSliceToStringSlice(domainNameServers.([]interface{}))) } if okLogServers { - createOpts.SetLogServers(expandStringValueList(logServers.([]interface{}))) + createOpts.SetLogServers(utils.InterfaceSliceToStringSlice(logServers.([]interface{}))) } if okNTPServers { - createOpts.SetNtpServers(expandStringValueList(ntpServers.([]interface{}))) + createOpts.SetNtpServers(utils.InterfaceSliceToStringSlice(ntpServers.([]interface{}))) } dhcp, _, err := createDhcpOption(conn, createOpts) diff --git a/outscale/resource_outscale_load_balancer.go b/outscale/resource_outscale_load_balancer.go index c7c42759d..98aba35de 100644 --- a/outscale/resource_outscale_load_balancer.go +++ b/outscale/resource_outscale_load_balancer.go @@ -209,24 +209,6 @@ func resourceLoadBalancer() *schema.Resource { } } -func expandStringList(ifs []interface{}) *[]string { - r := make([]string, len(ifs)) - - for k, v := range ifs { - r[k] = v.(string) - } - return &r -} - -func expandSetStringList(ifs *schema.Set) *[]string { - r := make([]string, ifs.Len()) - - for k, v := range ifs.List() { - r[k] = v.(string) - } - return &r -} - // Flattens an array of Listeners into a []map[string]interface{} func flattenListeners(list *[]oscgo.Listener) []map[string]interface{} { if list == nil { @@ -246,7 +228,7 @@ func flattenListeners(list *[]oscgo.Listener) []map[string]interface{} { listener["server_certificate_id"] = *i.ServerCertificateId } - listener["policy_names"] = flattenStringList(i.PolicyNames) + listener["policy_names"] = utils.StringListToInterfaceSlice(i.PolicyNames) result = append(result, listener) } return result @@ -418,12 +400,12 @@ func resourceLoadBalancerCreate_(d *schema.ResourceData, meta interface{}, isUpd } if v, ok := d.GetOk("security_groups"); ok { - req.SecurityGroups = expandSetStringList(v.(*schema.Set)) + req.SecurityGroups = utils.SetToStringSlicePtr(v.(*schema.Set)) } v_sb, sb_ok := d.GetOk("subnets") if sb_ok { - req.Subnets = expandStringList(v_sb.([]interface{})) + req.Subnets = utils.InterfaceSliceToStringList(v_sb.([]interface{})) } v_srn, srn_ok := d.GetOk("subregion_names") @@ -432,7 +414,7 @@ func resourceLoadBalancerCreate_(d *schema.ResourceData, meta interface{}, isUpd } if srn_ok && sb_ok == false { - req.SubregionNames = expandStringList(v_srn.([]interface{})) + req.SubregionNames = utils.InterfaceSliceToStringList(v_srn.([]interface{})) } log.Printf("[DEBUG] Load Balancer request configuration: %#v", *req) @@ -482,17 +464,6 @@ func resourceLoadBalancerCreate_(d *schema.ResourceData, meta interface{}, isUpd return resourceLoadBalancerRead(d, meta) } -func flattenStringList(list *[]string) []interface{} { - if list == nil { - return make([]interface{}, 0) - } - vs := make([]interface{}, 0, len(*list)) - for _, v := range *list { - vs = append(vs, v) - } - return vs -} - func readResourceLb(conn *oscgo.APIClient, elbName string) (*oscgo.LoadBalancer, *oscgo.ReadLoadBalancersResponse, error) { filter := &oscgo.FiltersLoadBalancer{ LoadBalancerNames: &[]string{elbName}, @@ -536,12 +507,12 @@ func resourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error { return err } - d.Set("subregion_names", flattenStringList(lb.SubregionNames)) + d.Set("subregion_names", utils.StringListToInterfaceSlice(lb.SubregionNames)) d.Set("dns_name", lb.DnsName) d.Set("health_check", flattenHealthCheck(lb.HealthCheck)) d.Set("access_log", flattenAccessLog(lb.AccessLog)) - d.Set("backend_vm_ids", flattenStringList(lb.BackendVmIds)) + d.Set("backend_vm_ids", utils.StringListToInterfaceSlice(lb.BackendVmIds)) if err := d.Set("listeners", flattenListeners(lb.Listeners)); err != nil { log.Printf("[DEBUG] out err %v", err) return err @@ -587,7 +558,7 @@ func resourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error { d.Set("load_balancer_type", lb.LoadBalancerType) if lb.SecurityGroups != nil { - d.Set("security_groups", flattenStringList(lb.SecurityGroups)) + d.Set("security_groups", utils.StringListToInterfaceSlice(lb.SecurityGroups)) } else { d.Set("security_groups", make([]map[string]interface{}, 0)) } @@ -597,7 +568,7 @@ func resourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error { ssg["security_group_account_id"] = *lb.SourceSecurityGroup.SecurityGroupAccountId } d.Set("source_security_group", ssg) - d.Set("subnets", flattenStringList(lb.Subnets)) + d.Set("subnets", utils.StringListToInterfaceSlice(lb.Subnets)) d.Set("public_ip", lb.PublicIp) d.Set("secured_cookies", lb.SecuredCookies) @@ -617,7 +588,7 @@ func resourceLoadBalancerUpdate(d *schema.ResourceData, meta interface{}) error LoadBalancerName: d.Id(), } nSg, _ := d.GetOk("security_groups") - req.SecurityGroups = expandSetStringList(nSg.(*schema.Set)) + req.SecurityGroups = utils.SetToStringSlicePtr(nSg.(*schema.Set)) var err error err = resource.Retry(1*time.Minute, func() *resource.RetryError { @@ -774,8 +745,8 @@ func resourceLoadBalancerUpdate(d *schema.ResourceData, meta interface{}) error o, n := d.GetChange("backend_vm_ids") os := o.(*schema.Set) ns := n.(*schema.Set) - remove := expandInstanceString(os.Difference(ns).List()) - add := expandInstanceString(ns.Difference(os).List()) + remove := utils.SetToStringSlice(os.Difference(ns)) + add := utils.SetToStringSlice(ns.Difference(os)) if len(add) > 0 { @@ -833,12 +804,12 @@ func resourceLoadBalancerUpdate(d *schema.ResourceData, meta interface{}) error req := oscgo.UpdateLoadBalancerRequest{ LoadBalancerName: d.Id(), HealthCheck: &oscgo.HealthCheck{ - HealthyThreshold: int32(check["healthy_threshold"].(int)), - UnhealthyThreshold: int32(check["unhealthy_threshold"].(int)), - CheckInterval: int32(check["check_interval"].(int)), + HealthyThreshold: check["healthy_threshold"].(int32), + UnhealthyThreshold: check["unhealthy_threshold"].(int32), + CheckInterval: check["check_interval"].(int32), Protocol: check["protocol"].(string), - Port: int32(check["port"].(int)), - Timeout: int32(check["timeout"].(int)), + Port: check["port"].(int32), + Timeout: check["timeout"].(int32), }, } if check["path"] != nil { @@ -996,30 +967,17 @@ func resourceLoadBalancerDelete(d *schema.ResourceData, meta interface{}) error return nil } -// Expands an array of String Instance IDs into a []Instances -func expandInstanceString(list []interface{}) []string { - result := make([]string, 0, len(list)) - for _, i := range list { - result = append(result, i.(string)) - } - return result -} - -func formatInt32(n int32) string { - return strconv.FormatInt(int64(n), 10) -} - func flattenHealthCheck(check *oscgo.HealthCheck) map[string]interface{} { chk := make(map[string]interface{}) if check != nil { - h := formatInt32(check.HealthyThreshold) - i := formatInt32(check.CheckInterval) + h := utils.I32toa(check.HealthyThreshold) + i := utils.I32toa(check.CheckInterval) pa := check.Path - po := formatInt32(check.Port) + po := utils.I32toa(check.Port) pr := check.Protocol - ti := formatInt32(check.Timeout) - u := formatInt32(check.UnhealthyThreshold) + ti := utils.I32toa(check.Timeout) + u := utils.I32toa(check.UnhealthyThreshold) chk["healthy_threshold"] = h chk["check_interval"] = i diff --git a/outscale/resource_outscale_load_balancer_attributes.go b/outscale/resource_outscale_load_balancer_attributes.go index d1bdb63c9..0e0b97a57 100644 --- a/outscale/resource_outscale_load_balancer_attributes.go +++ b/outscale/resource_outscale_load_balancer_attributes.go @@ -422,7 +422,7 @@ func resourceLoadBalancerAttributesRead(d *schema.ResourceData, meta interface{} d.Set("source_security_group", sgr) if lb.SecurityGroups != nil { - d.Set("security_groups", flattenStringList(lb.SecurityGroups)) + d.Set("security_groups", utils.StringListToInterfaceSlice(lb.SecurityGroups)) } else { d.Set("security_groups", make([]map[string]interface{}, 0)) } @@ -441,11 +441,11 @@ func resourceLoadBalancerAttributesRead(d *schema.ResourceData, meta interface{} d.Set("tags", make([]map[string]interface{}, 0)) } - d.Set("backend_vm_ids", flattenStringList(lb.BackendVmIds)) + d.Set("backend_vm_ids", utils.StringListToInterfaceSlice(lb.BackendVmIds)) - d.Set("subnets", flattenStringList(lb.Subnets)) + d.Set("subnets", utils.StringListToInterfaceSlice(lb.Subnets)) - d.Set("subregion_names", flattenStringList(lb.SubregionNames)) + d.Set("subregion_names", utils.StringListToInterfaceSlice(lb.SubregionNames)) if lb.ApplicationStickyCookiePolicies != nil { app := make([]map[string]interface{}, diff --git a/outscale/resource_outscale_load_balancer_listener_rule.go b/outscale/resource_outscale_load_balancer_listener_rule.go index b08437c58..a6f1d2b39 100644 --- a/outscale/resource_outscale_load_balancer_listener_rule.go +++ b/outscale/resource_outscale_load_balancer_listener_rule.go @@ -102,7 +102,7 @@ func resourceLoadBalancerListenerRuleCreate(d *schema.ResourceData, meta interfa req := &oscgo.CreateListenerRuleRequest{} if vids, ok := d.GetOk("vm_ids"); ok { - req.VmIds = *expandSetStringList(vids.(*schema.Set)) + req.SetVmIds(utils.SetToStringSlice(vids.(*schema.Set))) } else { return fmt.Errorf("expect vm_ids") } @@ -234,7 +234,7 @@ func resourceLoadBalancerListenerRuleRead(d *schema.ResourceData, meta interface return err } if lr.VmIds != nil { - d.Set("vm_ids", flattenStringList(lr.VmIds)) + d.Set("vm_ids", utils.StringListToInterfaceSlice(lr.VmIds)) } return nil } diff --git a/outscale/resource_outscale_load_balancer_policy.go b/outscale/resource_outscale_load_balancer_policy.go index 897c34af2..c8225b0c3 100644 --- a/outscale/resource_outscale_load_balancer_policy.go +++ b/outscale/resource_outscale_load_balancer_policy.go @@ -290,17 +290,17 @@ func resourceAppCookieStickinessPolicyCreate(d *schema.ResourceData, meta interf lb := resp.LoadBalancer d.Set("access_log", flattenAccessLog(lb.AccessLog)) d.Set("listeners", flattenListeners(lb.Listeners)) - d.Set("subregion_names", flattenStringList(lb.SubregionNames)) + d.Set("subregion_names", utils.StringListToInterfaceSlice(lb.SubregionNames)) d.Set("load_balancer_type", lb.LoadBalancerType) if lb.SecurityGroups != nil { - d.Set("security_groups", flattenStringList(lb.SecurityGroups)) + d.Set("security_groups", utils.StringListToInterfaceSlice(lb.SecurityGroups)) } else { d.Set("security_groups", make([]map[string]interface{}, 0)) } d.Set("dns_name", lb.DnsName) - d.Set("subnets", flattenStringList(lb.Subnets)) + d.Set("subnets", utils.StringListToInterfaceSlice(lb.Subnets)) d.Set("health_check", flattenHealthCheck(lb.HealthCheck)) - d.Set("backend_vm_ids", flattenStringList(lb.BackendVmIds)) + d.Set("backend_vm_ids", utils.StringListToInterfaceSlice(lb.BackendVmIds)) if lb.Tags != nil { ta := make([]map[string]interface{}, len(*lb.Tags)) for k1, v1 := range *lb.Tags { diff --git a/outscale/resource_outscale_net_access_point.go b/outscale/resource_outscale_net_access_point.go index e2e344795..5a9a801ee 100644 --- a/outscale/resource_outscale_net_access_point.go +++ b/outscale/resource_outscale_net_access_point.go @@ -63,8 +63,8 @@ func resourceNetAccessPointUpdate(d *schema.ResourceData, meta interface{}) erro o, n := d.GetChange("route_table_ids") log.Printf("[DEBUG] it change !: %v %v", o, n) - oo := expandSetStringList(o.(*schema.Set)) - nn := expandSetStringList(n.(*schema.Set)) + oo := utils.SetToStringSlicePtr(o.(*schema.Set)) + nn := utils.SetToStringSlicePtr(n.(*schema.Set)) destroy := make([]string, 0) add := make([]string, 0) @@ -170,7 +170,7 @@ func resourceNetAccessPointCreate(d *schema.ResourceData, meta interface{}) erro req := &oscgo.CreateNetAccessPointRequest{} if v, ok := d.GetOk("route_table_ids"); ok { - req.RouteTableIds = expandSetStringList(v.(*schema.Set)) + req.RouteTableIds = utils.SetToStringSlicePtr(v.(*schema.Set)) } nid := d.Get("net_id") @@ -262,7 +262,7 @@ func resourceNetAccessPointRead(d *schema.ResourceData, meta interface{}) error nap := (*resp.NetAccessPoints)[0] - d.Set("route_table_ids", flattenStringList(nap.RouteTableIds)) + d.Set("route_table_ids", utils.StringListToInterfaceSlice(nap.RouteTableIds)) d.Set("net_id", nap.NetId) d.Set("service_name", nap.ServiceName) d.Set("state", nap.State) diff --git a/outscale/resource_outscale_nic.go b/outscale/resource_outscale_nic.go index cc2f10e91..4b1799f55 100644 --- a/outscale/resource_outscale_nic.go +++ b/outscale/resource_outscale_nic.go @@ -646,7 +646,7 @@ func resourceNicUpdate(d *schema.ResourceData, meta interface{}) error { if diff < 0 { input := oscgo.UnlinkPrivateIpsRequest{ NicId: d.Id(), - PrivateIps: expandStringValueList(prips[0:int(math.Abs(float64(diff)))]), + PrivateIps: utils.InterfaceSliceToStringSlice(prips[0:int(math.Abs(float64(diff)))]), } err := resource.Retry(5*time.Minute, func() *resource.RetryError { @@ -665,7 +665,7 @@ func resourceNicUpdate(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("security_group_ids") { - stringValueList := expandStringValueList(d.Get("security_group_ids").([]interface{})) + stringValueList := utils.InterfaceSliceToStringSlice(d.Get("security_group_ids").([]interface{})) request := oscgo.UpdateNicRequest{ NicId: d.Id(), SecurityGroupIds: &stringValueList, diff --git a/outscale/resource_outscale_nic_private_ip.go b/outscale/resource_outscale_nic_private_ip.go index d9c1cb32a..d6957d621 100644 --- a/outscale/resource_outscale_nic_private_ip.go +++ b/outscale/resource_outscale_nic_private_ip.go @@ -72,7 +72,7 @@ func resourceNetworkInterfacePrivateIPCreate(d *schema.ResourceData, meta interf } if v, ok := d.GetOk("private_ips"); ok { - input.SetPrivateIps(expandStringValueList(v.([]interface{}))) + input.SetPrivateIps(utils.InterfaceSliceToStringSlice(v.([]interface{}))) } var err error @@ -178,7 +178,7 @@ func resourceNetworkInterfacePrivateIPDelete(d *schema.ResourceData, meta interf } if v, ok := d.GetOk("private_ips"); ok { - input.SetPrivateIps(expandStringValueList(v.([]interface{}))) + input.SetPrivateIps(utils.InterfaceSliceToStringSlice(v.([]interface{}))) } var err error diff --git a/outscale/resource_outscale_security_group_rule.go b/outscale/resource_outscale_security_group_rule.go index 3115fd8e5..0bcab79bf 100644 --- a/outscale/resource_outscale_security_group_rule.go +++ b/outscale/resource_outscale_security_group_rule.go @@ -210,11 +210,11 @@ func expandRules(d *schema.ResourceData) *[]oscgo.SecurityGroupRule { SecurityGroupsMembers: expandSecurityGroupsMembers(r["security_groups_members"].([]interface{})), } - if ipRanges := expandStringValueListPointer(r["ip_ranges"].([]interface{})); len(*ipRanges) > 0 { - rules[i].IpRanges = expandStringValueListPointer(r["ip_ranges"].([]interface{})) + if ipRanges := utils.InterfaceSliceToStringSlicePtr(r["ip_ranges"].([]interface{})); len(*ipRanges) > 0 { + rules[i].IpRanges = utils.InterfaceSliceToStringSlicePtr(r["ip_ranges"].([]interface{})) } - if serviceIDs := expandStringValueListPointer(r["service_ids"].([]interface{})); len(*serviceIDs) > 0 { - rules[i].ServiceIds = expandStringValueListPointer(r["service_ids"].([]interface{})) + if serviceIDs := utils.InterfaceSliceToStringSlicePtr(r["service_ids"].([]interface{})); len(*serviceIDs) > 0 { + rules[i].ServiceIds = utils.InterfaceSliceToStringSlicePtr(r["service_ids"].([]interface{})) } if v, ok := r["from_port_range"]; ok { rules[i].FromPortRange = pointy.Int32(cast.ToInt32(v)) diff --git a/outscale/resource_outscale_vm.go b/outscale/resource_outscale_vm.go index eefddb474..9d07c5e1e 100644 --- a/outscale/resource_outscale_vm.go +++ b/outscale/resource_outscale_vm.go @@ -804,7 +804,7 @@ func resourceVMUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("security_group_ids") && !d.IsNewResource() { opts := oscgo.UpdateVmRequest{VmId: id} - opts.SetSecurityGroupIds(expandStringValueList(d.Get("security_group_ids").([]interface{}))) + opts.SetSecurityGroupIds(utils.InterfaceSliceToStringSlice(d.Get("security_group_ids").([]interface{}))) if err := updateVmAttr(conn, opts); err != nil { return err } @@ -812,7 +812,7 @@ func resourceVMUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("security_group_names") && !d.IsNewResource() { opts := oscgo.UpdateVmRequest{VmId: id} - opts.SetSecurityGroupIds(expandStringValueList(d.Get("security_group_names").([]interface{}))) + opts.SetSecurityGroupIds(utils.InterfaceSliceToStringSlice(d.Get("security_group_names").([]interface{}))) if err := updateVmAttr(conn, opts); err != nil { return err } @@ -996,15 +996,15 @@ func buildCreateVmsRequest(d *schema.ResourceData, meta interface{}) (oscgo.Crea request.SetNics(nics) } - if privateIPs := expandStringValueList(d.Get("private_ips").([]interface{})); len(privateIPs) > 0 { + if privateIPs := utils.InterfaceSliceToStringSlice(d.Get("private_ips").([]interface{})); len(privateIPs) > 0 { request.SetPrivateIps(privateIPs) } - if sgIDs := expandStringValueList(d.Get("security_group_ids").([]interface{})); len(sgIDs) > 0 { + if sgIDs := utils.InterfaceSliceToStringSlice(d.Get("security_group_ids").([]interface{})); len(sgIDs) > 0 { request.SetSecurityGroupIds(sgIDs) } - if sgNames := expandStringValueList(d.Get("security_group_names").([]interface{})); len(sgNames) > 0 { + if sgNames := utils.InterfaceSliceToStringSlice(d.Get("security_group_names").([]interface{})); len(sgNames) > 0 { request.SetSecurityGroups(sgNames) } @@ -1133,7 +1133,7 @@ func buildNetworkInterfaceOpts(d *schema.ResourceData) []oscgo.NicForVmCreation ni.SetPrivateIps(expandPrivatePublicIps(nic["private_ips"].(*schema.Set))) ni.SetSubnetId(nic["subnet_id"].(string)) - if sg := expandStringValueList(nic["security_group_ids"].([]interface{})); len(sg) > 0 { + if sg := utils.InterfaceSliceToStringSlice(nic["security_group_ids"].([]interface{})); len(sg) > 0 { ni.SetSecurityGroupIds(sg) } diff --git a/utils/utils.go b/utils/utils.go index 6e9860cba..3a76b73e6 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -12,6 +12,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) // PrintToJSON method helper to debug responses @@ -146,3 +147,47 @@ func CheckThrottling(errCode int, err error) *resource.RetryError { } return resource.NonRetryableError(err) } + +func InterfaceSliceToStringSlicePtr(slice []interface{}) *[]string { + result := InterfaceSliceToStringSlice(slice) + return &result +} + +func SetToStringSlice(set *schema.Set) []string { + return InterfaceSliceToStringSlice(set.List()) +} + +func SetToStringSlicePtr(set *schema.Set) *[]string { + return InterfaceSliceToStringSlicePtr(set.List()) +} + +func InterfaceSliceToStringSlice(slice []interface{}) []string { + result := make([]string, 0, len(slice)) + for _, v := range slice { + val, ok := v.(string) + if ok && val != "" { + result = append(result, v.(string)) + } + } + return result +} + +func InterfaceSliceToStringList(slice []interface{}) *[]string { + res := InterfaceSliceToStringSlice(slice) + return &res +} + +func StringListToInterfaceSlice(list *[]string) []interface{} { + if list == nil { + return make([]interface{}, 0) + } + vs := make([]interface{}, 0, len(*list)) + for _, v := range *list { + vs = append(vs, v) + } + return vs +} + +func I32toa(i int32) string { + return strconv.FormatInt(int64(i), 10) +}