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

Default to helm release's namespace for templates where ns unspecified #1733

Merged
merged 5 commits into from
Sep 30, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
## HEAD (Unreleased)
(None)
- Use helm release's namespace on templates where namespace is left unspecified (https://github.com/pulumi/pulumi-kubernetes/pull/1733)

## 3.7.2 (September 17, 2021)
- Fix handling of charts with empty manifests (https://github.com/pulumi/pulumi-kubernetes/pull/1717)
Expand Down
56 changes: 44 additions & 12 deletions provider/pkg/provider/helm_release.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"strings"
"time"

"k8s.io/client-go/tools/clientcmd/api"

jsonpatch "github.com/evanphx/json-patch"
pbempty "github.com/golang/protobuf/ptypes/empty"
pkgerrors "github.com/pkg/errors"
Expand Down Expand Up @@ -155,7 +157,9 @@ type ReleaseStatus struct {
type helmReleaseProvider struct {
host *provider.HostClient
helmDriver string
kubeConfig *KubeConfig
apiConfig *api.Config
defaultOverrides *clientcmd.ConfigOverrides
restConfig *rest.Config
defaultNamespace string
enableSecrets bool
name string
Expand All @@ -164,8 +168,9 @@ type helmReleaseProvider struct {

func newHelmReleaseProvider(
host *provider.HostClient,
config *rest.Config,
clientConfig clientcmd.ClientConfig,
apiConfig *api.Config,
defaultOverrides *clientcmd.ConfigOverrides,
restConfig *rest.Config,
helmDriver,
namespace string,
enableSecrets bool,
Expand All @@ -174,7 +179,6 @@ func newHelmReleaseProvider(
repositoryConfigPath,
repositoryCache string,
) (customResourceProvider, error) {
kc := newKubeConfig(config, clientConfig)
settings := cli.New()
settings.PluginsDirectory = pluginsDirectory
settings.RegistryConfig = registryConfigPath
Expand All @@ -183,7 +187,9 @@ func newHelmReleaseProvider(

return &helmReleaseProvider{
host: host,
kubeConfig: kc,
apiConfig: apiConfig,
defaultOverrides: defaultOverrides,
restConfig: restConfig,
helmDriver: helmDriver,
defaultNamespace: namespace,
enableSecrets: enableSecrets,
Expand All @@ -196,9 +202,35 @@ func debug(format string, a ...interface{}) {
logger.V(9).Infof("[DEBUG] %s", fmt.Sprintf(format, a...))
}

func (r *helmReleaseProvider) getActionConfig(namespace string) (*action.Configuration, error) {
func (r *helmReleaseProvider) getActionConfig(namespace string, override bool) (*action.Configuration, error) {
conf := new(action.Configuration)
if err := conf.Init(r.kubeConfig, namespace, r.helmDriver, debug); err != nil {
var overrides clientcmd.ConfigOverrides
if r.defaultOverrides != nil {
overrides = *r.defaultOverrides
}

if override {
// This essentially points the client to use the specified namespace when a namespaced
// object doesn't have the namespace specified. This allows us to interpolate the
// release's namespace as the default namespace on charts with templates that don't
// explicitly set the namespace (e.g. through namespace: {{ .Release.Namespace }}).
overrides.Context.Namespace = namespace
}

var clientConfig clientcmd.ClientConfig
if r.apiConfig != nil {
clientConfig = clientcmd.NewDefaultClientConfig(*r.apiConfig, &overrides)
} else {
// Use client-go to resolve the final configuration values for the client. Typically these
// values would would reside in the $KUBECONFIG file, but can also be altered in several
// places, including in env variables, client-go default values, and (if we allowed it) CLI
// flags.
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig
clientConfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &overrides)
}
kc := newKubeConfig(r.restConfig, clientConfig)
if err := conf.Init(kc, namespace, r.helmDriver, debug); err != nil {
return nil, err
}
return conf, nil
Expand Down Expand Up @@ -275,7 +307,7 @@ func (r *helmReleaseProvider) Check(ctx context.Context, req *pulumirpc.CheckReq
templateRelease = true
} else {
assignNameIfAutonameable(new, news, "release")
conf, err := r.getActionConfig(new.Namespace)
conf, err := r.getActionConfig(new.Namespace, false)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -345,7 +377,7 @@ func (r *helmReleaseProvider) Check(ctx context.Context, req *pulumirpc.CheckReq
}

func (r *helmReleaseProvider) helmCreate(ctx context.Context, urn resource.URN, news resource.PropertyMap, newRelease *Release) error {
conf, err := r.getActionConfig(newRelease.Namespace)
conf, err := r.getActionConfig(newRelease.Namespace, true)
if err != nil {
return err
}
Expand Down Expand Up @@ -491,7 +523,7 @@ func (r *helmReleaseProvider) helmUpdate(ctx context.Context, urn resource.URN,
}
}

actionConfig, err := r.getActionConfig(oldRelease.Namespace)
actionConfig, err := r.getActionConfig(oldRelease.Namespace, true)
if err != nil {
return err
}
Expand Down Expand Up @@ -802,7 +834,7 @@ func (r *helmReleaseProvider) Read(ctx context.Context, req *pulumirpc.ReadReque

logger.V(9).Infof("%s Starting import for %s/%s", label, namespace, name)

actionConfig, err := r.getActionConfig(namespace)
actionConfig, err := r.getActionConfig(namespace, false)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -943,7 +975,7 @@ func (r *helmReleaseProvider) Delete(ctx context.Context, req *pulumirpc.DeleteR
}

namespace := release.Namespace
actionConfig, err := r.getActionConfig(namespace)
actionConfig, err := r.getActionConfig(namespace, false)
if err != nil {
return nil, err
}
Expand Down
11 changes: 7 additions & 4 deletions provider/pkg/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,7 @@ func (k *kubeProvider) Configure(_ context.Context, req *pulumirpc.ConfigureRequ
}

var kubeconfig clientcmd.ClientConfig
var apiConfig *clientapi.Config
homeDir := func() string {
// Ignore errors. The filepath will be checked later, so we can handle failures there.
usr, _ := user.Current()
Expand All @@ -567,7 +568,8 @@ func (k *kubeProvider) Configure(_ context.Context, req *pulumirpc.ConfigureRequ
}

// If the variable is a valid filepath, load the file and parse the contents as a k8s config.
if _, err := os.Stat(pathOrContents); err == nil {
_, err := os.Stat(pathOrContents)
if err == nil {
b, err := ioutil.ReadFile(pathOrContents)
if err != nil {
unreachableCluster(err)
Expand All @@ -579,11 +581,11 @@ func (k *kubeProvider) Configure(_ context.Context, req *pulumirpc.ConfigureRequ
}

// Load the contents of the k8s config.
config, err := clientcmd.Load([]byte(contents))
apiConfig, err = clientcmd.Load([]byte(contents))
if err != nil {
unreachableCluster(err)
} else {
kubeconfig = clientcmd.NewDefaultClientConfig(*config, overrides)
kubeconfig = clientcmd.NewDefaultClientConfig(*apiConfig, overrides)
configurationNamespace, _, err := kubeconfig.Namespace()
if err == nil {
k.defaultNamespace = configurationNamespace
Expand Down Expand Up @@ -622,8 +624,9 @@ func (k *kubeProvider) Configure(_ context.Context, req *pulumirpc.ConfigureRequ
}
k.helmReleaseProvider, err = newHelmReleaseProvider(
k.host,
apiConfig,
overrides,
k.config,
kubeconfig,
k.helmDriver,
namespace,
k.enableSecrets,
Expand Down
28 changes: 22 additions & 6 deletions tests/sdk/nodejs/examples/examples_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2016-2019, Pulumi Corporation.
// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -420,14 +420,14 @@ func TestHelmRelease(t *testing.T) {
assert.True(t, is)
versionOut, has := specMap["version"]
assert.True(t, has)
assert.Equal(t, version , versionOut)
assert.Equal(t, version, versionOut)
}
}
},
EditDirs: []integration.EditDir{
{
Dir: filepath.Join(getCwd(t), "helm-release", "step2"),
Additive: true,
Dir: filepath.Join(getCwd(t), "helm-release", "step2"),
Additive: true,
},
},
})
Expand All @@ -446,15 +446,31 @@ func TestHelmReleaseCRD(t *testing.T) {
Verbose: true,
EditDirs: []integration.EditDir{
{
Dir: filepath.Join(getCwd(t), "helm-release-crd", "step2"),
Additive: true,
Dir: filepath.Join(getCwd(t), "helm-release-crd", "step2"),
Additive: true,
},
},
})

integration.ProgramTest(t, &test)
}

func TestHelmReleasePrometheus(t *testing.T) {
// Validate fix for https://github.com/pulumi/pulumi-kubernetes/issues/1710
skipIfShort(t)
test := getBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "helm-release-prometheus"),
SkipRefresh: false,
Verbose: true,
// Ensure that the rule was found in the release's namespace.
ExtraRuntimeValidation: func(t *testing.T, stackInfo integration.RuntimeValidationStackInfo) {
assert.NotEmpty(t, stackInfo.Outputs["ruleUrn"].(string))
},
})

integration.ProgramTest(t, &test)
}

func skipIfShort(t *testing.T) {
if testing.Short() {
Expand Down
3 changes: 3 additions & 0 deletions tests/sdk/nodejs/examples/helm-release-prometheus/Pulumi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name: helm-release-prometheus
runtime: nodejs
description: A minimal Kubernetes TypeScript Pulumi program
39 changes: 39 additions & 0 deletions tests/sdk/nodejs/examples/helm-release-prometheus/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";


const namespace = new k8s.core.v1.Namespace("release-ns");

const prometheusOperator = new k8s.helm.v3.Release("prometheus", {
viveklak marked this conversation as resolved.
Show resolved Hide resolved
name: "prometheus-operator",
namespace: namespace.metadata.name,
chart: "prometheus-operator",
version: "8.5.2",
repositoryOpts: {
repo: "https://charts.helm.sh/stable",
},
values: {},
});

export const namespaceName = namespace.metadata.name
// Explicitly look for the rule in the release's namespace.
export const ruleUrn = k8s.apiextensions.CustomResource.get("prom-rule",
{
apiVersion: "monitoring.coreos.com/v1",
kind: "PrometheusRule",
id: pulumi.interpolate`${prometheusOperator.status.namespace}/${prometheusOperator.status.name}-prometheus-operator`
}).urn;
11 changes: 11 additions & 0 deletions tests/sdk/nodejs/examples/helm-release-prometheus/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "helm-release-prometheus",
"devDependencies": {
"@types/node": "^10.0.0"
},
"dependencies": {
"@pulumi/pulumi": "^3.0.0",
"@pulumi/kubernetes": "latest",
"@pulumi/kubernetesx": "^0.1.5"
}
}
18 changes: 18 additions & 0 deletions tests/sdk/nodejs/examples/helm-release-prometheus/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"strict": true,
"outDir": "bin",
"target": "es2016",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"experimentalDecorators": true,
"pretty": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.ts"
]
}