ansible - variable within variable

后端 未结 2 461
执笔经年
执笔经年 2021-01-01 20:44

Ansible 1.9.2 version.

Does Ansible supports variable expansion within a variable while evaluating it.

I have a task to download 3 zip files from Artifactory

相关标签:
2条回答
  • 2021-01-01 21:16

    It does.

    You can use

    set_fact:
      variable: '{{ vars['my_' + variablename + '_variable'] }}'
    

    the only downside of this approach so far is, it won't dynamically expand variables that get the value of another variable. an example:

    roles/xxx/defaults/main.yml:

    var1: foo
    var2: '{{ var1 }}'
    

    This, unfortunately will not work when trying to use the resolved value in var2. Hence,

    - debug: msg='{{ vars["var2"] }}'
    

    will output {{ var1 }} instead of foo.

    Workaround:

    In your vars declaration, instead of using var2: {{ var1 }}, use var2: '{{ vars["var1"] }}'. That way, it will work.

    0 讨论(0)
  • 2021-01-01 21:27

    No it doesn't. But it doesn't mean that you have to expand it into 3 different tasks. What you can do is actually expand you "dictionary" to look similar to this:

    with_items:
     - {"url": "https://xxxxx", "file": "/tmp/xxxxx" }
     - {"url": "https://yyyyy", "file": "/tmp/yyyyy" }
     - {"url": "https://zzzzz", "file": "/tmp/zzzzz" }
    

    Then in your task just call different parameters: {{ item.url }} and {{ item.file }}

    Alternative Options:

    1. Write your own filter that will expand your variable according to the value {{ jmeterplugins_url | my_custom_filter(item.plugin) }}

    2. Write a custom module, that will encapsulate all of the functionality of fetching url into the file based on your inputs

    3. Write custom lookup_plugin that will iterate through your list of variables and produce correct result.

    4. Since you are using command module you can leverage bash to concatenate your url, file in the same command ( this would probably be the messiest solution )

    0 讨论(0)
提交回复
热议问题