Repository: tektoncd/operator
Pull request #1207 (2022-12-08 18:06:28)

fix: setup pruner job with proper SecurityContext
# Changes

If using pruner with the restricted Pod Security, then along with ``RunAsNonRoot`` attribute, SecurityContext also needs ``RunAsUser`` and ``FSGroup`` attributes to be set, otherwise an error message along with
ContainerCreationError will appear.

# Submitter Checklist

These are the criteria that every PR should meet, please check them off as you
review them:

- [x] Run `make test lint` before submitting a PR
- [ ] Includes [tests](https://github.com/tektoncd/community/blob/master/standards.md#principles) (if functionality changed/added)
- [ ] Includes [docs](https://github.com/tektoncd/community/blob/master/standards.md#principles) (if user facing)
- [x] Commit messages follow [commit message best practices](https://github.com/tektoncd/community/blob/master/standards.md#commit-messages)

_See [the contribution guide](https://github.com/tektoncd/operator/blob/master/CONTRIBUTING.md) for more details._

# Release Notes

<!--
Describe any user facing changes here, or delete this block.

Examples of user facing changes:
- API changes
- Bug fixes
- Any changes in behavior
- Changes requiring upgrade notices or deprecation warnings

For pull requests with a release note:

```release-note
Your release note here
```

For pull requests that require additional action from users switching to the new release, include the string "action required" (case insensitive) in the release note:

```release-note
action required: your release note here
```

For pull requests that don't need to be mentioned at release time, use the `/release-note-none` Prow command to add the `release-note-none` label to the PR. You can also write the string "NONE" as a release note in your PR description:

```release-note
NONE
```
-->


linux-foundation-easycla[bot]:  <a href="https://api.easycla.lfx.linuxfoundation.org/v2/repository-provider/github/sign/8049964/196359824/1207/#/?version=2"><img src="https://s3.amazonaws.com/cla-project-logo-prod/cla-not-signed.svg" alt="CLA Not Signed" align="left" height="28" width="328"></a><br/><br /><ul><li><a href='https://api.easycla.lfx.linuxfoundation.org/v2/repository-provider/github/sign/8049964/196359824/1207/#/?version=2' target='_blank'>:x:</a> - login: @aellwein / name: Alex Ellwein . The commit (233ce2104f0f8985868e9b9cd634f62395fa5fdf) is not authorized under a signed CLA. <a href='https://api.easycla.lfx.linuxfoundation.org/v2/repository-provider/github/sign/8049964/196359824/1207/#/?version=2' target='_blank'>Please click here to be authorized</a>. For further assistance with EasyCLA, <a href='https://jira.linuxfoundation.org/servicedesk/customer/portal/4' target='_blank'>please submit a support request ticket</a>.</li></ul>
tekton-robot: Hi @aellwein. Thanks for your PR.

I'm waiting for a [tektoncd](https://github.com/orgs/tektoncd/people) member to verify that this patch is reasonable to test. If it is, they should reply with `/ok-to-test` on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work. Regular contributors should [join the org](https://github.com/orgs/tektoncd/people) to skip this step.

Once the patch is verified, the new status will be reflected by the `ok-to-test` label.

I understand the commands that are listed [here](https://go.k8s.io/bot-commands?repo=tektoncd%2Foperator).

<details>

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/test-infra](https://github.com/kubernetes/test-infra/issues/new?title=Prow%20issue:) repository.
</details>

tekton-robot: [APPROVALNOTIFIER] This PR is **NOT APPROVED**

This pull-request has been approved by:
To complete the [pull request process](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process), please assign **piyush-garg** after the PR has been reviewed.
You can assign the PR to them by writing `/assign @piyush-garg` in a comment when ready.

The full list of commands accepted by this bot can be found [here](https://prow.tekton.dev/command-help?repo=tektoncd%2Foperator).

<details open>
Needs approval from an approver in each of these files:

- **[OWNERS](https://github.com/tektoncd/operator/blob/main/OWNERS)**

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":["piyush-garg"]} -->
aellwein: Successfully tested on k3s 1.25.4 with pod security enabled by default.
tekton-robot: The following is the coverage report on the affected files.
Say `/test pull-tekton-operator-go-coverage` to re-run this coverage report

File | Old Coverage | New Coverage | Delta
---- |:------------:|:------------:|:-----:
[pkg/reconciler/common/prune.go](https://storage.cloud.google.com/tekton-prow/pr-logs/pull/tektoncd_operator/1207/pull-tekton-operator-go-coverage/1601209607206735872/artifacts/line-cov.html#file0) | 80.6% | 80.8% | 0.2

piyush-garg: Should we keep `65532` which we generally do in all tekton components?
aellwein: > Should we keep `65532` which we generally do in all tekton components?

@piyush-garg sure thing, will adapt accordingly
tekton-robot: The following is the coverage report on the affected files.
Say `/test pull-tekton-operator-go-coverage` to re-run this coverage report

File | Old Coverage | New Coverage | Delta
---- |:------------:|:------------:|:-----:
[pkg/reconciler/common/prune.go](https://storage.cloud.google.com/tekton-prow/pr-logs/pull/tektoncd_operator/1207/pull-tekton-operator-go-coverage/1602358185375567872/artifacts/line-cov.html#file0) | 80.6% | 80.8% | 0.2

tekton-robot: [APPROVALNOTIFIER] This PR is **APPROVED**

Approval requirements bypassed by manually added approval.

This pull-request has been approved by:

The full list of commands accepted by this bot can be found [here](https://prow.tekton.dev/command-help?repo=tektoncd%2Foperator).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- **[OWNERS](https://github.com/tektoncd/operator/blob/main/OWNERS)**

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":["piyush-garg"]} -->

Patch:
diff --git a/pkg/reconciler/common/prune.go b/pkg/reconciler/common/prune.go
index 25f52e1e1..a1d6ce39d 100644
--- a/pkg/reconciler/common/prune.go
+++ b/pkg/reconciler/common/prune.go
@@ -333,6 +333,9 @@ func createCronJob(ctx context.Context, kc kubernetes.Interface, cronName, targe
 	backOffLimit := int32(3)
 	ttlSecondsAfterFinished := int32(3600)
 	runAsNonRoot := true
+	runAsUser := int64(65532)
+	fsGroup := int64(65532)
+
 	cj := &batchv1.CronJob{
 		TypeMeta: v1.TypeMeta{
 			Kind:       "CronJob",
@@ -365,6 +368,8 @@ func createCronJob(ctx context.Context, kc kubernetes.Interface, cronName, targe
 								SeccompProfile: &corev1.SeccompProfile{
 									Type: corev1.SeccompProfileTypeRuntimeDefault,
 								},
+								RunAsUser: &runAsUser,
+								FSGroup:   &fsGroup,
 							},
 						},
 					},
diff --git a/pkg/reconciler/kubernetes/tektoninstallerset/client/update.go b/pkg/reconciler/kubernetes/tektoninstallerset/client/update.go
index 69fc0f684..81e2b3c46 100644
--- a/pkg/reconciler/kubernetes/tektoninstallerset/client/update.go
+++ b/pkg/reconciler/kubernetes/tektoninstallerset/client/update.go
@@ -32,32 +32,22 @@ import (
 func (i *InstallerSetClient) update(ctx context.Context, comp v1alpha1.TektonComponent, toBeUpdatedIS []v1alpha1.TektonInstallerSet, manifest *mf.Manifest, filterAndTransform FilterAndTransform, isType string) ([]v1alpha1.TektonInstallerSet, error) {
 	logger := logging.FromContext(ctx).With("kind", i.resourceKind, "type", isType)
 
-	switch isType {
-	case InstallerTypeMain:
+	if isType == InstallerTypeMain {
 		sets, err := i.updateMainSets(ctx, comp, toBeUpdatedIS, manifest, filterAndTransform)
 		if err != nil {
 			logger.Errorf("installer set update failed for main type: %v", err)
 			return sets, err
 		}
 		return sets, nil
-
-	case InstallerTypePre, InstallerTypePost:
-		logger.Infof("updating installer set: %v", toBeUpdatedIS[0].GetName())
-		updatedSet, err := i.updateSet(ctx, comp, toBeUpdatedIS[0], manifest, filterAndTransform)
-		if err != nil {
-			return nil, fmt.Errorf("failed to update installerset : %v", err)
-		}
-		logger.Infof("updated installer set: %v", toBeUpdatedIS[0].GetName())
-		return []v1alpha1.TektonInstallerSet{*updatedSet}, nil
-
-	case InstallerTypeCustom:
-	// TODO
-
-	default:
-		return nil, fmt.Errorf("invalid installer set type")
 	}
 
-	return nil, nil
+	logger.Infof("updating installer set: %v", toBeUpdatedIS[0].GetName())
+	updatedSet, err := i.updateSet(ctx, comp, toBeUpdatedIS[0], manifest, filterAndTransform)
+	if err != nil {
+		return nil, fmt.Errorf("failed to update installerset : %v", err)
+	}
+	logger.Infof("updated installer set: %v", toBeUpdatedIS[0].GetName())
+	return []v1alpha1.TektonInstallerSet{*updatedSet}, nil
 }
 
 func (i *InstallerSetClient) updateMainSets(ctx context.Context, comp v1alpha1.TektonComponent, toBeUpdatedIS []v1alpha1.TektonInstallerSet, manifest *mf.Manifest, filterAndTransform FilterAndTransform) ([]v1alpha1.TektonInstallerSet, error) {


Test patch:
diff --git a/pkg/apis/operator/v1alpha1/tektonconfig_default_test.go b/pkg/apis/operator/v1alpha1/tektonconfig_default_test.go
index 315bc56bd..a4eec9655 100644
--- a/pkg/apis/operator/v1alpha1/tektonconfig_default_test.go
+++ b/pkg/apis/operator/v1alpha1/tektonconfig_default_test.go
@@ -18,7 +18,6 @@ package v1alpha1
 
 import (
 	"context"
-	"os"
 	"testing"
 
 	"gotest.tools/v3/assert"
@@ -86,8 +85,7 @@ func Test_SetDefaults_Addon_Params(t *testing.T) {
 			},
 		},
 	}
-	assert.NilError(t, os.Setenv("PLATFORM", "openshift"))
-	defer os.Clearenv()
+	t.Setenv("PLATFORM", "openshift")
 
 	tc.SetDefaults(context.TODO())
 	if len(tc.Spec.Addon.Params) != 3 {
@@ -122,8 +120,7 @@ func Test_SetDefaults_Triggers_Properties(t *testing.T) {
 }
 
 func Test_SetDefaults_PipelineAsCode(t *testing.T) {
-	assert.NilError(t, os.Setenv("PLATFORM", "openshift"))
-	defer os.Clearenv()
+	t.Setenv("PLATFORM", "openshift")
 
 	// PAC disabled through addon
 	tc := &TektonConfig{
diff --git a/pkg/apis/operator/v1alpha1/tektonhub_default_test.go b/pkg/apis/operator/v1alpha1/tektonhub_default_test.go
index 3b12fdbfc..021348fe3 100644
--- a/pkg/apis/operator/v1alpha1/tektonhub_default_test.go
+++ b/pkg/apis/operator/v1alpha1/tektonhub_default_test.go
@@ -18,7 +18,6 @@ package v1alpha1
 
 import (
 	"context"
-	"os"
 	"testing"
 
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -26,8 +25,7 @@ import (
 
 func TestSetDefault(t *testing.T) {
 
-	os.Setenv("DEFAULT_TARGET_NAMESPACE", "tekton-pipelines")
-	defer os.Unsetenv("DEFAULT_TARGET_NAMESPACE")
+	t.Setenv("DEFAULT_TARGET_NAMESPACE", "tekton-pipelines")
 	th := &TektonHub{
 		ObjectMeta: metav1.ObjectMeta{
 			Name: "hub",
diff --git a/pkg/reconciler/common/prune_test.go b/pkg/reconciler/common/prune_test.go
index f54b50c14..3c6227920 100644
--- a/pkg/reconciler/common/prune_test.go
+++ b/pkg/reconciler/common/prune_test.go
@@ -19,7 +19,6 @@ package common
 import (
 	"context"
 	"errors"
-	"os"
 	"strings"
 	"testing"
 
@@ -109,8 +108,7 @@ func TestCompleteFlowPrune(t *testing.T) {
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns-three", Annotations: anno1}},
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns-four", Annotations: anno4}},
 	)
-	os.Setenv(JobsTKNImageName, "some")
-	defer os.Unsetenv(JobsTKNImageName)
+	t.Setenv(JobsTKNImageName, "some")
 
 	err := Prune(context.TODO(), client, config)
 	if err != nil {
@@ -211,8 +209,7 @@ func TestAnnotationCmd(t *testing.T) {
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns-ten", Annotations: annoResourceTrPr}},
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns-thirteen", Annotations: annoStrategyKeep}},
 	)
-	os.Setenv(JobsTKNImageName, "some")
-	defer os.Unsetenv(JobsTKNImageName)
+	t.Setenv(JobsTKNImageName, "some")
 
 	err := Prune(context.TODO(), client, config)
 	if err != nil {
@@ -284,8 +281,7 @@ func TestConfigChange(t *testing.T) {
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "kube-api"}},
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns-one", Annotations: anno1}},
 	)
-	os.Setenv(JobsTKNImageName, "some")
-	defer os.Unsetenv(JobsTKNImageName)
+	t.Setenv(JobsTKNImageName, "some")
 
 	err := Prune(context.TODO(), client, config)
 	if err != nil {
@@ -389,8 +385,7 @@ func TestNodeSelectorOrTolerationsChange(t *testing.T) {
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns-two", Annotations: annoUniqueSchedule}},
 		&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns-three", Annotations: annoUniqueSchedule2}},
 	)
-	os.Setenv(JobsTKNImageName, "some")
-	defer os.Unsetenv(JobsTKNImageName)
+	t.Setenv(JobsTKNImageName, "some")
 
 	// Pruning with the nodes and Tolerations
 	err := Prune(context.TODO(), client, config1)
diff --git a/pkg/reconciler/common/releases_test.go b/pkg/reconciler/common/releases_test.go
index f3d2bfd34..9889d59b4 100644
--- a/pkg/reconciler/common/releases_test.go
+++ b/pkg/reconciler/common/releases_test.go
@@ -17,7 +17,6 @@ limitations under the License.
 package common
 
 import (
-	"os"
 	"testing"
 
 	mf "github.com/manifestival/manifestival"
@@ -31,8 +30,7 @@ const (
 
 func TestGetLatestRelease(t *testing.T) {
 	koPath := "testdata/kodata"
-	os.Setenv(KoEnvKey, koPath)
-	defer os.Unsetenv(KoEnvKey)
+	t.Setenv(KoEnvKey, koPath)
 
 	version := latestRelease(&v1alpha1.TektonTrigger{})
 	util.AssertEqual(t, version, VERSION)
@@ -40,8 +38,7 @@ func TestGetLatestRelease(t *testing.T) {
 
 func TestListReleases(t *testing.T) {
 	koPath := "testdata/kodata"
-	os.Setenv(KoEnvKey, koPath)
-	defer os.Unsetenv(KoEnvKey)
+	t.Setenv(KoEnvKey, koPath)
 	expectedVersionList := []string{"0.15.2", "0.14.3", "0.13.2"}
 
 	version, err := allReleases(&v1alpha1.TektonTrigger{})
diff --git a/pkg/reconciler/common/stages_test.go b/pkg/reconciler/common/stages_test.go
index 6e98bc241..38df48fde 100644
--- a/pkg/reconciler/common/stages_test.go
+++ b/pkg/reconciler/common/stages_test.go
@@ -18,7 +18,6 @@ package common
 
 import (
 	"context"
-	"os"
 	"testing"
 
 	mf "github.com/manifestival/manifestival"
@@ -30,8 +29,7 @@ import (
 )
 
 func TestDeleteObsoleteResources(t *testing.T) {
-	os.Setenv(KoEnvKey, "testdata/kodata")
-	defer os.Unsetenv(KoEnvKey)
+	t.Setenv(KoEnvKey, "testdata/kodata")
 	client := fake.New()
 	manifest, err := mf.NewManifest("testdata/test_delete_obsolete_resources/dummy.release.notags.yaml", mf.UseClient(client))
 	if err != nil {
diff --git a/pkg/reconciler/common/transformers_test.go b/pkg/reconciler/common/transformers_test.go
index 6c5835fa9..6562c9972 100644
--- a/pkg/reconciler/common/transformers_test.go
+++ b/pkg/reconciler/common/transformers_test.go
@@ -18,7 +18,6 @@ package common
 
 import (
 	"context"
-	"os"
 	"path"
 	"testing"
 
@@ -97,7 +96,7 @@ func TestCommonTransformers(t *testing.T) {
 }
 
 func TestImagesFromEnv(t *testing.T) {
-	os.Setenv("IMAGE_PIPELINES_CONTROLLER", "docker.io/pipeline")
+	t.Setenv("IMAGE_PIPELINES_CONTROLLER", "docker.io/pipeline")
 	data := ImagesFromEnv(PipelinesImagePrefix)
 	if !cmp.Equal(data, map[string]string{"CONTROLLER": "docker.io/pipeline"}) {
 		t.Fatalf("Unexpected ImageFromEnv: %s", cmp.Diff(data, map[string]string{"CONTROLLER": "docker.io/pipeline"}))
diff --git a/pkg/reconciler/kubernetes/tektonconfig/extension/dashboard_test.go b/pkg/reconciler/kubernetes/tektonconfig/extension/dashboard_test.go
index af4a4fed8..b122ff0cd 100644
--- a/pkg/reconciler/kubernetes/tektonconfig/extension/dashboard_test.go
+++ b/pkg/reconciler/kubernetes/tektonconfig/extension/dashboard_test.go
@@ -18,7 +18,6 @@ package extension
 
 import (
 	"context"
-	"os"
 	"testing"
 
 	op "github.com/tektoncd/operator/pkg/client/clientset/versioned/typed/operator/v1alpha1"
@@ -109,14 +108,16 @@ func makeUpgradeCheckPass(t *testing.T, ctx context.Context, c op.TektonDashboar
 	// set necessary version labels to make upgrade check pass
 	dashboard, err := c.Get(ctx, v1alpha1.DashboardResourceName, metav1.GetOptions{})
 	util.AssertEqual(t, err, nil)
-	setDummyVersionLabel(dashboard)
+	setDummyVersionLabel(t, dashboard)
 	_, err = c.Update(ctx, dashboard, metav1.UpdateOptions{})
 	util.AssertEqual(t, err, nil)
 }
 
-func setDummyVersionLabel(td *v1alpha1.TektonDashboard) {
+func setDummyVersionLabel(t *testing.T, td *v1alpha1.TektonDashboard) {
+	t.Helper()
+
 	oprVersion := "v1.2.3"
-	os.Setenv(v1alpha1.VersionEnvKey, oprVersion)
+	t.Setenv(v1alpha1.VersionEnvKey, oprVersion)
 
 	labels := td.GetLabels()
 	if labels == nil {
diff --git a/pkg/reconciler/kubernetes/tektoninstallerset/client/update_test.go b/pkg/reconciler/kubernetes/tektoninstallerset/client/update_test.go
index a6ce02dd6..1b5e13837 100644
--- a/pkg/reconciler/kubernetes/tektoninstallerset/client/update_test.go
+++ b/pkg/reconciler/kubernetes/tektoninstallerset/client/update_test.go
@@ -65,6 +65,27 @@ func TestInstallerSetClient_Update(t *testing.T) {
 		wantIS     int
 		wantErr    error
 	}{
+		{
+			name:    "update custom set",
+			setType: InstallerTypeCustom,
+			existingIS: []v1alpha1.TektonInstallerSet{
+				{
+					ObjectMeta: metav1.ObjectMeta{
+						Name: "addon-custom-set-asdas",
+						Annotations: map[string]string{
+							v1alpha1.LastAppliedHashKey: "custom",
+						},
+					},
+					Spec: v1alpha1.TektonInstallerSetSpec{
+						Manifests: []unstructured.Unstructured{
+							serviceAccount, deployment,
+						},
+					},
+				},
+			},
+			resources: []unstructured.Unstructured{serviceAccount, deployment},
+			wantErr:   nil,
+		},
 		{
 			name:    "update pre set",
 			setType: InstallerTypePre,
diff --git a/pkg/reconciler/openshift/tektonconfig/extension/addon_test.go b/pkg/reconciler/openshift/tektonconfig/extension/addon_test.go
index 7fdc7c4fd..2826cb14a 100644
--- a/pkg/reconciler/openshift/tektonconfig/extension/addon_test.go
+++ b/pkg/reconciler/openshift/tektonconfig/extension/addon_test.go
@@ -18,7 +18,6 @@ package extension
 
 import (
 	"context"
-	"os"
 	"testing"
 
 	"github.com/tektoncd/operator/pkg/reconciler/shared/tektonconfig/pipeline"
@@ -110,14 +109,16 @@ func makeUpgradeCheckPass(t *testing.T, ctx context.Context, c op.TektonAddonInt
 	// set necessary version labels to make upgrade check pass
 	addon, err := c.Get(ctx, v1alpha1.AddonResourceName, metav1.GetOptions{})
 	util.AssertEqual(t, err, nil)
-	setDummyVersionLabel(addon)
+	setDummyVersionLabel(t, addon)
 	_, err = c.Update(ctx, addon, metav1.UpdateOptions{})
 	util.AssertEqual(t, err, nil)
 }
 
-func setDummyVersionLabel(ta *v1alpha1.TektonAddon) {
+func setDummyVersionLabel(t *testing.T, ta *v1alpha1.TektonAddon) {
+	t.Helper()
+
 	oprVersion := "v1.2.3"
-	os.Setenv(v1alpha1.VersionEnvKey, oprVersion)
+	t.Setenv(v1alpha1.VersionEnvKey, oprVersion)
 
 	labels := ta.GetLabels()
 	if labels == nil {
diff --git a/pkg/reconciler/openshift/tektonconfig/extension/pipelinesascode_test.go b/pkg/reconciler/openshift/tektonconfig/extension/pipelinesascode_test.go
index c457cce8f..a2718c62d 100644
--- a/pkg/reconciler/openshift/tektonconfig/extension/pipelinesascode_test.go
+++ b/pkg/reconciler/openshift/tektonconfig/extension/pipelinesascode_test.go
@@ -18,13 +18,10 @@ package extension
 
 import (
 	"context"
-	"os"
 	"testing"
 
-	"github.com/tektoncd/operator/pkg/reconciler/shared/tektonconfig/pipeline"
-	"gotest.tools/v3/assert"
-
 	op "github.com/tektoncd/operator/pkg/client/clientset/versioned/typed/operator/v1alpha1"
+	"github.com/tektoncd/operator/pkg/reconciler/shared/tektonconfig/pipeline"
 
 	"github.com/tektoncd/operator/pkg/apis/operator/v1alpha1"
 	"github.com/tektoncd/operator/pkg/client/injection/client/fake"
@@ -38,8 +35,7 @@ func TestEnsureOpenShiftPipelinesAsCodeExists(t *testing.T) {
 	c := fake.Get(ctx)
 	tConfig := pipeline.GetTektonConfig()
 
-	assert.NilError(t, os.Setenv("PLATFORM", "openshift"))
-	defer os.Clearenv()
+	t.Setenv("PLATFORM", "openshift")
 
 	tConfig.SetDefaults(ctx)
 	// first invocation should create instance as it is non-existent and return RECONCILE_AGAIN_ERR
@@ -71,8 +67,7 @@ func TestEnsureOpenShiftPipelinesAsCodeCRNotExists(t *testing.T) {
 	ctx, _, _ := ts.SetupFakeContextWithCancel(t)
 	c := fake.Get(ctx)
 
-	assert.NilError(t, os.Setenv("PLATFORM", "openshift"))
-	defer os.Clearenv()
+	t.Setenv("PLATFORM", "openshift")
 
 	// when no instance exists, nil error is returned immediately
 	err := EnsureOpenShiftPipelinesAsCodeCRNotExists(ctx, c.OperatorV1alpha1().OpenShiftPipelinesAsCodes())
diff --git a/pkg/reconciler/shared/tektonconfig/pipeline/pipeline_test.go b/pkg/reconciler/shared/tektonconfig/pipeline/pipeline_test.go
index c8bd97ba3..13a5e3adc 100644
--- a/pkg/reconciler/shared/tektonconfig/pipeline/pipeline_test.go
+++ b/pkg/reconciler/shared/tektonconfig/pipeline/pipeline_test.go
@@ -18,7 +18,6 @@ package pipeline
 
 import (
 	"context"
-	"os"
 	"testing"
 
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -108,14 +107,16 @@ func makeUpgradeCheckPass(t *testing.T, ctx context.Context, c op.TektonPipeline
 	// set necessary version labels to make upgrade check pass
 	pipeline, err := c.Get(ctx, v1alpha1.PipelineResourceName, metav1.GetOptions{})
 	util.AssertEqual(t, err, nil)
-	setDummyVersionLabel(pipeline)
+	setDummyVersionLabel(t, pipeline)
 	_, err = c.Update(ctx, pipeline, metav1.UpdateOptions{})
 	util.AssertEqual(t, err, nil)
 }
 
-func setDummyVersionLabel(tp *v1alpha1.TektonPipeline) {
+func setDummyVersionLabel(t *testing.T, tp *v1alpha1.TektonPipeline) {
+	t.Helper()
+
 	oprVersion := "v1.2.3"
-	os.Setenv(v1alpha1.VersionEnvKey, oprVersion)
+	t.Setenv(v1alpha1.VersionEnvKey, oprVersion)
 
 	labels := tp.GetLabels()
 	if labels == nil {
diff --git a/pkg/reconciler/shared/tektonconfig/trigger/trigger_test.go b/pkg/reconciler/shared/tektonconfig/trigger/trigger_test.go
index 7f650eec1..abb15693f 100644
--- a/pkg/reconciler/shared/tektonconfig/trigger/trigger_test.go
+++ b/pkg/reconciler/shared/tektonconfig/trigger/trigger_test.go
@@ -18,7 +18,6 @@ package trigger
 
 import (
 	"context"
-	"os"
 	"testing"
 
 	op "github.com/tektoncd/operator/pkg/client/clientset/versioned/typed/operator/v1alpha1"
@@ -109,14 +108,16 @@ func makeUpgradeCheckPass(t *testing.T, ctx context.Context, c op.TektonTriggerI
 	// set necessary version labels to make upgrade check pass
 	trigger, err := c.Get(ctx, v1alpha1.TriggerResourceName, metav1.GetOptions{})
 	util.AssertEqual(t, err, nil)
-	setDummyVersionLabel(trigger)
+	setDummyVersionLabel(t, trigger)
 	_, err = c.Update(ctx, trigger, metav1.UpdateOptions{})
 	util.AssertEqual(t, err, nil)
 }
 
-func setDummyVersionLabel(tr *v1alpha1.TektonTrigger) {
+func setDummyVersionLabel(t *testing.T, tr *v1alpha1.TektonTrigger) {
+	t.Helper()
+
 	oprVersion := "v1.2.3"
-	os.Setenv(v1alpha1.VersionEnvKey, oprVersion)
+	t.Setenv(v1alpha1.VersionEnvKey, oprVersion)
 
 	labels := tr.GetLabels()
 	if labels == nil {
diff --git a/pkg/webhook/webhook_init_test.go b/pkg/webhook/webhook_init_test.go
index 4d439a18a..bf332c0f9 100644
--- a/pkg/webhook/webhook_init_test.go
+++ b/pkg/webhook/webhook_init_test.go
@@ -1,7 +1,6 @@
 package webhook
 
 import (
-	"os"
 	"path/filepath"
 	"testing"
 
@@ -20,10 +19,7 @@ func TestCreateWebhookResources(t *testing.T) {
 		testdataPath := filepath.Join("testdata", "validating-defaulting-webhook")
 		m, err := mf.ManifestFrom(mf.Path(testdataPath))
 		assert.NilError(t, err)
-		os.Setenv(POD_NAMESPACE_ENV_KEY, namespace_new)
-		defer func() {
-			os.Unsetenv(POD_NAMESPACE_ENV_KEY)
-		}()
+		t.Setenv(POD_NAMESPACE_ENV_KEY, namespace_new)
 		mOut, err := manifestTransform(&m)
 		assert.NilError(t, err)
 		for _, res := range mOut.Resources() {