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

add helper to load env variables #541

Merged
merged 1 commit into from
Jun 29, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
260 changes: 260 additions & 0 deletions .osc-patches/22.06.28.add_helper_load_env_var.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
diff --git a/osc/config_env.go b/osc/config_env.go
new file mode 100644
index 00000000..9fcd634f
--- /dev/null
+++ b/osc/config_env.go
@@ -0,0 +1,140 @@
+/*
+ BSD 3-Clause License
+ Copyright (c) 2022, Outscale SAS
+ All rights reserved.
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+ * Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+package osc
+
+import (
+ "context"
+ "errors"
+ "os"
+)
+
+type ConfigEnv struct {
+ AccessKey *string
+ SecretKey *string
+ OutscaleApiEndpoint *string
+ ProfileName *string
+ Region *string
+}
+
+func NewConfigEnv() *ConfigEnv {
+ var configEnv ConfigEnv
+ if value, present := os.LookupEnv("OSC_ACCESS_KEY"); present {
+ configEnv.AccessKey = &value
+ }
+ if value, present := os.LookupEnv("OSC_SECRET_KEY"); present {
+ configEnv.SecretKey = &value
+ }
+ if value, present := os.LookupEnv("OSC_ENDPOINT_API"); present {
+ configEnv.OutscaleApiEndpoint = &value
+ }
+ if value, present := os.LookupEnv("OSC_PROFILE"); present {
+ configEnv.ProfileName = &value
+ }
+ if value, present := os.LookupEnv("OSC_REGION"); present {
+ configEnv.Region = &value
+ }
+ return &configEnv
+}
+
+func (configEnv *ConfigEnv) Configuration() (*Configuration, error) {
+ var config *Configuration
+
+ if configEnv.ProfileName != nil {
+ configFile, err := LoadDefaultConfigFile()
+ if err != nil {
+ return nil, err
+ }
+ config, err = configFile.Configuration(*configEnv.ProfileName)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ config = NewConfiguration()
+ default_region := "eu-west-2"
+ config.Servers = []ServerConfiguration{
+ {
+ Url: "https://api.{region}.outscale.com/api/v1",
+ Description: "Loaded from profile",
+ Variables: map[string]ServerVariable{
+ "region": ServerVariable{
+ Description: "Loaded from env variables",
+ DefaultValue: default_region,
+ EnumValues: []string{default_region},
+ },
+ },
+ },
+ }
+ }
+
+ // Overload with remaining environement variable values
+ if configEnv.OutscaleApiEndpoint != nil {
+ config.Servers[0].Url = *configEnv.OutscaleApiEndpoint
+ }
+
+ if configEnv.Region != nil && len(config.Servers) > 0 {
+ config.Servers[0].Variables["region"] = ServerVariable{
+ Description: "Loaded from env variables",
+ DefaultValue: *configEnv.Region,
+ EnumValues: []string{*configEnv.Region},
+ }
+ }
+ return config, nil
+}
+
+func (configEnv *ConfigEnv) Context(ctx context.Context) (context.Context, error) {
+ var accessKey *string
+ var secretKey *string
+
+ if configEnv.ProfileName != nil {
+ configFile, err := LoadDefaultConfigFile()
+ if err != nil {
+ return nil, err
+ }
+ profile, ok := configFile.profiles[*configEnv.ProfileName]
+ if !ok {
+ return nil, errors.New("profile not found for creating Context, did you load config file?")
+ }
+ accessKey = &profile.AccessKey
+ secretKey = &profile.SecretKey
+ }
+ // Overload with environement variable values
+ if configEnv.AccessKey != nil {
+ accessKey = configEnv.AccessKey
+ }
+ if configEnv.SecretKey != nil {
+ secretKey = configEnv.SecretKey
+ }
+
+ if accessKey == nil || len(*accessKey) == 0 || secretKey == nil || len(*secretKey) == 0 {
+ return ctx, nil
+ }
+ ctx = context.WithValue(ctx, ContextAWSv4, AWSv4{
+ AccessKey: *accessKey,
+ SecretKey: *secretKey,
+ })
+ return ctx, nil
+}
diff --git a/osc/config_env_test.go b/osc/config_env_test.go
new file mode 100644
index 00000000..562783d9
--- /dev/null
+++ b/osc/config_env_test.go
@@ -0,0 +1,108 @@
+/*
+ BSD 3-Clause License
+ Copyright (c) 2022, Outscale SAS
+ All rights reserved.
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+ * Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+package osc
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path"
+ "testing"
+)
+
+func TestEnvVariablesAkSk(t *testing.T) {
+ configEnv := NewConfigEnv()
+ config, err := configEnv.Configuration()
+ if err != nil {
+ t.Fatalf("Cannot create configutation: %s", err.Error())
+ }
+ ctx, err := configEnv.Context(context.Background())
+ if err != nil {
+ t.Fatalf("Cannot create context for making a query: %s", err.Error())
+ }
+ testConfAndContextOk(t, config, &ctx)
+}
+
+func TestEnvVariablesWithProfile(t *testing.T) {
+ if err := os.Setenv("OSC_PROFILE", "SomeProfile"); err != nil {
+ t.Fatalf("Cannot set OSC_PROFILE: %s", err.Error())
+ }
+ ak := os.Getenv("OSC_ACCESS_KEY")
+ sk := os.Getenv("OSC_SECRET_KEY")
+ region := os.Getenv("OSC_REGION")
+ os.Unsetenv("OSC_ACCESS_KEY")
+ os.Unsetenv("OSC_SECRET_KEY")
+ os.Unsetenv("OSC_REGION")
+ defer os.Setenv("OSC_ACCESS_KEY", ak)
+ defer os.Setenv("OSC_SECRET_KEY", sk)
+ defer os.Setenv("OSC_REGION", region)
+
+ home, err := os.UserHomeDir()
+ if err != nil {
+ t.Fatalf("Cannot get user home dir: %s", err.Error())
+ }
+ configFolderPath := path.Join(home, ".osc")
+ configPath := path.Join(configFolderPath, "config.json")
+
+ os.RemoveAll(configFolderPath)
+ if err := os.Mkdir(configFolderPath, os.ModePerm); err != nil {
+ t.Fatalf("Cannot create .osc folder: %s", err.Error())
+ }
+ defer os.RemoveAll(configFolderPath)
+
+ content := fmt.Sprintf(`{
+ "SomeProfile": {
+ "access_key": "%s",
+ "secret_key": "%s",
+ "endpoints": {
+ "api": "api.%s.outscale.com/api/v1"
+ }
+ }}`, ak, sk, region)
+ if err := testDumpToFile(configPath, content); err != nil {
+ t.Fatalf("Error: %s", err.Error())
+ }
+
+ configEnv := NewConfigEnv()
+ config, err := configEnv.Configuration()
+ if err != nil {
+ t.Fatalf("Cannot create configutation: %s", err.Error())
+ }
+ ctx, err := configEnv.Context(context.Background())
+ if err != nil {
+ t.Fatalf("Cannot create context for making a query: %s", err.Error())
+ }
+ testConfAndContextOk(t, config, &ctx)
+}
+
+func testConfAndContextOk(t *testing.T, config *Configuration, ctx *context.Context) {
+ var err error
+ client := NewAPIClient(config)
+ _, _, err = client.SubregionApi.ReadSubregions(*ctx, nil)
+ if err != nil {
+ t.Fatalf("Cannot call ReadSubregions: %s", err.Error())
+ }
+}