goss-org / goss

Quick and Easy server testing/validation
https://goss.rocks
Apache License 2.0
5.6k stars 473 forks source link

.Env.variable doesn't work in a range #965

Closed hinricht closed 2 months ago

hinricht commented 3 months ago

Describe the bug

I can use {{.Env.foo}} fine when using it in a simple command section, but when I use it in a Template range it won't render.

How To Reproduce

This works:

$ cat vars.yaml 
foo:
  - bar
  - baz

$ cat goss.yaml 
command:
  test:
    exec: 'echo {{.Env.TEST}}'

  {{range .Vars.foo}}
  {{.}}:
    exec: 'echo {{.}}'
    # stdout:
    #   - 192.168.3.102
    stderr: []
    exit-status: 0
  {{end}}

$ TEST=test goss --vars vars.yaml render
command:
  bar:
    exec: echo bar
    exit-status: 0
    stdout: []
    stderr: []
    timeout: 0
  baz:
    exec: echo baz
    exit-status: 0
    stdout: []
    stderr: []
    timeout: 0
  test:
    exec: echo test
    exit-status: null
    stdout: []
    stderr: []
    timeout: 0

But when I add {{.Env.TEST}}' inside the {{range .Vars.foo}} it won't render:

$ cat goss.yaml 
command:
  test:
    exec: 'echo {{.Env.TEST}}'

  {{range .Vars.foo}}
  {{.}}:
    exec: 'echo {{.}} {{.Env.TEST}}'
    stderr: []
    exit-status: 0
  {{end}}

$ TEST=test goss --vars vars.yaml render
2024/08/06 16:00:24 template: test:7:28: executing "test" at <.Env.TEST>: can't evaluate field Env in type interface {}

Expected Behavior

Env variables should render find, no matter if they are inside a range.

Actual Behavior

$ TEST=test goss --vars vars.yaml render
2024/08/06 16:05:41 template: test:7:28: executing "test" at <.Env.TEST>: can't evaluate field Env in type interface {}

Environment:

hinricht commented 2 months ago

Ah, found the solution: https://stackoverflow.com/a/72347561

In the range block . refers to the current value in the execution time. Instead of . you can use $ to access to the root data object in the range block instead of declaring top level variables.

So inside the range block I need to specify {{$.Env.TEST}} instead of {{.Env.TEST}} in order to make it work.