Skip to content

Commit 173f3e2

Browse files
authored
📖 Updating doc with Installation steps of cert-manager and prometheus (#2982)
* Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks Adding installing steps for testing webhooks * Adding installing steps for testing webhooks * Adding installing steps for testing webhooks * Adding installing steps for testing webhooks
1 parent 9a98346 commit 173f3e2

File tree

1 file changed

+139
-9
lines changed

1 file changed

+139
-9
lines changed

docs/book/src/reference/envtest.md

Lines changed: 139 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ The make targets require `bash` to run.
1212

1313
## Installation in Air Gaped/disconnected environments
1414
If you would like to download the tarball containing the binaries, to use in a disconnected environment you can use
15-
`setup-envtest` to download the required binaries locally. There are a lot of ways to configure `setup-envtest` to avoid talking to
15+
[`setup-envtest`][setup-envtest] to download the required binaries locally. There are a lot of ways to configure `setup-envtest` to avoid talking to
1616
the internet you can read about them [here](https://github.com/kubernetes-sigs/controller-runtime/tree/master/tools/setup-envtest#what-if-i-dont-want-to-talk-to-the-internet).
1717
The examples below will show how to install the Kubernetes API binaries using mostly defaults set by `setup-envtest`.
1818

@@ -76,6 +76,15 @@ err = testEnv.Stop()
7676
7777
Logs from the test runs are prefixed with `test-env`.
7878
79+
<aside class="note">
80+
<h1>Examples</h1>
81+
82+
You can use the plugin [DeployImage](https://book.kubebuilder.io/plugins/deploy-image-plugin-v1-alpha.html) to check examples. This plugin allows users to scaffold API/Controllers to deploy and manage an Operand (image) on the cluster following the guidelines and best practices. It abstracts the complexities of achieving this goal while allowing users to customize the generated code.
83+
84+
Therefore, you can check that a test using ENV TEST will be generated for the controller which has the purpose to ensure that the Deployment is created successfully. You can see an example of its code implementation under the `testdata` directory with the [DeployImage](https://book.kubebuilder.io/plugins/deploy-image-plugin-v1-alpha.html) samples [here](https://github.com/kubernetes-sigs/kubebuilder/blob/v3.7.0/testdata/project-v3-with-deploy-image/controllers/busybox_controller_test.go).
85+
86+
</aside>
87+
7988
### Configuring your test control plane
8089
8190
Controller-runtime’s [envtest][envtest] framework requires `kubectl`, `kube-apiserver`, and `etcd` binaries be present locally to simulate the API portions of a real cluster.
@@ -97,12 +106,12 @@ You can use environment variables and/or flags to specify the `kubectl`,`api-ser
97106
### Environment Variables
98107
99108
| Variable name | Type | When to use |
100-
| --- | :--- | :--- |
109+
| --- | :--- | :--- |
101110
| `USE_EXISTING_CLUSTER` | boolean | Instead of setting up a local control plane, point to the control plane of an existing cluster. |
102-
| `KUBEBUILDER_ASSETS` | path to directory | Point integration tests to a directory containing all binaries (api-server, etcd and kubectl). |
103-
| `TEST_ASSET_KUBE_APISERVER`, `TEST_ASSET_ETCD`, `TEST_ASSET_KUBECTL` | paths to, respectively, api-server, etcd and kubectl binaries | Similar to `KUBEBUILDER_ASSETS`, but more granular. Point integration tests to use binaries other than the default ones. These environment variables can also be used to ensure specific tests run with expected versions of these binaries. |
104-
| `KUBEBUILDER_CONTROLPLANE_START_TIMEOUT` and `KUBEBUILDER_CONTROLPLANE_STOP_TIMEOUT` | durations in format supported by [`time.ParseDuration`](https://golang.org/pkg/time/#ParseDuration) | Specify timeouts different from the default for the test control plane to (respectively) start and stop; any test run that exceeds them will fail. |
105-
| `KUBEBUILDER_ATTACH_CONTROL_PLANE_OUTPUT` | boolean | Set to `true` to attach the control plane's stdout and stderr to os.Stdout and os.Stderr. This can be useful when debugging test failures, as output will include output from the control plane. |
111+
| `KUBEBUILDER_ASSETS` | path to directory | Point integration tests to a directory containing all binaries (api-server, etcd and kubectl). |
112+
| `TEST_ASSET_KUBE_APISERVER`, `TEST_ASSET_ETCD`, `TEST_ASSET_KUBECTL` | paths to, respectively, api-server, etcd and kubectl binaries | Similar to `KUBEBUILDER_ASSETS`, but more granular. Point integration tests to use binaries other than the default ones. These environment variables can also be used to ensure specific tests run with expected versions of these binaries. |
113+
| `KUBEBUILDER_CONTROLPLANE_START_TIMEOUT` and `KUBEBUILDER_CONTROLPLANE_STOP_TIMEOUT` | durations in format supported by [`time.ParseDuration`](https://golang.org/pkg/time/#ParseDuration) | Specify timeouts different from the default for the test control plane to (respectively) start and stop; any test run that exceeds them will fail. |
114+
| `KUBEBUILDER_ATTACH_CONTROL_PLANE_OUTPUT` | boolean | Set to `true` to attach the control plane's stdout and stderr to os.Stdout and os.Stderr. This can be useful when debugging test failures, as output will include output from the control plane. |
106115

107116
See that the `test` makefile target will ensure that all is properly setup when you are using it. However, if you would like to run the tests without use the Makefile targets, for example via an IDE, then you can set the environment variables directly in the code of your `suite_test.go`:
108117

@@ -116,7 +125,7 @@ var _ = BeforeSuite(func(done Done) {
116125
117126
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
118127
testenv = &envtest.Environment{}
119-
128+
120129
_, err := testenv.Start()
121130
Expect(err).NotTo(HaveOccurred())
122131
@@ -133,6 +142,14 @@ var _ = AfterSuite(func() {
133142
})
134143
```
135144

145+
<aside class="note">
146+
<h1>ENV TEST Config Options</h1>
147+
148+
You can look at the controller-runtime docs to know more about its configuration options, see [here](https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/envtest#Environment). On top of that, if you are
149+
looking to use ENV TEST to test your webhooks then you might want to give a look at its install [options](https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/envtest#WebhookInstallOptions).
150+
151+
</aside>
152+
136153
### Flags
137154
Here's an example of modifying the flags with which to start the API server in your integration tests, compared to the default values in `envtest.DefaultKubeAPIServerFlags`:
138155
@@ -167,5 +184,118 @@ expectedOwnerReference := v1.OwnerReference{
167184
Expect(deployment.ObjectMeta.OwnerReferences).To(ContainElement(expectedOwnerReference))
168185
```
169186

170-
[envtest]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/envtest
171-
[setup-envtest]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/tools/setup-envtest
187+
## Cert-Manager and Prometheus options
188+
189+
Projects scaffolded with Kubebuilder can enable the [`metrics`][metrics] and the [`cert-manager`][cert-manager] options. Note that when we are using the ENV TEST we are looking to test the controllers and their reconciliation. It is considered an integrated test because the ENV TEST API will do the test against a cluster and because of this the binaries are downloaded and used to configure its pre-requirements, however, its purpose is mainly to `unit` test the controllers.
190+
191+
Therefore, to test a reconciliation in common cases you do not need to care about these options. However, if you would like to do tests with the Prometheus and the Cert-manager installed you can add the required steps to install them before running the tests.
192+
Following an example.
193+
194+
```go
195+
// Add the operations to install the Prometheus operator and the cert-manager
196+
// before the tests.
197+
BeforeEach(func() {
198+
By("installing prometheus operator")
199+
Expect(utils.InstallPrometheusOperator()).To(Succeed())
200+
201+
By("installing the cert-manager")
202+
Expect(utils.InstallCertManager()).To(Succeed())
203+
}
204+
205+
// You can also remove them after the tests::
206+
AfterEach(func() {
207+
By("uninstalling the Prometheus manager bundle")
208+
utils.UninstallPrometheusOperManager()
209+
210+
By("uninstalling the cert-manager bundle")
211+
utils.UninstallCertManager()
212+
})
213+
```
214+
215+
Check the following example of how you can implement the above operations:
216+
217+
```go
218+
const (
219+
prometheusOperatorVersion = "0.51"
220+
prometheusOperatorURL = "https://raw.githubusercontent.com/prometheus-operator/" + "prometheus-operator/release-%s/bundle.yaml"
221+
certmanagerVersion = "v1.5.3"
222+
certmanagerURLTmpl = "https://github.com/jetstack/cert-manager/releases/download/%s/cert-manager.yaml"
223+
)
224+
225+
func warnError(err error) {
226+
fmt.Fprintf(GinkgoWriter, "warning: %v\n", err)
227+
}
228+
229+
// InstallPrometheusOperator installs the prometheus Operator to be used to export the enabled metrics.
230+
func InstallPrometheusOperator() error {
231+
url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion)
232+
cmd := exec.Command("kubectl", "apply", "-f", url)
233+
_, err := Run(cmd)
234+
return err
235+
}
236+
237+
// UninstallPrometheusOperator uninstalls the prometheus
238+
func UninstallPrometheusOperator() {
239+
url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion)
240+
cmd := exec.Command("kubectl", "delete", "-f", url)
241+
if _, err := Run(cmd); err != nil {
242+
warnError(err)
243+
}
244+
}
245+
246+
// UninstallCertManager uninstalls the cert manager
247+
func UninstallCertManager() {
248+
url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion)
249+
cmd := exec.Command("kubectl", "delete", "-f", url)
250+
if _, err := Run(cmd); err != nil {
251+
warnError(err)
252+
}
253+
}
254+
255+
// InstallCertManager installs the cert manager bundle.
256+
func InstallCertManager() error {
257+
url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion)
258+
cmd := exec.Command("kubectl", "apply", "-f", url)
259+
if _, err := Run(cmd); err != nil {
260+
return err
261+
}
262+
// Wait for cert-manager-webhook to be ready, which can take time if cert-manager
263+
//was re-installed after uninstalling on a cluster.
264+
cmd = exec.Command("kubectl", "wait", "deployment.apps/cert-manager-webhook",
265+
"--for", "condition=Available",
266+
"--namespace", "cert-manager",
267+
"--timeout", "5m",
268+
)
269+
270+
_, err := Run(cmd)
271+
return err
272+
}
273+
274+
// LoadImageToKindCluster loads a local docker image to the kind cluster
275+
func LoadImageToKindClusterWithName(name string) error {
276+
cluster := "kind"
277+
if v, ok := os.LookupEnv("KIND_CLUSTER"); ok {
278+
cluster = v
279+
}
280+
281+
kindOptions := []string{"load", "docker-image", name, "--name", cluster}
282+
cmd := exec.Command("kind", kindOptions...)
283+
_, err := Run(cmd)
284+
return err
285+
}
286+
```
287+
However, see that tests for the metrics and cert-manager might fit better well as e2e tests and not under the tests done using ENV TEST for the controllers. You might want to give a look at the [sample example][sdk-e2e-sample-example] implemented into [Operator-SDK][sdk] repository to know how you can write your e2e tests to ensure the basic workflows of your project.
288+
Also, see that you can run the tests against a cluster where you have some configurations in place they can use the option to test using an existing cluster:
289+
290+
```go
291+
testEnv = &envtest.Environment{
292+
UseExistingCluster: true,
293+
}
294+
```
295+
296+
[metrics]: https://book.kubebuilder.io/reference/metrics.html
297+
[envtest]: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/envtest
298+
[setup-envtest]: https://pkg.go.dev/sigs.k8s.io/controller-runtime/tools/setup-envtest
299+
[cert-manager]: https://book.kubebuilder.io/cronjob-tutorial/cert-manager.html
300+
[sdk-e2e-sample-example]: https://github.com/operator-framework/operator-sdk/tree/master/testdata/go/v3/memcached-operator/test/e2e
301+
[sdk]: https://github.com/operator-framework/operator-sdk

0 commit comments

Comments
 (0)