动态构建变量

时间:2018-08-14 17:47:45

标签: ansible

我正在尝试使用ovirt-ansible(https://github.com/oVirt/ovirt-ansible),但是它的var有点冗长,我想从一些更简单的变量中生成它们,以减少人为错误的机会。

例如,类似这样的东西显然不起作用:

vars:
  cluster_name: test
  domain_suffix: blah
  subnet_mgmt: 1.2.3

  myhosts:
    - id: 001
      ip_suffix: 101

  hosts:
   {% for host in myhosts %}
   - name: "{{ cluster_name }}-{{ host[id] }}.{{ domain_suffix }}"
     address: "{{ subnet_mgmt  }}.{{ host[ip_suffix] }}"
   {% endfor %}

有人能建议最好的方法做到这一点,而不必简​​单地分叉他们的仓库并重写剧本以我自己的格式读取变量吗?我希望避免维护前叉。

1 个答案:

答案 0 :(得分:0)

这是您要寻找的code吗?

> cat dynamic_var.yml

- hosts: localhost                                                                           
  vars:                                                                                      
    cluster_name: test                                                                       
    domain_suffix: blah                                                                      
    subnet_mgmt: 1.2.3                                                                       
    myhosts:                                                                                 
      - { id: "001", ip_suffix: "101" }                                                      
  tasks:                                                                                     
    - set_fact:                                                                              
        hosts:                                                                               
          - name: "{{ cluster_name }}-{{ item.id }}.{{ domain_suffix }}"                     
            address: "{{ subnet_mgmt  }}.{{ item.ip_suffix }}"                               
      loop: "{{ myhosts }}"                                                                  
    - debug:                                                                                 
        msg: "{{ hosts }}"                                                                   

> ansible-playbook dynamic_var.ym

(摘要)

TASK [debug] 
        "address": "1.2.3.101", 
        "name": "test-001.blah"