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

Replace wif models and client with sdk #643

Merged
merged 6 commits into from
Jul 31, 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
256 changes: 142 additions & 114 deletions cmd/ocm/gcp/create-wif-config.go

Large diffs are not rendered by default.

96 changes: 50 additions & 46 deletions cmd/ocm/gcp/delete-wif-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ package gcp
import (
"context"
"fmt"
"strings"

"log"

"github.com/googleapis/gax-go/v2/apierror"
"google.golang.org/grpc/codes"

alphaocm "github.com/openshift-online/ocm-cli/pkg/alpha_ocm"
"github.com/openshift-online/ocm-cli/pkg/gcp"
"github.com/openshift-online/ocm-cli/pkg/models"
"github.com/openshift-online/ocm-cli/pkg/ocm"
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
"github.com/pkg/errors"
"google.golang.org/api/googleapi"

"github.com/spf13/cobra"
)
Expand All @@ -28,10 +27,10 @@ var (
// NewDeleteWorkloadIdentityConfiguration provides the "gcp delete wif-config" subcommand
func NewDeleteWorkloadIdentityConfiguration() *cobra.Command {
deleteWifConfigCmd := &cobra.Command{
Use: "wif-config [ID]",
Short: "Delete workload identity configuration",
Run: deleteWorkloadIdentityConfigurationCmd,
PersistentPreRun: validationForDeleteWorkloadIdentityConfigurationCmd,
Use: "wif-config [ID]",
Short: "Delete workload identity configuration",
RunE: deleteWorkloadIdentityConfigurationCmd,
PreRunE: validationForDeleteWorkloadIdentityConfigurationCmd,
}

deleteWifConfigCmd.PersistentFlags().BoolVar(&DeleteWifConfigOpts.DryRun, "dry-run", false,
Expand All @@ -42,99 +41,104 @@ func NewDeleteWorkloadIdentityConfiguration() *cobra.Command {
return deleteWifConfigCmd
}

func validationForDeleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func validationForDeleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
if len(argv) != 1 {
log.Fatal(
"Expected exactly one command line parameters containing the id " +
"of the WIF config.",
return fmt.Errorf(
"expected exactly one command line parameters containing the id " +
"of the WIF config",
)
}
return nil
}

func deleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func deleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
ctx := context.Background()

wifConfigId := argv[0]
if wifConfigId == "" {
log.Fatal("WIF config ID is required")
return fmt.Errorf("WIF config ID is required")
}

// Create clients
ocmClient, err := alphaocm.NewOcmClient()
// Create the client for the OCM API:
connection, err := ocm.NewConnection().Build()
if err != nil {
log.Fatalf("failed to create backend client: %v", err)
return errors.Wrapf(err, "Failed to create OCM connection")
}
defer connection.Close()

wifConfig, err := ocmClient.GetWifConfig(wifConfigId)
response, err := connection.ClustersMgmt().V1().GCP().WifConfigs().WifConfig(wifConfigId).Get().Send()
if err != nil {
log.Fatal(err)
return errors.Wrapf(err, "failed to get wif-config")
}
wifConfig := response.Body()

if DeleteWifConfigOpts.DryRun {
log.Printf("Writing script files to %s", DeleteWifConfigOpts.TargetDir)

err := createDeleteScript(DeleteWifConfigOpts.TargetDir, &wifConfig)
err := createDeleteScript(DeleteWifConfigOpts.TargetDir, wifConfig)
if err != nil {
log.Fatalf("Failed to create script files: %s", err)
return errors.Wrapf(err, "failed to create script files")
}
return
return nil
}

gcpClient, err := gcp.NewGcpClient(context.Background())
if err != nil {
log.Fatal(err)
return err
}

if err := deleteServiceAccounts(ctx, gcpClient, &wifConfig, true); err != nil {
log.Fatal(err)
if err := deleteServiceAccounts(ctx, gcpClient, wifConfig, true); err != nil {
return err
}

if err := deleteWorkloadIdentityPool(ctx, gcpClient, &wifConfig, true); err != nil {
log.Fatal(err)
if err := deleteWorkloadIdentityPool(ctx, gcpClient, wifConfig, true); err != nil {
return err
}

err = ocmClient.DeleteWifConfig(wifConfigId)
_, err = connection.ClustersMgmt().V1().GCP().WifConfigs().
WifConfig(wifConfigId).
Delete().
Send()
if err != nil {
log.Fatal(err)
return errors.Wrapf(err, "failed to delete wif config %q", wifConfigId)
}
return nil
}

func deleteServiceAccounts(ctx context.Context, gcpClient gcp.GcpClient,
wifConfig *models.WifConfigOutput, allowMissing bool) error {
wifConfig *cmv1.WifConfig, allowMissing bool) error {
log.Println("Deleting service accounts...")
projectId := wifConfig.Spec.ProjectId
projectId := wifConfig.Gcp().ProjectId()

for _, serviceAccount := range wifConfig.Status.ServiceAccounts {
serviceAccountID := serviceAccount.Id
for _, serviceAccount := range wifConfig.Gcp().ServiceAccounts() {
serviceAccountID := serviceAccount.ServiceAccountId()
log.Println("Deleting service account", serviceAccountID)
err := gcpClient.DeleteServiceAccount(serviceAccountID, projectId, allowMissing)
if err != nil {
return errors.Wrapf(err, "Failed to delete service account %s", serviceAccountID)
return errors.Wrapf(err, "Failed to delete service account %q", serviceAccountID)
}
}

return nil
}

func deleteWorkloadIdentityPool(ctx context.Context, gcpClient gcp.GcpClient,
wifConfig *models.WifConfigOutput, allowMissing bool) error {
wifConfig *cmv1.WifConfig, allowMissing bool) error {
log.Println("Deleting workload identity pool...")
projectId := wifConfig.Spec.ProjectId
poolName := wifConfig.Status.WorkloadIdentityPoolData.PoolId
projectId := wifConfig.Gcp().ProjectId()
poolName := wifConfig.Gcp().WorkloadIdentityPool().PoolId()
poolResource := fmt.Sprintf("projects/%s/locations/global/workloadIdentityPools/%s", projectId, poolName)

_, err := gcpClient.DeleteWorkloadIdentityPool(ctx, poolResource)
if err != nil {
pApiError, ok := err.(*apierror.APIError)
if ok {
if pApiError.GRPCStatus().Code() == codes.NotFound && allowMissing {
log.Printf("Workload identity pool %s not found", poolName)
return nil
}
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 &&
strings.Contains(gerr.Message, "Requested entity was not found") && allowMissing {
log.Printf("Workload identity pool %q not found", poolName)
return nil
}
return errors.Wrapf(err, "Failed to delete workload identity pool %s", poolName)
return errors.Wrapf(err, "Failed to delete workload identity pool %q", poolName)
}

log.Printf("Workload identity pool %s deleted", poolName)
log.Printf("Workload identity pool %q deleted", poolName)
return nil
}
43 changes: 22 additions & 21 deletions cmd/ocm/gcp/describe-wif-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,59 +2,60 @@ package gcp

import (
"fmt"
"log"
"os"
"text/tabwriter"

alphaocm "github.com/openshift-online/ocm-cli/pkg/alpha_ocm"
"github.com/openshift-online/ocm-cli/pkg/ocm"
"github.com/openshift-online/ocm-cli/pkg/urls"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

// NewDescribeWorkloadIdentityConfiguration provides the "gcp describe wif-config" subcommand
func NewDescribeWorkloadIdentityConfiguration() *cobra.Command {
describeWorkloadIdentityPoolCmd := &cobra.Command{
Use: "wif-config [ID]",
Short: "Show details of a wif-config.",
Run: describeWorkloadIdentityConfigurationCmd,
PersistentPreRun: validationForDescribeWorkloadIdentityConfigurationCmd,
Use: "wif-config [ID]",
Short: "Show details of a wif-config.",
RunE: describeWorkloadIdentityConfigurationCmd,
PreRunE: validationForDescribeWorkloadIdentityConfigurationCmd,
}

return describeWorkloadIdentityPoolCmd
}

func describeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func describeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
id, err := urls.Expand(argv)
if err != nil {
log.Fatalf("could not create URI: %v", err)
return errors.Wrapf(err, "could not create URI")
}

// Create the client for the OCM API:
ocmClient, err := alphaocm.NewOcmClient()
connection, err := ocm.NewConnection().Build()
if err != nil {
log.Fatalf("failed to create backend client: %v", err)
return errors.Wrapf(err, "Failed to create OCM connection")
}
defer connection.Close()

wifconfig, err := ocmClient.GetWifConfig(id)
response, err := connection.ClustersMgmt().V1().GCP().WifConfigs().WifConfig(id).Get().Send()
if err != nil {
log.Fatalf("failed to get wif-config: %v", err)
return errors.Wrapf(err, "failed to get wif-config")
}
wifConfig := response.Body()

// Print output
w := tabwriter.NewWriter(os.Stdout, 8, 0, 2, ' ', 0)

fmt.Fprintf(w, "ID:\t%s\n", wifconfig.Metadata.Id)
fmt.Fprintf(w, "Display Name:\t%s\n", wifconfig.Metadata.DisplayName)
fmt.Fprintf(w, "Project:\t%s\n", wifconfig.Spec.ProjectId)
fmt.Fprintf(w, "State:\t%s\n", wifconfig.Status.State)
fmt.Fprintf(w, "Summary:\t%s\n", wifconfig.Status.Summary)
fmt.Fprintf(w, "Issuer URL:\t%s\n", wifconfig.Status.WorkloadIdentityPoolData.IssuerUrl)
fmt.Fprintf(w, "ID:\t%s\n", wifConfig.ID())
fmt.Fprintf(w, "Display Name:\t%s\n", wifConfig.DisplayName())
fmt.Fprintf(w, "Project:\t%s\n", wifConfig.Gcp().ProjectId())
fmt.Fprintf(w, "Issuer URL:\t%s\n", wifConfig.Gcp().WorkloadIdentityPool().IdentityProvider().IssuerUrl())

w.Flush()
return w.Flush()
}

func validationForDescribeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func validationForDescribeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
if len(argv) != 1 {
log.Fatalf("Expected exactly one command line parameters containing the id of the WIF config.")
return fmt.Errorf("Expected exactly one command line parameters containing the id of the WIF config")
}
return nil
}
57 changes: 38 additions & 19 deletions cmd/ocm/gcp/generate-wif-script.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package gcp

import (
"context"
"fmt"
"log"

alphaocm "github.com/openshift-online/ocm-cli/pkg/alpha_ocm"
"github.com/openshift-online/ocm-cli/pkg/gcp"
"github.com/openshift-online/ocm-cli/pkg/ocm"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

Expand All @@ -16,11 +20,11 @@ var (

func NewGenerateCommand() *cobra.Command {
generateScriptCmd := &cobra.Command{
Use: "generate [wif-config ID]",
Short: "Generate script based on a wif-config",
Args: cobra.ExactArgs(1),
Run: generateCreateScriptCmd,
PersistentPreRun: validationForGenerateCreateScriptCmd,
Use: "generate [wif-config ID]",
Short: "Generate script based on a wif-config",
Args: cobra.ExactArgs(1),
RunE: generateCreateScriptCmd,
PreRunE: validationForGenerateCreateScriptCmd,
}

generateScriptCmd.PersistentFlags().StringVar(&GenerateScriptOpts.TargetDir, "output-dir", "",
Expand All @@ -29,37 +33,52 @@ func NewGenerateCommand() *cobra.Command {
return generateScriptCmd
}

func validationForGenerateCreateScriptCmd(cmd *cobra.Command, argv []string) {
func validationForGenerateCreateScriptCmd(cmd *cobra.Command, argv []string) error {
if len(argv) != 1 {
log.Fatal(
return fmt.Errorf(
"Expected exactly one command line parameters containing the id " +
"of the WIF config.",
)
}
return nil
}

func generateCreateScriptCmd(cmd *cobra.Command, argv []string) {
// Create the client for the OCM API:
ocmClient, err := alphaocm.NewOcmClient()
func generateCreateScriptCmd(cmd *cobra.Command, argv []string) error {
ctx := context.Background()

gcpClient, err := gcp.NewGcpClient(ctx)
if err != nil {
errors.Wrapf(err, "failed to initiate GCP client")
}

connection, err := ocm.NewConnection().Build()
if err != nil {
log.Fatalf("failed to create backend client: %v", err)
return errors.Wrapf(err, "Failed to create OCM connection")
}
defer connection.Close()

wifConfigId := argv[0]
if wifConfigId == "" {
log.Fatal("WIF config ID is required")
return fmt.Errorf("WIF config ID is required")
}

response, err := connection.ClustersMgmt().V1().GCP().WifConfigs().WifConfig(wifConfigId).Get().Send()
if err != nil {
return errors.Wrapf(err, "failed to get wif-config")
}
wifConfig := response.Body()

wifConfig, err := ocmClient.GetWifConfig(wifConfigId)
projectNum, err := gcpClient.ProjectNumberFromId(wifConfig.Gcp().ProjectId())
if err != nil {
log.Fatalf("failed to get wif-config: %v", err)
return errors.Wrapf(err, "failed to get project number from id")
}

log.Printf("Writing script files to %s", GenerateScriptOpts.TargetDir)
if err := createScript(GenerateScriptOpts.TargetDir, &wifConfig); err != nil {
log.Fatalf("failed to generate create script: %v", err)
if err := createScript(GenerateScriptOpts.TargetDir, wifConfig, projectNum); err != nil {
return errors.Wrapf(err, "failed to generate create script")
}
if err := createDeleteScript(GenerateScriptOpts.TargetDir, &wifConfig); err != nil {
log.Fatalf("failed to generate delete script: %v", err)
if err := createDeleteScript(GenerateScriptOpts.TargetDir, wifConfig); err != nil {
return errors.Wrapf(err, "failed to generate delete script")
}
return nil
}
Loading
Loading