From 3ed19af2dfad5acb7bec8c4500292be0e928d4ef Mon Sep 17 00:00:00 2001 From: Chris Collins Date: Tue, 14 Mar 2023 12:33:50 -1000 Subject: [PATCH] Default to OCM login via environment `osdctl` currently expects an OCM connection in order to run, but it contains the packages necessary to build that connection automatically based on the environment, as other OCM integrations do. This commit adds support for automatically building the OCM connection based on the presence of the `OCM_TOKEN` and `OCM_URL` environment variables. This will fall back to the existing connection usage if these environment variables are not set. Signed-off-by: Chris Collins --- pkg/utils/ocm.go | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/pkg/utils/ocm.go b/pkg/utils/ocm.go index c3f93012..0e5b6345 100644 --- a/pkg/utils/ocm.go +++ b/pkg/utils/ocm.go @@ -4,16 +4,33 @@ import ( "encoding/json" "fmt" "log" + "os" "strings" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/openshift-online/ocm-cli/pkg/ocm" sdk "github.com/openshift-online/ocm-sdk-go" v1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1" ) const ClusterServiceClusterSearch = "id = '%s' or name = '%s' or external_id = '%s'" +const ( + productionURL = "https://api.openshift.com" + stagingURL = "https://api.stage.openshift.com" + integrationURL = "https://api.integration.openshift.com" +) + +var urlAliases = map[string]string{ + "production": productionURL, + "prod": productionURL, + "prd": productionURL, + "staging": stagingURL, + "stage": stagingURL, + "stg": stagingURL, + "integration": integrationURL, + "int": integrationURL, +} + // GetClusterAnyStatus returns an OCM cluster object given an OCM connection and cluster id // (internal and external ids both supported). func GetClusterAnyStatus(conn *sdk.Connection, clusterId string) (*v1.Cluster, error) { @@ -104,7 +121,26 @@ func GenerateQuery(clusterIdentifier string) string { } func CreateConnection() *sdk.Connection { - connection, err := ocm.NewConnection().Build() + token := os.Getenv("OCM_TOKEN") + url := os.Getenv("OCM_URL") + + connectionBuilder := sdk.NewConnectionBuilder() + + if token != "" { + connectionBuilder.Tokens(token) + } + + if url != "" { + gatewayURL, ok := urlAliases[url] + if !ok { + fmt.Println("Invalid OCM_URL found: ", url) + fmt.Println("Valid URL aliases are: 'production', 'staging', 'integration'") + } + connectionBuilder.URL(gatewayURL) + } + + connection, err := connectionBuilder.Build() + if err != nil { if strings.Contains(err.Error(), "Not logged in, run the") { log.Fatalf("Failed to create OCM connection: Authentication error, run the 'ocm login' command first.")