How to use .Values in other variable loops

9/15/2018

Below is my case:

{{- $v := (.Files.Get "values-productpage.yaml") | fromYaml }}.   
   spec:
     {{- range $key, $value := $v.containers }}
     containers:
     - name: {{ $value.name }}
       image: {{.Values.productpage_image}}:latest

Here when reaching .Values.productpage_image, it reports: can't evaluate field productpage_image in type interface {}.

Is there any usage error here? Why can I not use .Values.xxx in this loop? If I move the .Values to the first line, there is no error.

-- yangyang
kubernetes-helm

3 Answers

10/16/2019

You can simply use $ to get to the root scope

Without defining what $root is, you can references .Values as $.Values from within a loop, or any other scope.

Source: https://github.com/kubeapps/kubeapps/pull/1057

-- GeorgeLambadas
Source: StackOverflow

9/18/2018

It's because range changes a scope (see detailed description here https://github.com/helm/helm/blob/master/docs/chart_template_guide/control_structures.md#looping-with-the-range-action).

You can assign .Values.productpage_image to the variable outside the range and use inside.

-- abinet
Source: StackOverflow

10/15/2018

As @abinet explained properly about the reason, I'll share my solution for that( which helped me a lot, and I hope that will save you time):

First, I saved the scope:
{{- $root := . -}}

and after that , I called the .Value inside the loop context like this:
{{ $root.Values.data }}

so basically , you code should be look like:

{{- $root := . -}}

{{- $v := (.Files.Get "values-productpage.yaml") | fromYaml }}.   
  spec:
   {{- range $key, $value := $v.containers }}
   containers:
   - name: {{ $value.name }}
     image: {{$root.Values.productpage_image}}:latest
-- nisanarz
Source: StackOverflow