summarylogtreecommitdiffstats
path: root/helmrelease
blob: aec46e1bf16d7955c4a73ca9c83fec4982592ca5 (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
#!/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 might not be the exact result"
      fi
      validCommand=true
      ;;
    diff)
      commands+=("diff" "upgrade" "--show-secrets" "--color" "--output=dyff")
      ;;
    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 helmrelease() {
  local subCommand="${1?You need to set the command}"
  shift
  local commands=()
  local clusterConnected=false
  local namespace
  local releaseName
  local helmReleaseYaml
  local numberOfHelmReleases
  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" -lt 1 ]]; then
    err 'There are no HelmReleases in the input'
  elif [[ "$numberOfHelmReleases" -gt 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" -ge "$numberOfHelmReleases" ]]; then
    info "index '$index' is out of range"
    <<<"$yaml" printIndices
    exit 1
  fi

  helmReleaseYaml=$(_hr_getYaml "$yaml" "$index" HelmRelease)
  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 --namespace=$(<<<"$helmReleaseYaml" | yq -r '.metadata.namespace') 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)
      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 "${@}"