cli: cleanup terraform files when create fails (#2282)

This commit is contained in:
Adrian Stobbe 2023-08-24 16:38:02 +02:00 committed by GitHub
parent b278b76df5
commit 9e79e2e0a1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 16 deletions

View file

@ -13,11 +13,12 @@ import (
"io"
"github.com/edgelesssys/constellation/v2/cli/internal/terraform"
"github.com/edgelesssys/constellation/v2/internal/constants"
)
// rollbacker does a rollback.
type rollbacker interface {
rollback(ctx context.Context, logLevel terraform.LogLevel) error
rollback(ctx context.Context, w io.Writer, logLevel terraform.LogLevel) error
}
// rollbackOnError calls rollback on the rollbacker if the handed error is not nil,
@ -28,7 +29,7 @@ func rollbackOnError(w io.Writer, onErr *error, roll rollbacker, logLevel terraf
}
fmt.Fprintf(w, "An error occurred: %s\n", *onErr)
fmt.Fprintln(w, "Attempting to roll back.")
if err := roll.rollback(context.Background(), logLevel); err != nil {
if err := roll.rollback(context.Background(), w, logLevel); err != nil {
*onErr = errors.Join(*onErr, fmt.Errorf("on rollback: %w", err)) // TODO(katexochen): print the error, or return it?
return
}
@ -39,8 +40,10 @@ type rollbackerTerraform struct {
client tfCommonClient
}
func (r *rollbackerTerraform) rollback(ctx context.Context, logLevel terraform.LogLevel) error {
func (r *rollbackerTerraform) rollback(ctx context.Context, w io.Writer, logLevel terraform.LogLevel) error {
if err := r.client.Destroy(ctx, logLevel); err != nil {
fmt.Fprintf(w, "Could not destroy the resources. Please delete the %q directory manually if no resources were created\n",
constants.TerraformWorkingDir)
return err
}
return r.client.CleanUpWorkspace()
@ -52,11 +55,13 @@ type rollbackerQEMU struct {
createdWorkspace bool
}
func (r *rollbackerQEMU) rollback(ctx context.Context, logLevel terraform.LogLevel) (retErr error) {
func (r *rollbackerQEMU) rollback(ctx context.Context, w io.Writer, logLevel terraform.LogLevel) (retErr error) {
if r.createdWorkspace {
retErr = r.client.Destroy(ctx, logLevel)
}
if retErr := errors.Join(retErr, r.libvirt.Stop(ctx)); retErr != nil {
fmt.Fprintf(w, "Could not destroy the resources. Please delete the %q directory manually if no resources were created\n",
constants.TerraformWorkingDir)
return retErr
}
return r.client.CleanUpWorkspace()