How to write dynamic variable in Ansible playbook

前端 未结 3 360
一整个雨季
一整个雨季 2021-01-30 10:51

Based on extra vars parameter I Need to write variable value in ansible playbook

ansible-playbook playbook.yml -e \"param1=value1 param         


        
相关标签:
3条回答
  • 2021-01-30 11:30

    I am sure there is a smarter way for doing what you want but this should work:

    - name         : Test var
      hosts        : all
      gather_facts : no
      vars:
        myvariable : false
      tasks:
        - name: param1
          set_fact:
            myvariable: "{{param1}}"
          when: param1 is defined
    
        - name: param2
          set_fact:
            myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
          when: param2 is defined
    
        - name: param3
          set_fact:
            myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
          when: param3 is defined
    
        - name: default
          set_fact:
            myvariable: "default"
          when: not myvariable
    
        - debug:
           var=myvariable
    

    Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible

    0 讨论(0)
  • 2021-01-30 11:30

    I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

       vars:
        myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
    
    0 讨论(0)
  • 2021-01-30 11:34

    my_var: the variable declared

    VAR: the variable, whose value is to be checked

    param_1, param_2: values of the variable VAR

    value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

    my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"
    
    0 讨论(0)
提交回复
热议问题