helmclient

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2023 License: MIT Imports: 38 Imported by: 0

README

Go Helm Client

Go client library for accessing Helm, enabling the user to programmatically change helm charts and releases.

This library is build upon helm and available under the MIT License.

GitHub license Go Report Card Documentation

Installation

Install this library using go get:

$ go get github.com/whybeyoung/go-helm-client

Usage

Example usage of the client can be found in the package examples.

Private chart repository

When working with private repositories, you can utilize the Username and Password parameters of a chart entry to specify credentials.

An example of this can be found in the corresponding example.

Mock Client

This library includes a mock client mock/interface_mock.go which is generated by mockgen.

Example usage of the mocked client can be found in mock/mock_test.go.

If you made changes to interface.go, you should issue the make generate command to trigger code generation.

Documentation

For more specific documentation, please refer to the godoc of this library.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChartSpec

type ChartSpec struct {
	ReleaseName string `json:"release"`
	ChartName   string `json:"chart"`
	// Namespace where the chart release is deployed.
	// Note that helmclient.Options.Namespace should ideally match the namespace configured here.
	Namespace string `json:"namespace"`
	// ValuesYaml is the values.yaml content.
	// use string instead of map[string]interface{}
	// https://github.com/kubernetes-sigs/kubebuilder/issues/528#issuecomment-466449483
	// and https://github.com/kubernetes-sigs/controller-tools/pull/317
	// +optional
	ValuesYaml string `json:"valuesYaml,omitempty"`
	// Specify values similar to the cli
	// +optional
	ValuesOptions values.Options `json:"valuesOptions,omitempty"`
	// Version of the chart release.
	// +optional
	Version string `json:"version,omitempty"`
	// CreateNamespace indicates whether to create the namespace if it does not exist.
	// +optional
	CreateNamespace bool `json:"createNamespace,omitempty"`
	// DisableHooks indicates whether to disable hooks.
	// +optional
	DisableHooks bool `json:"disableHooks,omitempty"`
	// Replace indicates whether to replace the chart release if it already exists.
	// +optional
	Replace bool `json:"replace,omitempty"`
	// Wait indicates whether to wait for the release to be deployed or not.
	// +optional
	Wait bool `json:"wait,omitempty"`
	// WaitForJobs indicates whether to wait for completion of release Jobs before marking the release as successful.
	// 'Wait' has to be specified for this to take effect.
	// The timeout may be specified via the 'Timeout' field.
	WaitForJobs bool `json:"waitForJobs,omitempty"`
	// DependencyUpdate indicates whether to update the chart release if the dependencies have changed.
	// +optional
	DependencyUpdate bool `json:"dependencyUpdate,omitempty"`
	// Timeout configures the time to wait for any individual Kubernetes operation (like Jobs for hooks).
	// +optional
	Timeout time.Duration `json:"timeout,omitempty"`
	// GenerateName indicates that the release name should be generated.
	// +optional
	GenerateName bool `json:"generateName,omitempty"`
	// NameTemplate is the template used to generate the release name if GenerateName is configured.
	// +optional
	NameTemplate string `json:"nameTemplate,omitempty"`
	// Atomic indicates whether to install resources atomically.
	// 'Wait' will automatically be set to true when using Atomic.
	// +optional
	Atomic bool `json:"atomic,omitempty"`
	// SkipCRDs indicates whether to skip CRDs during installation.
	// +optional
	SkipCRDs bool `json:"skipCRDs,omitempty"`
	// Upgrade indicates whether to perform a CRD upgrade during installation.
	// +optional
	UpgradeCRDs bool `json:"upgradeCRDs,omitempty"`
	// SubNotes indicates whether to print sub-notes.
	// +optional
	SubNotes bool `json:"subNotes,omitempty"`
	// Force indicates whether to force the operation.
	// +optional
	Force bool `json:"force,omitempty"`
	// ResetValues indicates whether to reset the values.yaml file during installation.
	// +optional
	ResetValues bool `json:"resetValues,omitempty"`
	// ReuseValues indicates whether to reuse the values.yaml file during installation.
	// +optional
	ReuseValues bool `json:"reuseValues,omitempty"`
	// Recreate indicates whether to recreate the release if it already exists.
	// +optional
	Recreate bool `json:"recreate,omitempty"`
	// MaxHistory limits the maximum number of revisions saved per release.
	// +optional
	MaxHistory int `json:"maxHistory,omitempty"`
	// CleanupOnFail indicates whether to cleanup the release on failure.
	// +optional
	CleanupOnFail bool `json:"cleanupOnFail,omitempty"`
	// DryRun indicates whether to perform a dry run.
	// +optional
	DryRun bool `json:"dryRun,omitempty"`
	// Description specifies a custom description for the uninstalled release
	// +optional
	Description string `json:"description,omitempty"`
	// KeepHistory indicates whether to retain or purge the release history during uninstall
	// +optional
	KeepHistory bool `json:"keepHistory,omitempty"`
}

ChartSpec defines the values of a helm chart +kubebuilder:object:generate:=true

func (*ChartSpec) DeepCopy

func (in *ChartSpec) DeepCopy() *ChartSpec

DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartSpec.

func (*ChartSpec) DeepCopyInto

func (in *ChartSpec) DeepCopyInto(out *ChartSpec)

DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (*ChartSpec) GetValuesMap

func (spec *ChartSpec) GetValuesMap(p getter.Providers) (map[string]interface{}, error)

GetValuesMap returns the merged mapped out values of a chart, using both ValuesYaml and ValuesOptions

type Client

type Client interface {
	AddOrUpdateChartRepo(entry repo.Entry) error
	UpdateChartRepos() error
	InstallOrUpgradeChart(ctx context.Context, spec *ChartSpec, opts *GenericHelmOptions) (*release.Release, error)
	InstallChart(ctx context.Context, spec *ChartSpec, opts *GenericHelmOptions) (*release.Release, error)
	UpgradeChart(ctx context.Context, spec *ChartSpec, opts *GenericHelmOptions) (*release.Release, error)
	ListDeployedReleases() ([]*release.Release, error)
	ListReleasesByStateMask(action.ListStates) ([]*release.Release, error)
	GetRelease(name string) (*release.Release, error)
	// RollBack is an interface to abstract a rollback action.
	RollBack
	GetReleaseValues(name string, allValues bool) (map[string]interface{}, error)
	UninstallRelease(spec *ChartSpec) error
	UninstallReleaseByName(name string) error
	TemplateChart(spec *ChartSpec, options *HelmTemplateOptions) ([]byte, error)
	LintChart(spec *ChartSpec) error
	SetDebugLog(debugLog action.DebugLog)
	ListReleaseHistory(name string, max int) ([]*release.Release, error)
	GetChart(chartName string, chartPathOptions *action.ChartPathOptions) (*chart.Chart, string, error)
	StatusRelease(name string) (*release.Release, error)
}

Client holds the method signatures for a Helm client. NOTE: This is an interface to allow for mocking in tests.

func New

func New(options *Options) (Client, error)

New returns a new Helm client with the provided options

Example
var outputBuffer bytes.Buffer

opt := &Options{
	Namespace:        "default", // Change this to the namespace you wish the client to operate in.
	RepositoryCache:  "/tmp/.helmcache",
	RepositoryConfig: "/tmp/.helmrepo",
	Debug:            true,
	Linting:          true,
	DebugLog:         func(format string, v ...interface{}) {},
	Output:           &outputBuffer, // Not mandatory, leave open for default os.Stdout
}

helmClient, err := New(opt)
if err != nil {
	panic(err)
}
_ = helmClient
Output:

func NewClientFromKubeConf

func NewClientFromKubeConf(options *KubeConfClientOptions, restClientOpts ...RESTClientOption) (Client, error)

NewClientFromKubeConf returns a new Helm client constructed with the provided kubeconfig & RESTClient (optional) options.

Example
opt := &KubeConfClientOptions{
	Options: &Options{
		Namespace:        "default", // Change this to the namespace you wish to install the chart in.
		RepositoryCache:  "/tmp/.helmcache",
		RepositoryConfig: "/tmp/.helmrepo",
		Debug:            true,
		Linting:          true, // Change this to false if you don't want linting.
		DebugLog: func(format string, v ...interface{}) {
			// Change this to your own logger. Default is 'log.Printf(format, v...)'.
		},
	},
	KubeContext: "",
	KubeConfig:  []byte{},
}

helmClient, err := NewClientFromKubeConf(opt, Burst(100), Timeout(10e9))
if err != nil {
	panic(err)
}
_ = helmClient
Output:

func NewClientFromRestConf

func NewClientFromRestConf(options *RestConfClientOptions) (Client, error)

NewClientFromRestConf returns a new Helm client constructed with the provided REST config options.

Example
opt := &RestConfClientOptions{
	Options: &Options{
		Namespace:        "default", // Change this to the namespace you wish the client to operate in.
		RepositoryCache:  "/tmp/.helmcache",
		RepositoryConfig: "/tmp/.helmrepo",
		Debug:            true,
		Linting:          true, // Change this to false if you don't want linting.
		DebugLog: func(format string, v ...interface{}) {
			// Change this to your own logger. Default is 'log.Printf(format, v...)'.
		},
	},
	RestConfig: &rest.Config{},
}

helmClient, err := NewClientFromRestConf(opt)
if err != nil {
	panic(err)
}
_ = helmClient
Output:

type GenericHelmOptions

type GenericHelmOptions struct {
	PostRenderer postrender.PostRenderer
	RollBack     RollBack
}

type HelmClient

type HelmClient struct {
	// Settings defines the environment settings of a client.
	Settings  *cli.EnvSettings
	Providers getter.Providers

	// ActionConfig is the helm action configuration.
	ActionConfig *action.Configuration

	DebugLog action.DebugLog
	// contains filtered or unexported fields
}

HelmClient Client defines the values of a helm client.

func (*HelmClient) AddOrUpdateChartRepo

func (c *HelmClient) AddOrUpdateChartRepo(entry repo.Entry) error

AddOrUpdateChartRepo adds or updates the provided helm chart repository.

Example (Private)
// Define a private chart repository
chartRepo := repo.Entry{
	Name:     "stable",
	URL:      "https://private-chartrepo.somedomain.com",
	Username: "foo",
	Password: "bar",
	// Since helm 3.6.1 it is necessary to pass 'PassCredentialsAll = true'.
	PassCredentialsAll: true,
}

// Add a chart-repository to the client.
if err := helmClient.AddOrUpdateChartRepo(chartRepo); err != nil {
	panic(err)
}
Output:

Example (Public)
// Define a public chart repository.
chartRepo := repo.Entry{
	Name: "stable",
	URL:  "https://charts.helm.sh/stable",
}

// Add a chart-repository to the client.
if err := helmClient.AddOrUpdateChartRepo(chartRepo); err != nil {
	panic(err)
}
Output:

func (*HelmClient) GetChart

func (c *HelmClient) GetChart(chartName string, chartPathOptions *action.ChartPathOptions) (*chart.Chart, string, error)

GetChart returns a chart matching the provided chart name and options.

func (*HelmClient) GetRelease

func (c *HelmClient) GetRelease(name string) (*release.Release, error)

GetRelease returns a release specified by name.

Example
// Get specific details of a deployed release.
if _, err := helmClient.GetRelease("etcd-operator"); err != nil {
	panic(err)
}
Output:

func (*HelmClient) GetReleaseValues

func (c *HelmClient) GetReleaseValues(name string, allValues bool) (map[string]interface{}, error)

GetReleaseValues returns the (optionally, all computed) values for the specified release.

Example
// Get the values of a deployed release.
if _, err := helmClient.GetReleaseValues("etcd-operator", true); err != nil {
	panic(err)
}
Output:

func (*HelmClient) InstallChart

func (c *HelmClient) InstallChart(ctx context.Context, spec *ChartSpec, opts *GenericHelmOptions) (*release.Release, error)

InstallChart installs the provided chart and returns the corresponding release. Namespace and other context is provided via the helmclient.Options struct when instantiating a client.

func (*HelmClient) InstallOrUpgradeChart

func (c *HelmClient) InstallOrUpgradeChart(ctx context.Context, spec *ChartSpec, opts *GenericHelmOptions) (*release.Release, error)

InstallOrUpgradeChart installs or upgrades the provided chart and returns the corresponding release. Namespace and other context is provided via the helmclient.Options struct when instantiating a client.

Example
// Define the chart to be installed
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "stable/etcd-operator",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
}

// Install a chart release.
// Note that helmclient.Options.Namespace should ideally match the namespace in chartSpec.Namespace.
if _, err := helmClient.InstallOrUpgradeChart(context.Background(), &chartSpec, nil); err != nil {
	panic(err)
}
Output:

Example (UseChartDirectory)
// Use an unpacked chart directory.
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "/path/to/stable/etcd-operator",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
}

if _, err := helmClient.InstallOrUpgradeChart(context.Background(), &chartSpec, nil); err != nil {
	panic(err)
}
Output:

Example (UseCustomRollBackStrategy)
// Define the chart to be installed
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "stable/etcd-operator",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
}

// Use a custom rollback strategy (customRollBack needs to implement RollBack).
rollBacker := customRollBack{}

opts := GenericHelmOptions{
	RollBack: rollBacker,
}

// Install a chart release.
// Note that helmclient.Options.Namespace should ideally match the namespace in chartSpec.Namespace.
if _, err := helmClient.InstallOrUpgradeChart(context.Background(), &chartSpec, &opts); err != nil {
	panic(err)
}
Output:

Example (UseDefaultRollBackStrategy)
// Define the chart to be installed
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "stable/etcd-operator",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
}

// Use the default rollback strategy offer by HelmClient (revert to the previous version).
opts := GenericHelmOptions{
	RollBack: helmClient,
}

// Install a chart release.
// Note that helmclient.Options.Namespace should ideally match the namespace in chartSpec.Namespace.
if _, err := helmClient.InstallOrUpgradeChart(context.Background(), &chartSpec, &opts); err != nil {
	panic(err)
}
Output:

Example (UseLocalChartArchive)
// Use an archived chart directory.
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "/path/to/stable/etcd-operator.tar.gz",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
}

if _, err := helmClient.InstallOrUpgradeChart(context.Background(), &chartSpec, nil); err != nil {
	panic(err)
}
Output:

Example (UseURL)
// Use an archived chart directory via URL.
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "http://helm.whatever.com/repo/etcd-operator.tar.gz",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
}

if _, err := helmClient.InstallOrUpgradeChart(context.Background(), &chartSpec, nil); err != nil {
	panic(err)
}
Output:

func (*HelmClient) LintChart

func (c *HelmClient) LintChart(spec *ChartSpec) error

LintChart fetches a chart using the provided ChartSpec 'spec' and lints it's values.

Example
// Define a chart with custom values to be tested.
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "stable/etcd-operator",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
	ValuesYaml: `deployments:
  etcdOperator: true
  backupOperator: false`,
}

if err := helmClient.LintChart(&chartSpec); err != nil {
	panic(err)
}
Output:

func (*HelmClient) ListDeployedReleases

func (c *HelmClient) ListDeployedReleases() ([]*release.Release, error)

ListDeployedReleases lists all deployed releases. Namespace and other context is provided via the helmclient.Options struct when instantiating a client.

Example
// List all deployed releases.
if _, err := helmClient.ListDeployedReleases(); err != nil {
	panic(err)
}
Output:

func (*HelmClient) ListReleaseHistory

func (c *HelmClient) ListReleaseHistory(name string, max int) ([]*release.Release, error)

ListReleaseHistory lists the last 'max' number of entries in the history of the release identified by 'name'.

func (*HelmClient) ListReleasesByStateMask

func (c *HelmClient) ListReleasesByStateMask(states action.ListStates) ([]*release.Release, error)

ListReleasesByStateMask lists all releases filtered by stateMask. Namespace and other context is provided via the helmclient.Options struct when instantiating a client.

func (*HelmClient) RollbackRelease

func (c *HelmClient) RollbackRelease(spec *ChartSpec) error

RollbackRelease implicitly rolls back a release to the last revision.

Example
// Define the released chart to be installed
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "stable/etcd-operator",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
}

// Rollback to the previous version of the release.
if err := helmClient.RollbackRelease(&chartSpec); err != nil {
	return
}
Output:

func (*HelmClient) SetDebugLog

func (c *HelmClient) SetDebugLog(debugLog action.DebugLog)

SetDebugLog set's a Helm client's DebugLog to the desired 'debugLog'.

func (*HelmClient) StatusRelease

func (c *HelmClient) StatusRelease(release string) (*release.Release, error)

func (*HelmClient) TemplateChart

func (c *HelmClient) TemplateChart(spec *ChartSpec, options *HelmTemplateOptions) ([]byte, error)

TemplateChart returns a rendered version of the provided ChartSpec 'spec' by performing a "dry-run" install.

Example
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "stable/etcd-operator",
	Namespace:   "default",
	UpgradeCRDs: true,
	Wait:        true,
	ValuesYaml: `deployments:
  etcdOperator: true
  backupOperator: false`,
}

options := &HelmTemplateOptions{
	KubeVersion: &chartutil.KubeVersion{
		Version: "v1.23.10",
		Major:   "1",
		Minor:   "23",
	},
	APIVersions: []string{
		"helm.sh/v1/Test",
	},
}

_, err := helmClient.TemplateChart(&chartSpec, options)
if err != nil {
	panic(err)
}
Output:

func (*HelmClient) UninstallRelease

func (c *HelmClient) UninstallRelease(spec *ChartSpec) error

UninstallRelease uninstalls the provided release

Example
// Define the released chart to be installed.
chartSpec := ChartSpec{
	ReleaseName: "etcd-operator",
	ChartName:   "stable/etcd-operator",
	Namespace:   "default",
	Wait:        true,
	DryRun:      true,
	KeepHistory: true,
}

// Uninstall the chart release.
// Note that helmclient.Options.Namespace should ideally match the namespace in chartSpec.Namespace.
if err := helmClient.UninstallRelease(&chartSpec); err != nil {
	panic(err)
}
Output:

func (*HelmClient) UninstallReleaseByName

func (c *HelmClient) UninstallReleaseByName(name string) error

UninstallReleaseByName uninstalls a release identified by the provided 'name'.

Example
// Uninstall a release by name.
if err := helmClient.UninstallReleaseByName("etcd-operator"); err != nil {
	panic(err)
}
Output:

func (*HelmClient) UpdateChartRepos

func (c *HelmClient) UpdateChartRepos() error

UpdateChartRepos updates the list of chart repositories stored in the client's cache.

Example
// Update the list of chart repositories.
if err := helmClient.UpdateChartRepos(); err != nil {
	panic(err)
}
Output:

func (*HelmClient) UpgradeChart

func (c *HelmClient) UpgradeChart(ctx context.Context, spec *ChartSpec, opts *GenericHelmOptions) (*release.Release, error)

UpgradeChart upgrades the provided chart and returns the corresponding release. Namespace and other context is provided via the helmclient.Options struct when instantiating a client.

type HelmTemplateOptions

type HelmTemplateOptions struct {
	KubeVersion *chartutil.KubeVersion
	// APIVersions defined here will be appended to the default list helm provides
	APIVersions chartutil.VersionSet
}

type KubeConfClientOptions

type KubeConfClientOptions struct {
	*Options
	KubeContext string
	KubeConfig  []byte
}

KubeConfClientOptions defines the options used for constructing a client via kubeconfig.

type Options

type Options struct {
	Namespace        string
	RepositoryConfig string
	RepositoryCache  string
	Debug            bool
	Linting          bool
	DebugLog         action.DebugLog
	RegistryConfig   string
	Output           io.Writer
}

Options defines the options of a client. If Output is not set, os.Stdout will be used.

type RESTClientGetter

type RESTClientGetter struct {
	// contains filtered or unexported fields
}

RESTClientGetter defines the values of a helm REST client.

func NewRESTClientGetter

func NewRESTClientGetter(namespace string, kubeConfig []byte, restConfig *rest.Config, opts ...RESTClientOption) *RESTClientGetter

NewRESTClientGetter returns a RESTClientGetter using the provided 'namespace', 'kubeConfig' and 'restConfig'.

source: https://github.com/helm/helm/issues/6910#issuecomment-601277026

func (*RESTClientGetter) ToDiscoveryClient

func (c *RESTClientGetter) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)

ToDiscoveryClient returns a CachedDiscoveryInterface that can be used as a discovery client.

func (*RESTClientGetter) ToRESTConfig

func (c *RESTClientGetter) ToRESTConfig() (*rest.Config, error)

ToRESTConfig returns a REST config build from a given kubeconfig

func (*RESTClientGetter) ToRESTMapper

func (c *RESTClientGetter) ToRESTMapper() (meta.RESTMapper, error)

func (*RESTClientGetter) ToRawKubeConfigLoader

func (c *RESTClientGetter) ToRawKubeConfigLoader() clientcmd.ClientConfig

type RESTClientOption

type RESTClientOption func(*rest.Config)

RESTClientOption is a function that can be used to set the RESTClientOptions of a HelmClient.

func Burst

func Burst(v int) RESTClientOption

Maximum burst for throttle the created RESTClient will use DefaultBurst: 100.

func Timeout

func Timeout(d time.Duration) RESTClientOption

Timeout specifies the timeout for a RESTClient as a RESTClientOption. The default (if unspecified) is 32 seconds. See [1] for reference. [^1]: https://github.com/kubernetes/client-go/blob/c6bd30b9ec5f668df191bc268c6f550c37726edb/discovery/discovery_client.go#L52

type RestConfClientOptions

type RestConfClientOptions struct {
	*Options
	RestConfig *rest.Config
}

RestConfClientOptions defines the options used for constructing a client via REST config.

type RollBack

type RollBack interface {
	RollbackRelease(spec *ChartSpec) error
}

Directories

Path Synopsis
Package mockhelmclient is a generated GoMock package.
Package mockhelmclient is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL