saltstack / salt

Software to automate the management and configuration of any infrastructure or application at scale. Get access to the Salt software package repository here:
https://repo.saltproject.io/
Apache License 2.0
13.98k stars 5.47k forks source link

Construct variable from another variables #66556

Open AGirin opened 1 month ago

AGirin commented 1 month ago
{% load_yaml as yaml %}

test:
  dev: 'xxxxx'
test_2:
  dev: 'yyyyy'

{% endload %}

{% set proj = slspath.split('/')[0] %}
{% set env = slspath.split('/')[1] %}
{% set service = slspath.split('/')[2] %}

{% set a = yaml ~ '.' ~ proj ~ '.' ~ env %}

test:
  cmd.run:
    - name: echo {{ a }}

Output:

test:
  cmd.run:
    - name: echo {'test': {'dev': 'xxxxx'}, 'test_2': {'dev': 'yyyyy'}}.test.dev    <======================

Is it possible to access test yaml from dynamically created variable?

As I really want to return yaml.test.dev value no entire yaml + test.dev...

bdrx312 commented 1 month ago

yaml in your example is a dictionary/hashmap. You just access the value in a dictionary like you would any value in jinja. So your code should be

{%- set a = yaml[proj][env] %}

All of your example is just plain jinja (https://jinja.palletsprojects.com/en/3.0.x/templates/#variables) and really has nothing to with salt specifically except that it uses jinja for the default renderer.

AGirin commented 1 month ago

Thanks! It works.