Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable setting credentials using profile default:(~/.osc/config.json) #481

Merged
merged 4 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/nav-inc/datetime v0.1.3
github.com/outscale/osc-sdk-go/v2 v2.23.0
github.com/spf13/cast v1.6.0
github.com/tidwall/gjson v1.18.0
)

require (
Expand Down Expand Up @@ -51,6 +52,8 @@ require (
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/oklog/run v1.1.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect
github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
Expand Down
7 changes: 7 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,13 @@ github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI=
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
Expand Down
20 changes: 11 additions & 9 deletions outscale/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@ import (

// Config ...
type Config struct {
AccessKeyID string
SecretKeyID string
Region string
TokenID string
Endpoints map[string]interface{}
X509cert string
X509key string
Insecure bool
AccessKeyID string
SecretKeyID string
Region string
TokenID string
Endpoints map[string]interface{}
X509CertPath string
X509KeyPath string
Insecure bool
ConfigFilePath string
Profile string
}

// OutscaleClient client
Expand All @@ -31,7 +33,7 @@ type OutscaleClient struct {
// Client ...
func (c *Config) Client() (*OutscaleClient, error) {
tlsconfig := &tls.Config{InsecureSkipVerify: c.Insecure}
cert, err := tls.LoadX509KeyPair(c.X509cert, c.X509key)
cert, err := tls.LoadX509KeyPair(c.X509CertPath, c.X509KeyPath)
if err == nil {
tlsconfig = &tls.Config{
InsecureSkipVerify: false,
Expand Down
10 changes: 4 additions & 6 deletions outscale/data_source_outscale_load_balancer_vms.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,14 @@ func DataSourceOutscaleLoadBalancerVms() *schema.Resource {
return &schema.Resource{
Read: DataSourceOutscaleLoadBalancerVmsRead,
Schema: getDataSourceSchemas(map[string]*schema.Schema{
"filter": dataSourceFiltersSchema(),
"load_balancer_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
Computed: true,
},

"backend_vm_ids": {
Type: schema.TypeList,
ForceNew: true,
Required: true,
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"request_id": {
Expand Down
4 changes: 2 additions & 2 deletions outscale/data_source_outscale_net_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ func TestAccNet_DataSource_basic(t *testing.T) {
{
Config: testAccDataSourceOutscaleVpcConfig(ipRange, tag),
Check: resource.ComposeTestCheckFunc(
testAccDataSourceOutscaleVpcCheck("data.outscale_net.by_id", ipRange, tag),
testAccDataSourceOutscaleVpcCheck("data.outscale_net.by_id", ipRange),
),
},
},
})
}

func testAccDataSourceOutscaleVpcCheck(name, ipRange, tag string) resource.TestCheckFunc {
func testAccDataSourceOutscaleVpcCheck(name, ipRange string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[name]
if !ok {
Expand Down
6 changes: 1 addition & 5 deletions outscale/data_source_outscale_nic.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,17 +244,13 @@ func DataSourceOutscaleNicRead(d *schema.ResourceData, meta interface{}) error {
return nil
})

if err != nil {
return fmt.Errorf("Error describing Network Interfaces : %s", err)
}

if err != nil {
if statusCode == http.StatusNotFound {
// The ENI is gone now, so just remove it from the state
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving ENI: %s", err)
return fmt.Errorf("Error describing Network Interfaces: %s", err)
}
if err := utils.IsResponseEmptyOrMutiple(len(resp.GetNics()), "Nic"); err != nil {
return err
Expand Down
4 changes: 0 additions & 4 deletions outscale/data_source_outscale_route_tables.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,6 @@ func DataSourceOutscaleRouteTablesRead(d *schema.ResourceData, meta interface{})
return fmt.Errorf("[DEBUG] Error reading Internet Services (%s)", errString)
}

if err != nil {
return err
}

rt := resp.GetRouteTables()
if len(rt) == 0 {
return fmt.Errorf("your query returned no results, please change your search criteria and try again")
Expand Down
6 changes: 2 additions & 4 deletions outscale/data_source_outscale_virtual_gateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccOthers_DataSourceVirtualGateway_unattached(t *testing.T) {
//t.Skip()
t.Parallel()
rInt := acctest.RandInt()

resource.Test(t, resource.TestCase{
PreCheck: func() {
Expand All @@ -20,7 +18,7 @@ func TestAccOthers_DataSourceVirtualGateway_unattached(t *testing.T) {
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceOutscaleVirtualGatewayUnattachedConfig(rInt),
Config: testAccDataSourceOutscaleVirtualGatewayUnattachedConfig(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrPair(
"data.outscale_virtual_gateway.test_by_id", "id",
Expand All @@ -33,7 +31,7 @@ func TestAccOthers_DataSourceVirtualGateway_unattached(t *testing.T) {
})
}

func testAccDataSourceOutscaleVirtualGatewayUnattachedConfig(rInt int) string {
func testAccDataSourceOutscaleVirtualGatewayUnattachedConfig() string {
return fmt.Sprintf(`
resource "outscale_virtual_gateway" "unattached" {
connection_type = "ipsec.1"
Expand Down
7 changes: 2 additions & 5 deletions outscale/data_source_outscale_virtual_gateways_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,26 @@ import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccOthers_DataSourceVpnGateways_unattached(t *testing.T) {
//t.Skip()
t.Parallel()
rInt := acctest.RandInt()

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceOutscaleVpnGatewaysUnattachedConfig(rInt),
Config: testAccDataSourceOutscaleVpnGatewaysUnattachedConfig(),
},
},
})
}

func testAccDataSourceOutscaleVpnGatewaysUnattachedConfig(rInt int) string {
func testAccDataSourceOutscaleVpnGatewaysUnattachedConfig() string {
return fmt.Sprintf(`
resource "outscale_virtual_gateway" "unattached" {
connection_type = "ipsec.1"
Expand Down
2 changes: 1 addition & 1 deletion outscale/data_source_outscale_vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func DataSourceOutscaleVMRead(d *schema.ResourceData, meta interface{}) error {
instanceID, instanceIDOk := d.GetOk("vm_id")
var err error
if !filtersOk && !instanceIDOk {
return fmt.Errorf("One of filters, or instance_id must be assigned")
return fmt.Errorf("one of filters, or instance_id must be assigned")
}
// Build up search parameters
params := oscgo.ReadVmsRequest{}
Expand Down
2 changes: 1 addition & 1 deletion outscale/data_source_outscale_vm_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestAccVM_TypesDataSource_basic(t *testing.T) {
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceOutscaleVMTypesConfig(omi, "tinav4.c1r1p1"),
Config: testAccDataSourceOutscaleVMTypesConfig(omi, "tinav5.c2r2p2"),
},
},
})
Expand Down
99 changes: 96 additions & 3 deletions outscale/framework_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"

"github.com/hashicorp/terraform-plugin-framework/diag"
Expand All @@ -13,6 +15,7 @@ import (
oscgo "github.com/outscale/osc-sdk-go/v2"
"github.com/outscale/terraform-provider-outscale/utils"
"github.com/outscale/terraform-provider-outscale/version"
"github.com/tidwall/gjson"
)

// OutscaleClient client
Expand All @@ -22,8 +25,14 @@ type OutscaleClient_fw struct {

// Client ...
func (c *frameworkProvider) Client_fw(ctx context.Context, data *ProviderModel, diags *diag.Diagnostics) (*OutscaleClient_fw, error) {
ok, err := IsProfileSet(data)
if err != nil {
return nil, err
}
if !ok {
setDefaultEnv(data)
}

setDefaultEnv(data)
tlsconfig := &tls.Config{InsecureSkipVerify: c.insecure}
cert, err := tls.LoadX509KeyPair(data.X509CertPath.ValueString(), data.X509KeyPath.ValueString())
if err == nil {
Expand Down Expand Up @@ -66,6 +75,90 @@ func (c *frameworkProvider) Client_fw(ctx context.Context, data *ProviderModel,
return client, nil
}

func IsProfileSet(data *ProviderModel) (bool, error) {
isProfSet := false
if profileName, ok := os.LookupEnv("OSC_PROFILE"); ok || !data.Profile.IsNull() {
if data.Profile.ValueString() != "" {
profileName = data.Profile.ValueString()
}

var profilePath string
if envPath, ok := os.LookupEnv("OSC_CONFIG_FILE"); ok || !data.ConfigFilePath.IsNull() {
if data.ConfigFilePath.ValueString() != "" {
profilePath = data.ConfigFilePath.ValueString()
} else {
profilePath = envPath
}
if profilePath == "" {
homePath, err := os.UserHomeDir()
if err != nil {
return isProfSet, err
}
profilePath = homePath + "/.osc/config.json"
}
}
jsonFile, err := ioutil.ReadFile(profilePath)
if err != nil {
return isProfSet, err
}
profile := gjson.GetBytes(jsonFile, profileName)
if !gjson.Valid(profile.String()) {
return isProfSet, fmt.Errorf("Invalid json profile file")
}
if !profile.Get("access_key").Exists() ||
!profile.Get("secret_key").Exists() {
return isProfSet, fmt.Errorf("Profile 'access_key' or 'secret_key' are not defined!")
}
setProfile(data, profile)
isProfSet = true
}
return isProfSet, nil
}

func setProfile(data *ProviderModel, profile gjson.Result) {
if data.AccessKeyId.IsNull() {
if accessKeyId := profile.Get("access_key").String(); accessKeyId != "" {
data.AccessKeyId = types.StringValue(accessKeyId)
}
}
if data.SecretKeyId.IsNull() {
if secretKeyId := profile.Get("secret_key").String(); secretKeyId != "" {
data.SecretKeyId = types.StringValue(secretKeyId)
}
}
if data.Region.IsNull() {
if profile.Get("region").Exists() {
if region := profile.Get("region").String(); region != "" {
data.Region = types.StringValue(region)
}
}
}
if data.X509CertPath.IsNull() {
if profile.Get("x509_cert_path").Exists() {
if x509Cert := profile.Get("x509_cert_path").String(); x509Cert != "" {
data.X509CertPath = types.StringValue(x509Cert)
}
}
}
if data.X509KeyPath.IsNull() {
if profile.Get("x509_key_path").Exists() {
if x509Key := profile.Get("x509_key_path").String(); x509Key != "" {
data.X509KeyPath = types.StringValue(x509Key)
}
}
}
if len(data.Endpoints) == 0 {
if profile.Get("endpoints").Exists() {
endpoints := profile.Get("endpoints").Value().(map[string]interface{})
if endpoint := endpoints["api"].(string); endpoint != "" {
endp := make([]Endpoints, 1)
endp[0].API = types.StringValue(endpoint)
data.Endpoints = endp
}
}
}
}

func setDefaultEnv(data *ProviderModel) {
if data.AccessKeyId.IsNull() {
if accessKeyId := utils.GetEnvVariableValue([]string{"OSC_ACCESS_KEY", "OUTSCALE_ACCESSKEYID"}); accessKeyId != "" {
Expand Down Expand Up @@ -96,9 +189,9 @@ func setDefaultEnv(data *ProviderModel) {
}
}
if len(data.Endpoints) == 0 {
if endpoints := utils.GetEnvVariableValue([]string{"OSC_ENDPOINT_API", "OUTSCALE_OAPI_URL"}); endpoints != "" {
if endpoint := utils.GetEnvVariableValue([]string{"OSC_ENDPOINT_API", "OUTSCALE_OAPI_URL"}); endpoint != "" {
endp := make([]Endpoints, 1)
endp[0].API = types.StringValue(endpoints)
endp[0].API = types.StringValue(endpoint)
data.Endpoints = endp
}
}
Expand Down
Loading
Loading