summarylogtreecommitdiffstats
path: root/helmrelease
blob: 3bdd04bfb79ccb5892587479d39671cf6f458240 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#!/usr/bin/env zsh

set -e

function err() {
  info "${@}"
  return 1
}

function info() {
  echo "${@}" >&2
}

function _hr_getYaml() {
  local yaml="$1"
  local index="$2"
  local kind="$3"

  <<<"$yaml" | yq -erys "map(select(.kind == \"$kind\"))[$index]"
}

function _hr_getNamespace() {
  local yaml="$1"

  <<<"$yaml" | yq -er '.spec.targetNamespace // .metadata.namespace // ""'
}

function _hr_getReleaseName() {
  local yaml="$1"
  local ns

  if <<<"$yaml" | yq -e '.apiVersion == "helm.fluxcd.io/v1" or .spec.targetNamespace' > /dev/null; then
    <<<"$yaml" | yq -er ".spec.releaseName // \"$(_hr_getNamespace "$yaml")-\\(.metadata.name)\""
  else
    <<<"$yaml" | yq -er '.spec.releaseName // .metadata.name'
  fi
}

function _parse_hr_subcommand() {
  local clusterConnected="${1?}"
  local subCommand="${2?}"
  local validCommand="$clusterConnected"
  local commands=()
  case "$subCommand" in
    template)
      commands+=("template")
      if [[ "$clusterConnected" == true ]]; then
        commands+=("--dry-run=server")
      else
        info "Not connected to cluster, template result might not be accurate"
      fi
      validCommand=true
      ;;
    diff)
      commands+=("diff" "upgrade" "--show-secrets" "--output=dyff" "--find-renames=1")
      ;;
    install)
      commands+=("install")
      ;;
    upgrade)
      commands+=("upgrade")
      ;;
    uninstall)
      commands+=("uninstall")
      ;;
    *)
      err "command '$subCommand' is not implemented"
      ;;
  esac
  if [[ "$validCommand" == false ]]; then
    err "command '$subCommand' is not valid when not connected to a cluster"
  fi
  echo "${commands[@]}"
}

function _hr_git() {
  local clusterConnected="${1?}"
  local subCommand="${2?}"
  local commands=()
  local clonePath="$(mktemp -d)"
  trap "rm -rf '$clonePath'" EXIT
  local gitUrl="$3"
  local gitRef="$4"
  local gitPath="$5"
  local namespace="$6"
  local releaseName="$7"
  local values="$8"

  commands=($(_parse_hr_subcommand "$clusterConnected" "$subCommand"))

  (
    git clone -q "$gitUrl" "$clonePath"
    cd "$clonePath"
    git checkout -q "$gitRef"
  ) > /dev/null

  helm dependency update "$clonePath/$gitPath" > /dev/null
  helm "${commands[@]}" ${namespace:+--namespace=$namespace} $releaseName "$clonePath/$gitPath" --values <(<<< "$values") ${@:9}
}

function printIndices() {
  yq -ers 'map(select(.kind == "HelmRelease")) | . as $hrs | keys[] | "\(.): \($hrs[.] | "\(.metadata.namespace)/\(.metadata.name)")"' >&2
}

function _show_help() {
  local subCommand="$1"
  if [[ -z "$subCommand" ]]; then
    cat >&2 <<'EOF'
Usage: helmrelease <command> [options]
       hr [yaml] [source] [options]

Commands:
  template      Template a HelmRelease (default)
  diff          Diff an upgrade
  install       Install a HelmRelease
  upgrade       Upgrade a HelmRelease
  uninstall     Uninstall a HelmRelease

Input:
  <yaml>        Path to HelmRelease YAML file (or stdin with -)
  <source>      Optional chart source: directory, URL, or OCI ref
  -N            Index of HelmRelease in multi-document YAML
  --            Separator before helm options
EOF
  elif [[ "$subCommand" == "template" ]]; then
    cat >&2 <<'EOF'
Usage: hr [yaml] [source] [-N] [--] [helm options]

Template a HelmRelease from flux YAML.

When connected to a cluster, uses --dry-run=server for accurate results.
Pass -- to forward options directly to helm template.

EOF
    helm template --help 2>&1 | sed 's/^/  /' >&2
  elif [[ "$subCommand" == "diff" ]]; then
    cat >&2 <<'EOF'
Usage: hrDiff [yaml] [-N] [--] [helm options]

Diff the changes that an upgrade would apply, using helm-diff.

Pass -- to forward options directly to helm.

EOF
    helm diff upgrade --help 2>&1 | sed 's/^/  /' >&2
  elif [[ "$subCommand" == "install" ]]; then
    cat >&2 <<'EOF'
Usage: hrInstall yaml [source] [-N] [--] [helm options]

Install a HelmRelease from flux YAML.

Only one HelmRelease can be installed at a time. Use -N to select
which HelmRelease if the input contains multiple.

Pass -- to forward options directly to helm.

EOF
    helm install --help 2>&1 | sed 's/^/  /' >&2
  elif [[ "$subCommand" == "upgrade" ]]; then
    cat >&2 <<'EOF'
Usage: hrUpgrade [yaml] [source] [-N] [--] [helm options]

Upgrade a HelmRelease from flux YAML.

Pass -- to forward options directly to helm.

EOF
    helm upgrade --help 2>&1 | sed 's/^/  /' >&2
  elif [[ "$subCommand" == "uninstall" ]]; then
    cat >&2 <<'EOF'
Usage: hrUninstall [yaml] [-N] [--] [helm options]

Uninstall a HelmRelease from flux YAML.

Pass -- to forward options directly to helm.

EOF
    helm uninstall --help 2>&1 | sed 's/^/  /' >&2
  else
    echo "Unknown command '$subCommand'" >&2
    return 1
  fi
}

function helmrelease() {
  local subCommand="${1?You need to set the command}"
  if [[ "$subCommand" == "--help" || "$subCommand" == "-h" ]]; then
    _show_help "${2:-}"
    exit 0
  fi
  shift
  local commands=()
  local clusterConnected=false
  local releaseName
  local helmReleaseYaml
  local helmReleaseNamespace
  local namespace
  local numberOfHelmReleases
  local numberOfValuesFromItems
  local values
  local index
  local sourceParameter
  local yaml
  local remoteKubeconfig
  local REMOTE_KUBECONFIG
  if kubectl version &> /dev/null; then
    clusterConnected=true
  fi
  commands=($(_parse_hr_subcommand "$clusterConnected" "$subCommand"))

  while [[ "$#" != 0 ]]; do
    case "$1" in
      -)
        yaml=$(cat)
        shift
        ;;
      -[0-9]*)
        index="${1/-/}"
        shift
        ;;
      --)
        shift
        break
        ;;
      *)
        if [[ -f "$1" ]]; then
          if [[ -n "$yaml" ]]; then
            sourceParameter="$1"
          else
            yaml=$(cat "$1")
          fi
        elif [[ -d "$1" ]]; then
          sourceParameter="$1"
        elif [[ "$1" =~ ^https://* ]] || [[ "$1" =~ ^oci://* ]]; then
          sourceParameter="$1"
        else
          err "parameter '$1' is not supported"
        fi
        shift
        ;;
    esac
  done

  if [[ -z "$yaml" ]]; then
    yaml=$(cat)
  fi

  numberOfHelmReleases=$(<<< "$yaml" | yq -ers 'map(select(.kind == "HelmRelease")) | length')
  if (( numberOfHelmReleases < 1 )); then
    err 'There are no HelmReleases in the input'
  elif (( numberOfHelmReleases > 1 )) && [[ -z "$index" ]]; then
    if [[ "$subCommand" == "install" ]]; then
      info 'You can only install 1 HelmReleases at the same time, but you can do `-$index`;'
      <<<"$yaml" printIndices
      return 1
    else
      <<<"$yaml" | yq -erys '.[] | select(.kind != "HelmRelease") | select(.)' \
        | if [[ "$subCommand" = "template" ]]; then
        cat -
      elif [[ "$subCommand" = "diff" ]]; then
        kubectl diff -f - || true
      fi
      for index in {0..$(( numberOfHelmReleases - 1 ))}; do
        if [[ "$subCommand" = "template" ]]; then
          echo ---
        fi
        <<<"$yaml" | yq -erys '(map(select(.kind == "HelmRelease"))['"$index"']),(.[] | select(.kind | IN(["GitRepository", "HelmRepository"][])))' | helmrelease "$subCommand" - -- "${@}"
      done
    fi
  else
    index="${index:-0}"
  fi
  if (( index >= numberOfHelmReleases )); then
    info "index '$index' is out of range"
    <<<"$yaml" printIndices
    exit 1
  fi

  helmReleaseYaml=$(_hr_getYaml "$yaml" "$index" HelmRelease)
  helmReleaseNamespace="$(<<< "$helmReleaseYaml" | yq -r '.metadata.namespace')"
  namespace=$(_hr_getNamespace "$helmReleaseYaml")
  remoteKubeconfig="$(<<< "$helmReleaseYaml" | yq -r '.spec.kubeConfig.secretRef.name // empty')"
  if [[ ! -z "$remoteKubeconfig" ]] && ( [[ "$subCommand" != template ]] || [[ "$clusterConnected" == true ]] ); then
    REMOTE_KUBECONFIG="$(mktemp)"
    trap "rm -f \"$REMOTE_KUBECONFIG\"" EXIT
    kubectl ${helmReleaseNamespace:+--namespace=$helmReleaseNamespace} get secret $remoteKubeconfig -o jsonpath='{.data.value}' | base64 -d > "$REMOTE_KUBECONFIG"
  fi
  releaseName=$(_hr_getReleaseName "$helmReleaseYaml")
  case "$subCommand" in
    uninstall)
      KUBECONFIG="${REMOTE_KUBECONFIG:-$KUBECONFIG}" helm "${commands[@]}" ${namespace:+--namespace=$namespace} $releaseName "$@"
      ;;
    *)
      values=$(<<< "$helmReleaseYaml" | yq -y -r .spec.values)
      numberOfValuesFromItems=$(<<< "$helmReleaseYaml" | yq -r '.spec.valuesFrom | length')
      if (( numberOfValuesFromItems > 0 )); then
        local valuesFromItem
        local valuesFromItemKind
        local valuesFromItemName
        local valuesFromItemTargetPath
        local valuesFromItemValuesKey
        local valuesFromYaml
        local valuesFromItemResource
        for index in {0..$(( numberOfValuesFromItems - 1 ))}; do
          valuesFromItem="$(<<< "$helmReleaseYaml" | yq -er ".spec.valuesFrom[$index]")"
          valuesFromItemKind="$(<<< "$valuesFromItem" | yq -er .kind)"
          valuesFromItemName="$(<<< "$valuesFromItem" | yq -er .name)"
          valuesFromItemValuesKey="$(<<< "$valuesFromItem" | yq -er '.valuesKey // "values.yaml"')"
          valuesFromItemTargetPath="$(<<< "$valuesFromItem" | yq -er '.targetPath // ""')"
          if valuesFromYaml=$(_hr_getYaml "$yaml" "" "$valuesFromItemKind") || ! valuesFromItemResource=$(<<< "$valuesFromYaml" | yq -erys "map(select( (.metadata.namespace == \"$helmReleaseNamespace\") and (.metadata.name == \"$valuesFromItemName\") ))[0] // empty"); then
            if [[ "$clusterConnected" == true ]]; then
              if ! valuesFromItemResource=$(kubectl --namespace=$helmReleaseNamespace get $valuesFromItemKind $valuesFromItemName -o yaml | yq -er --arg valuesFromItemValuesKey "$valuesFromItemValuesKey" '.data[$valuesFromItemValuesKey]'); then
                info "ValuesFrom resource '$helmReleaseNamespace/$valuesFromItemKind/$valuesFromItemName' not found in cluster nor in input or doesn't contain '$valuesFromItemValuesKey', template result might not be accurate"
              fi
            else
              info "Cannot get source resource '$helmReleaseNamespace/$valuesFromItemKind/$valuesFromItemName' from cluster when not connected"
            fi
          fi
          if [[ ! -z "$valuesFromItemResource" ]]; then
            if [[ "$valuesFromItemKind" == Secret ]]; then
              valuesFromItemResource="$(<<< "$valuesFromItemResource" | base64 -d)"
            fi
            if [[ "$valuesFromItemTargetPath" == "" ]]; then
              values="$(<<< "$values" | yq -er --argjson valuesFromItemResource "$(yq -e . <<<"$valuesFromItemResource")" '. * $valuesFromItemResource')"
            else
              values="$(<<< "$values" | yq -er --arg valuesFromItemResource "$valuesFromItemResource" --arg valuesFromItemTargetPath "$valuesFromItemTargetPath" 'setpath($valuesFromItemTargetPath | split("."); $valuesFromItemResource)')"
            fi
          fi
        done
      fi
      if [[ -e "$sourceParameter" ]]; then
        KUBECONFIG="${REMOTE_KUBECONFIG:-$KUBECONFIG}" helm "${commands[@]}" ${namespace:+--namespace=$namespace} $releaseName "$sourceParameter" --values <(<<< "$values") ${@}
      elif <<< "$helmReleaseYaml" | yq -e '.apiVersion == "helm.fluxcd.io/v1"' > /dev/null; then
        if <<< "$helmReleaseYaml" | yq -e .spec.chart.git > /dev/null; then
          local gitPath
          local gitUrl
          local gitRef
          gitPath="$(<<< "$helmReleaseYaml" | yq -er '.spec.chart.path // "."')"
          gitUrl="$(<<< "$helmReleaseYaml" | yq -er .spec.chart.git)"
          gitRef="$(<<< "$helmReleaseYaml" | yq -er '.spec.chart.ref // "master"')"
          KUBECONFIG="${REMOTE_KUBECONFIG:-$KUBECONFIG}" _hr_git "$clusterConnected" "$subCommand" "$gitUrl" "$gitRef" "$gitPath" "$namespace" "$releaseName" "$values" "$@"
        else
          KUBECONFIG="${REMOTE_KUBECONFIG:-$KUBECONFIG}" helm "${commands[@]}" ${namespace:+--namespace=$namespace} --repo $(<<< "$helmReleaseYaml" | yq -er .spec.chart.repository) $releaseName $(<<< "$helmReleaseYaml" | yq -er .spec.chart.name) --version $(<<< "$helmReleaseYaml" | yq -er .spec.chart.version) --values <(<<< "$values") "$@"
        fi
      else
        local sourceNamespace
        local sourceName
        local sourceKind
        local sourceResource
        local chartName
        local helmRepositoryUrl
        sourceNamespace=$(<<< "$helmReleaseYaml" | yq -er ".spec.chart.spec.sourceRef.namespace // \"$namespace\"")
        sourceName=$(<<< "$helmReleaseYaml" | yq -er .spec.chart.spec.sourceRef.name)
        sourceKind=$(<<< "$helmReleaseYaml" | yq -er .spec.chart.spec.sourceRef.kind)
        if [[ -z "$sourceParameter" ]]; then
          local sourcesYaml
          if ! { sourcesYaml=$(_hr_getYaml "$yaml" "" "$sourceKind") && sourceResource=$(<<< "$sourcesYaml" | yq -erys "map(select( (.metadata.namespace == \"$sourceNamespace\") and (.metadata.name == \"$sourceName\") ))[0] // empty") }; then
            if [[ "$clusterConnected" == true ]]; then
              if ! sourceResource=$(kubectl ${sourceNamespace:+--namespace=$sourceNamespace} get $sourceKind $sourceName -o yaml); then
                info "Source resource '$sourceNamespace/$sourceKind/$sourceName' not found in cluster nor in input"
              fi
            else
              info "Cannot get source resource '$sourceNamespace/$sourceKind/$sourceName' from cluster when not connected"
            fi
            if [[ -z "$sourceResource" ]]; then
              helmRepositoryUrl="oci://ghcr.io/teutonet/teutonet-helm-charts"
              vared -p "Please specify Helm Repository URL: " helmRepositoryUrl > /dev/null
              sourceKind=HelmRepository
              sourceResource=$'spec:\n  url: '"$helmRepositoryUrl"
            fi
          fi
        else
          sourceResource=$'spec:\n  url: '"$sourceParameter"
        fi
        chartName="$(<<< "$helmReleaseYaml" | yq -er .spec.chart.spec.chart)"
        case "$sourceKind" in
          GitRepository)
            local gitUrl
            local gitRef
            gitUrl="$(<<< "$sourceResource" | yq -er .spec.url)"
            gitRef="$(<<< "$sourceResource" | yq -er '.spec.ref | if .branch then .branch elif .tag then .tag elif .semver then .semver elif .commit then .commit else "master" end')"
            KUBECONFIG="${REMOTE_KUBECONFIG:-$KUBECONFIG}" _hr_git "$clusterConnected" "$subCommand" "$gitUrl" "$gitRef" "$chartName" "$namespace" "$releaseName" "$values" "$@"
            ;;
          HelmRepository)
            local chartVersion
            helmRepositoryUrl="$(<<< "$sourceResource" | yq -er .spec.url)"
            chartVersion="$(<<< "$helmReleaseYaml" | yq -er '.spec.chart.spec.version // "x.x.x"')"
            commands+=( $releaseName )
            case "$helmRepositoryUrl" in
              https://*)
                commands+=( --repo "$helmRepositoryUrl" "$chartName" )
                ;;
              oci://*)
                commands+=( "$helmRepositoryUrl/$chartName" )
                ;;
              *)
                err "'$helmRepositoryUrl' is not supported"
                ;;
            esac
            KUBECONFIG="${REMOTE_KUBECONFIG:-$KUBECONFIG}" helm "${commands[@]}" ${namespace:+--namespace=$namespace} --version "$chartVersion" --values <(<<< "$values") "$@"
            ;;
          *)
            err "'$sourceKind' is not implemented"
            ;;
        esac
      fi
      ;;
  esac
}

if [[ "$XTRACE" == true ]]; then
  set -x
fi

exec helmrelease "${@}"