如何在Ansible playbook中编写动态变量

时间:2014-04-24 08:55:07

标签: jinja2 ansible ansible-playbook

基于extra vars参数我需要在ansible playbook

中编写变量值
ansible-playbook playbook.yml -e "param1=value1 param2=value2 param3=value3"

如果仅 param1 传递

myvariable: 'param1'  

如果只有 param1,param2 传递

myvariable: 'param1,param2' 

如果 param1,param2,param3 被传递,那么变量值将

myvariable: 'param1,param2,param3' 

当我尝试通过模板动态创建变量时,我的playbook总是采用先前的变量值。但在dest=roles/myrole/vars/main.yml内写出正确的值。

我在这里试一试

- hosts: local
  user: roop
  gather_facts: yes
  connection: local

  tasks: 

  - template: src=roles/myrole/templates/myvar.j2 dest=roles/myrole/vars/main.yml

  - debug: var=myvariable

  roles:
        - { role: myrole }

因此,在 myrole 目录中,我创建了templatevars

- roles
  - myrole
    - vars/main.yml
    - templates/myvar.j2 

templates / myvar.j2

{% if param1 is defined and param2 is defined and param3 is defined %}
  myvariable: 'param1,param2,param3'
{% elif param1 is defined and param2 is defined %}
  myvariable: 'param1,param2'
{% elif param1 is defined %}
  myvariable: 'param1'
{% else %}
  myvariable: 'default-param'
{% endif %} 

据我所知,如果只有两个条件,那么我可以使用下面的inline expression

来做到这一点
{{ 'param1,param2' if param1 is defined and param2 is defined else 'default-param' }}

<do something> if <something is true> else <do something else>

if - elif - else中是否可能inline expression如上所述。或者在ansible playbook中动态分配值的任何其他方式?

3 个答案:

答案 0 :(得分:39)

我确信有一种更聪明的方法可以做你想做的事情,但这应该有效:

- 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

希望有所帮助。我不确定你是否可以动态构造变量并在迭代器中执行此操作。但是你也可以编写一个小的python代码或任何其他语言并将其插入ansible

答案 1 :(得分:19)

my_var:声明的变量

VAR:要检查其值的变量

param_1,param_2:变量VAR的值

value_1,value_2,value_3:根据my_var的值分配给my_var的值

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

答案 2 :(得分:15)

我首先建议你退后一步,看看组织你的戏剧不需要这么复杂,但如果你真的这么做,请使用以下内容:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"