Repository: metal3-io/baremetal-operator

Issue:
Enable variable shadowing check in govet linter
If we enable variable shadowing check in govet, we get a lot of errors. Variable shadowing can cause hard to debug issues.

```diff
diff --git a/.golangci.yaml b/.golangci.yaml
index 075a0062..0302721d 100644
--- a/.golangci.yaml
+++ b/.golangci.yaml
@@ -124,6 +124,9 @@ linters-settings:
     - unnecessaryDefer
     - whyNoLint
     - wrapperFunc
+  govet:
+    enable:
+    - shadow
 issues:
   exclude-dirs:
   - mock*
```

leads to

```text
main.go:235:12: shadow: declaration of "err" shadows declaration at line 195 (govet)
		seconds, err := strconv.ParseInt(leaseDurationSeconds, 10, 16)
		         ^
main.go:246:12: shadow: declaration of "err" shadows declaration at line 195 (govet)
		seconds, err := strconv.ParseInt(renewDeadlineSeconds, 10, 16)
		         ^
main.go:257:12: shadow: declaration of "err" shadows declaration at line 195 (govet)
		seconds, err := strconv.ParseInt(retryPeriodSeconds, 10, 16)
		         ^
internal/controller/metal3.io/baremetalhost_controller.go:173:3: shadow: declaration of "err" shadows declaration at line 109 (govet)
		err := r.Update(ctx, host)
		^
internal/controller/metal3.io/baremetalhost_controller.go:1019:7: shadow: declaration of "err" shadows declaration at line 989 (govet)
			if err := r.Update(info.ctx, info.host); err != nil {
			   ^
internal/controller/metal3.io/baremetalhost_controller.go:1485:7: shadow: declaration of "err" shadows declaration at line 1476 (govet)
			if err := r.Status().Update(info.ctx, hfc); err != nil {
			   ^
internal/controller/metal3.io/baremetalhost_controller.go:1581:8: shadow: declaration of "err" shadows declaration at line 1534 (govet)
		hup, err := r.acquireHostUpdatePolicy(info)
		     ^
internal/controller/metal3.io/baremetalhost_controller.go:1813:6: shadow: declaration of "err" shadows declaration at line 1807 (govet)
		if err := r.Status().Update(info.ctx, dataImage); err != nil {
		   ^
internal/controller/metal3.io/baremetalhost_controller.go:1843:6: shadow: declaration of "err" shadows declaration at line 1837 (govet)
		if err := r.Status().Update(info.ctx, dataImage); err != nil {
		   ^
internal/controller/metal3.io/dataimage_controller.go:122:7: shadow: declaration of "err" shadows declaration at line 115 (govet)
			if err := r.Update(ctx, di); err != nil {
			   ^
internal/controller/metal3.io/preprovisioningimage_controller.go:85:6: shadow: declaration of "err" shadows declaration at line 74 (govet)
		if err := r.discardExistingImage(&img, log); err != nil {
		   ^
internal/controller/metal3.io/preprovisioningimage_controller.go:90:3: shadow: declaration of "err" shadows declaration at line 74 (govet)
		err := r.Update(ctx, &img)
		^
internal/controller/metal3.io/preprovisioningimage_controller.go:100:3: shadow: declaration of "err" shadows declaration at line 74 (govet)
		err := r.Update(ctx, &img)
		^
internal/controller/metal3.io/preprovisioningimage_controller.go:176:7: shadow: declaration of "err" shadows declaration at line 160 (govet)
			if err := r.discardExistingImage(img, log); err != nil {
			   ^
pkg/provisioner/ironic/ironic.go:1257:18: shadow: declaration of "err" shadows declaration at line 1227 (govet)
		if provResult, err := p.setUpForProvisioning(ironicNode, data); err != nil || provResult.Dirty || provResult.ErrorMessage != "" {
		               ^
pkg/provisioner/ironic/ironic.go:1261:16: shadow: declaration of "err" shadows declaration at line 1227 (govet)
		configDrive, err := p.getConfigDrive(data)
		             ^
pkg/provisioner/ironic/ironic.go:1290:18: shadow: declaration of "err" shadows declaration at line 1227 (govet)
		if provResult, err := p.setUpForProvisioning(ironicNode, data); err != nil || provResult.Dirty || provResult.ErrorMessage != "" {
		               ^
pkg/provisioner/ironic/ironic.go:1297:16: shadow: declaration of "err" shadows declaration at line 1227 (govet)
		configDrive, err := p.getConfigDrive(data)
		             ^
pkg/provisioner/ironic/ironic.go:1490:24: shadow: declaration of "err" shadows declaration at line 1465 (govet)
			_, success, result, err := p.tryUpdateNode(ironicNode, updater)
			                    ^
pkg/provisioner/ironic/clients/auth.go:46:8: shadow: declaration of "err" shadows declaration at line 43 (govet)
	if _, err := os.Stat(authPath); err != nil {
	      ^
pkg/provisioner/ironic/testserver/server.go:94:6: shadow: declaration of "response" shadows declaration at line 28 (govet)
		if response, ok := m.responsesByMethod[r.URL.Path][r.Method]; ok {
		   ^
pkg/provisioner/ironic/testserver/server.go:206:2: shadow: declaration of "defaultResponse" shadows declaration at line 33 (govet)
	defaultResponse := defaultResponse{
	^
INFO File cache stats: 21 entries of total size 302.4KiB 
INFO Memory: 440 samples, avg is 1359.4MB, max is 4326.0MB 
INFO Execution took 44.438255091s                 
make: *** [Makefile:142: lint] Error 1
```

/kind ci
/help


Hints from issue comments:
@tuminoid: OK, using Go 1.24 crashes the linter. Downgrading to Go 1.23.9 works. We also need newer golangci-lint when we upgrade Go.@tuminoid: /help@metal3-io-bot: @tuminoid: 
	This request has been marked as needing help from a contributor.

Please ensure the request meets the requirements listed [here](https://git.k8s.io/community/contributors/guide/help-wanted.md).

If this request no longer meets these requirements, the label can be removed
by commenting with the `/remove-help` command.


<details>

In response to [this](https://github.com/metal3-io/baremetal-operator/issues/2460):

>/help


Instructions for interacting with me using PR comments are available [here](https://git.k8s.io/community/contributors/guide/pull-requests.md).  If you have questions or suggestions related to my behavior, please file an issue against the [kubernetes-sigs/prow](https://github.com/kubernetes-sigs/prow/issues/new?title=Prow%20issue:) repository.
</details>@Rozzii: /triage accepted
@sirpaleet: /assign

Solution patch:
diff --git a/.golangci.yaml b/.golangci.yaml
index 53f5df1f..2bca6550 100644
--- a/.golangci.yaml
+++ b/.golangci.yaml
@@ -21,7 +21,7 @@ linters:
   - errchkjson
   #- errname
   #- errorlint
-  #- exhaustive
+  - exhaustive
   - exptostd
   - fatcontext
   - forbidigo
@@ -78,6 +78,8 @@ linters:
   # Run with --fast=false for more extensive checks
   fast: true
 linters-settings:
+  exhaustive:
+    default-signifies-exhaustive: true
   gosec:
     severity: medium
     confidence: medium
@@ -124,6 +126,9 @@ linters-settings:
     - unnecessaryDefer
     - whyNoLint
     - wrapperFunc
+  govet:
+    enable:
+    - shadow
   tagliatelle:
     case:
       rules:
diff --git a/apis/metal3.io/v1alpha1/baremetalhost_types.go b/apis/metal3.io/v1alpha1/baremetalhost_types.go
index 754e0e6c..e7fbb7a1 100644
--- a/apis/metal3.io/v1alpha1/baremetalhost_types.go
+++ b/apis/metal3.io/v1alpha1/baremetalhost_types.go
@@ -1113,6 +1113,7 @@ func (host *BareMetalHost) OperationMetricForState(operation ProvisioningState)
 		metric = &history.Provision
 	case StateDeprovisioning:
 		metric = &history.Deprovision
+	default:
 	}
 	return
 }
diff --git a/hack/tools/deploy-cli/deploy-cli.go b/hack/tools/deploy-cli/deploy-cli.go
index e90da7bd..f24fe3ee 100644
--- a/hack/tools/deploy-cli/deploy-cli.go
+++ b/hack/tools/deploy-cli/deploy-cli.go
@@ -80,7 +80,7 @@ func (d *DeployContext) determineIronicAuth() error {
 	ironicAuthDir := filepath.Join(ironicDataDir, "auth")
 	ironicUsernameFile := filepath.Join(ironicAuthDir, "ironic-username")
 
-	if err := os.MkdirAll(ironicAuthDir, filePerm755); err != nil {
+	if err = os.MkdirAll(ironicAuthDir, filePerm755); err != nil {
 		return err
 	}
 
@@ -119,7 +119,6 @@ func (d *DeployContext) determineIronicAuth() error {
 // deployIronic configures the kustomize overlay for ironic
 // based on the configuration, then install ironic with that overlay.
 func (d *DeployContext) deployIronic() error {
-	var err error
 	ironicDataDir, err := d.GetEnvOrDefault("IRONIC_DATA_DIR")
 	if err != nil {
 		return err
@@ -127,7 +126,7 @@ func (d *DeployContext) deployIronic() error {
 	configMapFileName := "ironic_bmo_configmap.env"
 	configMapInDataDir := filepath.Join(ironicDataDir, configMapFileName)
 
-	if _, err := os.Stat(configMapInDataDir); err == nil && d.IronicBMOConfigMapEnvFile == "" {
+	if _, err = os.Stat(configMapInDataDir); err == nil && d.IronicBMOConfigMapEnvFile == "" {
 		log.Printf("Detected ironic_bmo_configmap.env file in IRONIC_DATA_DIR: %s. Taken into use.", configMapInDataDir)
 		d.IronicBMOConfigMapEnvFile = configMapInDataDir
 	}
@@ -149,14 +148,14 @@ func (d *DeployContext) deployIronic() error {
 
 		kustomizeFile := filepath.Join(ironicOverlay, "kustomization.yaml")
 
-		if err := RenderEmbedTemplateToFile(d.TemplateFiles, ironicKustomizeTpl, kustomizeFile, d); err != nil {
+		if err = RenderEmbedTemplateToFile(d.TemplateFiles, ironicKustomizeTpl, kustomizeFile, d); err != nil {
 			return err
 		}
 
 		ironicBMOConfigMapTpl := "templates/ironic_bmo_configmap_env.tpl"
 		ironicBMOConfigMapOutput := filepath.Join(ironicOverlay, configMapFileName)
 
-		if err := RenderEmbedTemplateToFile(d.TemplateFiles, ironicBMOConfigMapTpl, ironicBMOConfigMapOutput, d); err != nil {
+		if err = RenderEmbedTemplateToFile(d.TemplateFiles, ironicBMOConfigMapTpl, ironicBMOConfigMapOutput, d); err != nil {
 			return err
 		}
 
@@ -168,7 +167,7 @@ func (d *DeployContext) deployIronic() error {
 
 	if d.IronicBMOConfigMapEnvFile != "" {
 		log.Printf("Using custom ironic_bmo_configmap.env file: %s", d.IronicBMOConfigMapEnvFile)
-		if err := CopyFile(d.IronicBMOConfigMapEnvFile, filepath.Join(ironicOverlay, "ironic_bmo_configmap.env")); err != nil {
+		if err = CopyFile(d.IronicBMOConfigMapEnvFile, filepath.Join(ironicOverlay, "ironic_bmo_configmap.env")); err != nil {
 			return err
 		}
 	}
@@ -176,7 +175,8 @@ func (d *DeployContext) deployIronic() error {
 	username, password := d.IronicUsername, d.IronicPassword
 
 	if username != "" && password != "" {
-		ironicHtpasswd, err := GenerateHtpasswd(username, password)
+		var ironicHtpasswd string
+		ironicHtpasswd, err = GenerateHtpasswd(username, password)
 		if err != nil {
 			return err
 		}
@@ -200,7 +200,7 @@ func (d *DeployContext) deployBMO() error {
 	ironicEnvFileName := "ironic.env"
 	ironicEnvInDataDir := filepath.Join(ironicDataDir, ironicEnvFileName)
 
-	if _, err := os.Stat(ironicEnvInDataDir); err == nil && d.IronicEnvFile == "" {
+	if _, err = os.Stat(ironicEnvInDataDir); err == nil && d.IronicEnvFile == "" {
 		log.Printf("Detected ironic.env file in IRONIC_DATA_DIR: %s. Taken into use.", ironicEnvInDataDir)
 		d.IronicEnvFile = ironicEnvInDataDir
 	}
diff --git a/hack/tools/deploy-cli/main.go b/hack/tools/deploy-cli/main.go
index e4fc8210..be6cd307 100644
--- a/hack/tools/deploy-cli/main.go
+++ b/hack/tools/deploy-cli/main.go
@@ -117,7 +117,7 @@ func main() {
 		os.Exit(1)
 	}
 
-	if err := dc.determineIronicAuth(); err != nil {
+	if err = dc.determineIronicAuth(); err != nil {
 		log.Fatalf("Error retrieving Ironic username/password: %v", err)
 	}
 
diff --git a/internal/controller/metal3.io/baremetalhost_controller.go b/internal/controller/metal3.io/baremetalhost_controller.go
index 6984d8cc..c97fe565 100644
--- a/internal/controller/metal3.io/baremetalhost_controller.go
+++ b/internal/controller/metal3.io/baremetalhost_controller.go
@@ -170,7 +170,7 @@ func (r *BareMetalHostReconciler) Reconcile(ctx context.Context, request ctrl.Re
 		)
 		host.Finalizers = append(host.Finalizers,
 			metal3api.BareMetalHostFinalizer)
-		err := r.Update(ctx, host)
+		err = r.Update(ctx, host)
 		if err != nil {
 			return ctrl.Result{}, fmt.Errorf("failed to add finalizer: %w", err)
 		}
@@ -585,6 +585,7 @@ func getCurrentImage(host *metal3api.BareMetalHost) *metal3api.Image {
 		if host.Spec.Image != nil && host.Spec.Image.URL != "" {
 			return host.Spec.Image.DeepCopy()
 		}
+	default:
 	}
 	return nil
 }
@@ -815,6 +816,7 @@ func (r *BareMetalHostReconciler) registerHost(prov provisioner.Provisioner, inf
 		if info.host.Spec.AutomatedCleaningMode == metal3api.CleaningModeDisabled {
 			preprovImgFormats = nil
 		}
+	default:
 	}
 
 	preprovImg, err := r.getPreprovImage(info, preprovImgFormats)
@@ -1015,7 +1017,7 @@ func (r *BareMetalHostReconciler) actionInspecting(prov provisioner.Provisioner,
 		}
 
 		if dirty {
-			if err := r.Update(info.ctx, info.host); err != nil {
+			if err = r.Update(info.ctx, info.host); err != nil {
 				return actionError{fmt.Errorf("failed to update the host after inspection start: %w", err)}
 			}
 			return actionContinue{}
@@ -1067,10 +1069,10 @@ func (r *BareMetalHostReconciler) actionInspecting(prov provisioner.Provisioner,
 		if controllerutil.ContainsFinalizer(hardwareData, hardwareDataFinalizer) {
 			controllerutil.RemoveFinalizer(hardwareData, hardwareDataFinalizer)
 		}
-		if err := r.Update(info.ctx, hardwareData); err != nil {
+		if err = r.Update(info.ctx, hardwareData); err != nil {
 			return actionError{fmt.Errorf("failed to remove hardwareData finalizer: %w", err)}
 		}
-		if err := r.Client.Delete(info.ctx, hd); err != nil {
+		if err = r.Client.Delete(info.ctx, hd); err != nil {
 			return actionError{fmt.Errorf("failed to delete hardwareData: %w", err)}
 		}
 	}
@@ -1480,7 +1482,7 @@ func (r *BareMetalHostReconciler) doServiceIfNeeded(prov provisioner.Provisioner
 		info.host.Status.Provisioning.Firmware = nil
 		if hfcDirty && hfc.Status.Updates != nil {
 			hfc.Status.Updates = nil
-			if err := r.Status().Update(info.ctx, hfc); err != nil {
+			if err = r.Status().Update(info.ctx, hfc); err != nil {
 				return actionError{fmt.Errorf("failed to update hostfirmwarecomponents status: %w", err)}
 			}
 		}
@@ -1576,7 +1578,8 @@ func (r *BareMetalHostReconciler) manageHostPower(prov provisioner.Provisioner,
 
 	servicingAllowed := isProvisioned && !info.host.Status.PoweredOn && desiredPowerOnState
 	if servicingAllowed || info.host.Status.OperationalStatus == metal3api.OperationalStatusServicing || info.host.Status.ErrorType == metal3api.ServicingError {
-		hup, err := r.acquireHostUpdatePolicy(info)
+		var hup *metal3api.HostUpdatePolicy
+		hup, err = r.acquireHostUpdatePolicy(info)
 		if err != nil {
 			info.log.Info("failed setting owner reference on hostupdatepolicy")
 			return actionError{fmt.Errorf("failed setting owner reference on hostUpdatePolicy: %w", err)}
@@ -1808,8 +1811,8 @@ func (r *BareMetalHostReconciler) attachDataImage(prov provisioner.Provisioner,
 		dataImage.Status.Error.Count++
 		dataImage.Status.Error.Message = err.Error()
 		// Error updating DataImage Status
-		if err := r.Status().Update(info.ctx, dataImage); err != nil {
-			return fmt.Errorf("failed to update DataImage status, %w", err)
+		if errOnUpdate := r.Status().Update(info.ctx, dataImage); errOnUpdate != nil {
+			return fmt.Errorf("failed to update DataImage status, %w", errOnUpdate)
 		}
 
 		return fmt.Errorf("failed to attach dataImage, %w", err)
@@ -1838,8 +1841,8 @@ func (r *BareMetalHostReconciler) detachDataImage(prov provisioner.Provisioner,
 		dataImage.Status.Error.Count++
 		dataImage.Status.Error.Message = err.Error()
 		// Error updating DataImage Status
-		if err := r.Status().Update(info.ctx, dataImage); err != nil {
-			return fmt.Errorf("failed to update DataImage status, %w", err)
+		if errOnUpdate := r.Status().Update(info.ctx, dataImage); errOnUpdate != nil {
+			return fmt.Errorf("failed to update DataImage status, %w", errOnUpdate)
 		}
 
 		return fmt.Errorf("failed to detach dataImage, %w", err)
diff --git a/internal/controller/metal3.io/dataimage_controller.go b/internal/controller/metal3.io/dataimage_controller.go
index f505405f..01504d26 100644
--- a/internal/controller/metal3.io/dataimage_controller.go
+++ b/internal/controller/metal3.io/dataimage_controller.go
@@ -119,7 +119,7 @@ func (r *DataImageReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
 			di.Finalizers = utils.FilterStringFromList(
 				di.Finalizers, metal3api.DataImageFinalizer)
 
-			if err := r.Update(ctx, di); err != nil {
+			if err = r.Update(ctx, di); err != nil {
 				return ctrl.Result{Requeue: true, RequeueAfter: dataImageRetryDelay}, fmt.Errorf("failed to update resource after remove finalizer, %w", err)
 			}
 			return ctrl.Result{}, nil
diff --git a/internal/controller/metal3.io/host_state_machine.go b/internal/controller/metal3.io/host_state_machine.go
index 7267c0c7..f321da90 100644
--- a/internal/controller/metal3.io/host_state_machine.go
+++ b/internal/controller/metal3.io/host_state_machine.go
@@ -110,6 +110,7 @@ func (hsm *hostStateMachine) updateHostStateFrom(initialState metal3api.Provisio
 			if actionRes := hsm.ensureCapacity(info, hsm.NextState); actionRes != nil {
 				return actionRes
 			}
+		default:
 		}
 
 		info.log.Info("changing provisioning state",
@@ -140,6 +141,7 @@ func (hsm *hostStateMachine) updateHostStateFrom(initialState metal3api.Provisio
 				info.log.Info("saving boot mode",
 					"new mode", hsm.Host.Status.Provisioning.BootMode)
 			}
+		default:
 		}
 	}
 
@@ -166,6 +168,7 @@ func (hsm *hostStateMachine) checkDelayedHost(info *reconcileInfo) actionResult
 		if actionRes := hsm.ensureCapacity(info, info.host.Status.Provisioning.State); actionRes != nil {
 			return actionRes
 		}
+	default:
 	}
 
 	return nil
@@ -302,6 +305,7 @@ func (hsm *hostStateMachine) checkDetachedHost(info *reconcileInfo) (result acti
 		switch info.host.Status.Provisioning.State {
 		case metal3api.StateProvisioned, metal3api.StateExternallyProvisioned, metal3api.StateReady, metal3api.StateAvailable:
 			return hsm.Reconciler.detachHost(hsm.Provisioner, info)
+		default:
 		}
 	}
 	if info.host.Status.ErrorType == metal3api.DetachError {
diff --git a/internal/controller/metal3.io/preprovisioningimage_controller.go b/internal/controller/metal3.io/preprovisioningimage_controller.go
index 92dc4150..c9a4e951 100644
--- a/internal/controller/metal3.io/preprovisioningimage_controller.go
+++ b/internal/controller/metal3.io/preprovisioningimage_controller.go
@@ -83,12 +83,12 @@ func (r *PreprovisioningImageReconciler) Reconcile(ctx context.Context, req ctrl
 
 	if !img.DeletionTimestamp.IsZero() {
 		log.Info("cleaning up deleted resource")
-		if err := r.discardExistingImage(&img, log); err != nil {
+		if err = r.discardExistingImage(&img, log); err != nil {
 			return ctrl.Result{}, err
 		}
 		img.Finalizers = utils.FilterStringFromList(
 			img.Finalizers, metal3api.PreprovisioningImageFinalizer)
-		err := r.Update(ctx, &img)
+		err = r.Update(ctx, &img)
 		if err != nil {
 			return ctrl.Result{}, fmt.Errorf("failed to remove finalizer: %w", err)
 		}
@@ -98,7 +98,7 @@ func (r *PreprovisioningImageReconciler) Reconcile(ctx context.Context, req ctrl
 	if !utils.StringInList(img.Finalizers, metal3api.PreprovisioningImageFinalizer) {
 		log.Info("adding finalizer")
 		img.Finalizers = append(img.Finalizers, metal3api.PreprovisioningImageFinalizer)
-		err := r.Update(ctx, &img)
+		err = r.Update(ctx, &img)
 		if err != nil {
 			return ctrl.Result{}, fmt.Errorf("failed to add finalizer: %w", err)
 		}
@@ -174,7 +174,7 @@ func (r *PreprovisioningImageReconciler) update(ctx context.Context, img *metal3
 			// from the image cache.
 			setUnready(generation, &img.Status, reason)
 		} else {
-			if err := r.discardExistingImage(img, log); err != nil {
+			if err = r.discardExistingImage(img, log); err != nil {
 				return false, err
 			}
 			// Set up all the data before building the image and adding the URL,
diff --git a/main.go b/main.go
index 8477a9a6..b8e519c0 100644
--- a/main.go
+++ b/main.go
@@ -231,7 +231,8 @@ func main() {
 	}
 
 	if leaseDurationSeconds != "" {
-		seconds, err := strconv.ParseInt(leaseDurationSeconds, 10, 16)
+		var seconds int64
+		seconds, err = strconv.ParseInt(leaseDurationSeconds, 10, 16)
 		if err != nil {
 			setupLog.Error(err, "failed to parse duration")
 			os.Exit(1)
@@ -242,7 +243,8 @@ func main() {
 	}
 
 	if renewDeadlineSeconds != "" {
-		seconds, err := strconv.ParseInt(renewDeadlineSeconds, 10, 16)
+		var seconds int64
+		seconds, err = strconv.ParseInt(renewDeadlineSeconds, 10, 16)
 		if err != nil {
 			setupLog.Error(err, "failed to parse renew deadline")
 			os.Exit(1)
@@ -253,7 +255,8 @@ func main() {
 	}
 
 	if retryPeriodSeconds != "" {
-		seconds, err := strconv.ParseInt(retryPeriodSeconds, 10, 16)
+		var seconds int64
+		seconds, err = strconv.ParseInt(retryPeriodSeconds, 10, 16)
 		if err != nil {
 			setupLog.Error(err, "failed to parse retry period")
 			os.Exit(1)
diff --git a/pkg/provisioner/ironic/clients/auth.go b/pkg/provisioner/ironic/clients/auth.go
index 84f0469a..2b3c5e6f 100644
--- a/pkg/provisioner/ironic/clients/auth.go
+++ b/pkg/provisioner/ironic/clients/auth.go
@@ -43,7 +43,7 @@ func readAuthFile(filename string) (string, error) {
 func LoadAuth() (auth AuthConfig, err error) {
 	authPath := path.Join(authRoot(), "ironic")
 
-	if _, err := os.Stat(authPath); err != nil {
+	if _, err = os.Stat(authPath); err != nil {
 		if os.IsNotExist(err) {
 			auth.Type = NoAuth
 			return auth, nil
diff --git a/pkg/provisioner/ironic/ironic.go b/pkg/provisioner/ironic/ironic.go
index cc2f8f9b..4bc753f2 100644
--- a/pkg/provisioner/ironic/ironic.go
+++ b/pkg/provisioner/ironic/ironic.go
@@ -339,21 +339,17 @@ func (p *ironicProvisioner) configureImages(data provisioner.ManagementAccessDat
 		return result, err
 	}
 
+	if data.State == metal3api.StateProvisioning && data.CurrentImage.IsLiveISO() {
+		// Live ISO doesn't need pre-provisioning image
+		return result, nil
+	}
+
+	if data.State == metal3api.StateDeprovisioning && data.AutomatedCleaningMode == metal3api.CleaningModeDisabled {
+		// No need for pre-provisioning image if cleaning disabled
+		return result, nil
+	}
+
 	switch data.State {
-	case metal3api.StateProvisioning,
-		metal3api.StateDeprovisioning:
-		if data.State == metal3api.StateProvisioning {
-			if data.CurrentImage.IsLiveISO() {
-				// Live ISO doesn't need pre-provisioning image
-				return result, nil
-			}
-		} else {
-			if data.AutomatedCleaningMode == metal3api.CleaningModeDisabled {
-				// No need for pre-provisioning image if cleaning disabled
-				return result, nil
-			}
-		}
-		fallthrough
 	case metal3api.StateInspecting,
 		metal3api.StatePreparing:
 		if deployImageInfo == nil {
@@ -364,6 +360,7 @@ func (p *ironicProvisioner) configureImages(data provisioner.ManagementAccessDat
 			}
 			return result, err
 		}
+	default:
 	}
 
 	return result, nil
@@ -1245,6 +1242,8 @@ func (p *ironicProvisioner) Provision(data provisioner.ProvisionData, forceReboo
 		// with the image and checksum we have been trying to use, so we
 		// should stop. (If the image values do not match, we want to try
 		// again.)
+		var provResult provisioner.Result
+		var configDrive nodes.ConfigDrive
 		if ironicHasSameImage {
 			// Save me from "eventually consistent" systems built on
 			// top of relational databases...
@@ -1257,11 +1256,11 @@ func (p *ironicProvisioner) Provision(data provisioner.ProvisionData, forceReboo
 				ironicNode.LastError))
 		}
 		p.log.Info("recovering from previous failure")
-		if provResult, err := p.setUpForProvisioning(ironicNode, data); err != nil || provResult.Dirty || provResult.ErrorMessage != "" {
+		if provResult, err = p.setUpForProvisioning(ironicNode, data); err != nil || provResult.Dirty || provResult.ErrorMessage != "" {
 			return provResult, err
 		}
 
-		configDrive, err := p.getConfigDrive(data)
+		configDrive, err = p.getConfigDrive(data)
 		if err != nil {
 			return transientError(err)
 		}
@@ -1290,14 +1289,17 @@ func (p *ironicProvisioner) Provision(data provisioner.ProvisionData, forceReboo
 		)
 
 	case nodes.Available:
-		if provResult, err := p.setUpForProvisioning(ironicNode, data); err != nil || provResult.Dirty || provResult.ErrorMessage != "" {
+		var provResult provisioner.Result
+		var configDrive nodes.ConfigDrive
+
+		if provResult, err = p.setUpForProvisioning(ironicNode, data); err != nil || provResult.Dirty || provResult.ErrorMessage != "" {
 			return provResult, err
 		}
 
 		// After it is available, we need to start provisioning by
 		// setting the state to "active".
 
-		configDrive, err := p.getConfigDrive(data)
+		configDrive, err = p.getConfigDrive(data)
 		if err != nil {
 			return transientError(err)
 		}
@@ -1487,10 +1489,11 @@ func (p *ironicProvisioner) Delete() (result provisioner.Result, err error) {
 	if currentProvState == nodes.Available || currentProvState == nodes.Manageable {
 		// Make sure we don't have a stale instance UUID
 		if ironicNode.InstanceUUID != "" {
+			var success bool
 			p.log.Info("removing stale instance UUID before deletion", "instanceUUID", ironicNode.InstanceUUID)
 			updater := clients.UpdateOptsBuilder(p.log)
 			updater.SetTopLevelOpt("instance_uuid", nil, ironicNode.InstanceUUID)
-			_, success, result, err := p.tryUpdateNode(ironicNode, updater)
+			_, success, result, err = p.tryUpdateNode(ironicNode, updater)
 			if !success {
 				return result, err
 			}
@@ -1728,6 +1731,7 @@ func (p *ironicProvisioner) loadBusyHosts() (hosts map[string]struct{}, err erro
 			if !strings.Contains(node.BootInterface, "virtual-media") {
 				hosts[node.Name] = struct{}{}
 			}
+		default:
 		}
 	}
 



Test patch:
diff --git a/pkg/provisioner/ironic/testserver/server.go b/pkg/provisioner/ironic/testserver/server.go
index 01f23091..c6502af4 100644
--- a/pkg/provisioner/ironic/testserver/server.go
+++ b/pkg/provisioner/ironic/testserver/server.go
@@ -91,8 +91,8 @@ func (m *MockServer) Handler(pattern string, handlerFunc http.HandlerFunc) *Mock
 
 func (m *MockServer) buildHandler(_ string) func(http.ResponseWriter, *http.Request) {
 	handler := func(w http.ResponseWriter, r *http.Request) {
-		if response, ok := m.responsesByMethod[r.URL.Path][r.Method]; ok {
-			m.sendData(w, r, response.code, response.payload)
+		if resp, ok := m.responsesByMethod[r.URL.Path][r.Method]; ok {
+			m.sendData(w, r, resp.code, resp.payload)
 			return
 		}
 
@@ -203,7 +203,7 @@ func (m *MockServer) AddDefaultResponse(patternWithVars string, httpMethod strin
 	pattern := "^" + regexp.MustCompile("{(.[^}]*)}").ReplaceAllString(patternWithVars, "(?P<$1>.[^/]*)") + "$"
 	m.t.Logf("%s: adding default response for %s (%s) -> {%d, %s}", m.name, patternWithVars, pattern, code, payload)
 
-	defaultResponse := defaultResponse{
+	defaultResp := defaultResponse{
 		re:     regexp.MustCompile(pattern),
 		method: httpMethod,
 		response: response{
@@ -212,7 +212,7 @@ func (m *MockServer) AddDefaultResponse(patternWithVars string, httpMethod strin
 		},
 	}
 
-	m.defaultResponses = append(m.defaultResponses, defaultResponse)
+	m.defaultResponses = append(m.defaultResponses, defaultResp)
 	return m
 }
 
diff --git a/test/e2e/e2e_suite_test.go b/test/e2e/e2e_suite_test.go
index fe787ec0..f189d619 100644
--- a/test/e2e/e2e_suite_test.go
+++ b/test/e2e/e2e_suite_test.go
@@ -108,6 +108,7 @@ func serviceAccountToken() (string, error) {
 
 	var out string
 	verifyTokenCreation := func(g Gomega) {
+		var output []byte
 		// Execute kubectl command to create the token
 		cmd := exec.Command("kubectl", "create", "--raw", fmt.Sprintf(
 			"/api/v1/namespaces/%s/serviceaccounts/%s/token",
@@ -115,7 +116,7 @@ func serviceAccountToken() (string, error) {
 			serviceAccountName,
 		), "-f", tokenRequestFile)
 
-		output, err := cmd.CombinedOutput()
+		output, err = cmd.CombinedOutput()
 		g.Expect(err).NotTo(HaveOccurred())
 
 		// Parse the JSON output to extract the token
@@ -165,7 +166,7 @@ var _ = SynchronizedBeforeSuite(func() []byte {
 
 	scheme := runtime.NewScheme()
 	framework.TryAddDefaultSchemes(scheme)
-	clusterProxy := framework.NewClusterProxy("bmo-e2e", kubeconfigPath, scheme)
+	clusterProxy = framework.NewClusterProxy("bmo-e2e", kubeconfigPath, scheme)
 	Expect(clusterProxy).ToNot(BeNil(), "Failed to get a cluster proxy")
 
 	DeferCleanup(func() {
@@ -240,8 +241,9 @@ var _ = SynchronizedBeforeSuite(func() []byte {
 
 		By("validating that the metrics service is available")
 		Eventually(func() error {
-			cmd := exec.Command("kubectl", "get", "service", metricsServiceName, "-n", namespace)
-			output, err := cmd.CombinedOutput()
+			var output []byte
+			cmd = exec.Command("kubectl", "get", "service", metricsServiceName, "-n", namespace)
+			output, err = cmd.CombinedOutput()
 			if err != nil {
 				log.Printf("Service check output: %s\n", string(output))
 				return err
@@ -256,8 +258,9 @@ var _ = SynchronizedBeforeSuite(func() []byte {
 
 		By("waiting for the metrics endpoint to be ready")
 		verifyMetricsEndpointReady := func(g Gomega) {
-			cmd := exec.Command("kubectl", "get", "endpoints", metricsServiceName, "-n", namespace)
-			output, err := cmd.CombinedOutput()
+			var output []byte
+			cmd = exec.Command("kubectl", "get", "endpoints", metricsServiceName, "-n", namespace)
+			output, err = cmd.CombinedOutput()
 			g.Expect(err).NotTo(HaveOccurred())
 			g.Expect(output).To(ContainSubstring("8443"), "Metrics endpoint is not ready")
 		}
@@ -275,10 +278,11 @@ var _ = SynchronizedBeforeSuite(func() []byte {
 
 		By("waiting for the curl-metrics pod to complete.")
 		verifyCurlUp := func(g Gomega) {
-			cmd := exec.Command("kubectl", "get", "pods", "curl-metrics",
+			var output []byte
+			cmd = exec.Command("kubectl", "get", "pods", "curl-metrics",
 				"-o", "jsonpath={.status.phase}",
 				"-n", namespace)
-			output, err := cmd.CombinedOutput()
+			output, err = cmd.CombinedOutput()
 			g.Expect(err).NotTo(HaveOccurred())
 			g.Expect(string(output)).To(Equal("Succeeded"), "curl pod in wrong status")
 		}
diff --git a/test/e2e/provisioning_and_annotation_test.go b/test/e2e/provisioning_and_annotation_test.go
index f5ec523a..83bdf1dd 100644
--- a/test/e2e/provisioning_and_annotation_test.go
+++ b/test/e2e/provisioning_and_annotation_test.go
@@ -167,7 +167,7 @@ var _ = Describe("Provision, detach, recreate from status and deprovision", Labe
 
 			By("Waiting for the secret to be deleted")
 			Eventually(func() bool {
-				err := clusterProxy.GetClient().Get(ctx, types.NamespacedName{
+				err = clusterProxy.GetClient().Get(ctx, types.NamespacedName{
 					Name:      "bmc-credentials",
 					Namespace: namespace.Name,
 				}, &corev1.Secret{})