0

在 Ansible 中添加变量列表时,如何实现相似值的跨度?例如“000-100” - 在 Ansible 主机文件中,这可以通过像这样列出“hostname-[a:v].com”来完成。这个过程在变量列表中是否相似?

我的用例是一次性在 oVirt 中配置许多 VM,而无需逐行列出。

---
- name: Create VM based on template
  hosts: ovirt-engine
  become: yes
  become_method: sudo

  vars:
  - temp: '{{temp_fedora25}}'
  - iname:
      - db-aa
      - db-ab
      - db-ac

  tasks:

    - name: Giving Birth to lil Baby VM's
      ovirt:
          user: '{{ovirt_usr}}'
          password: '{{ovirt_pass}}'
          url: '{{engine_url}}'
          instance_name: "{{item}}"
          instance_nic: ovirtmgmt
          resource_type: template
          image: '{{temp}}'
          zone: superblade-a
          disk_alloc: preallocated
      with_items: "{{iname}}"
4

2 回答 2

0

您可以使用序列查找:

- name: numeric
  debug:
    msg: "{{ item }}"
  with_sequence: start=1 count=10 format=server-%0d


- name: characters from small 'a'
  debug:
    msg: "{{ item }}"
  with_sequence: start=0x61 count=10 format=server-%c

- name: save for future use
  set_fact:
    my_seq: "{{ lookup('sequence','start={} count={} format={}{}'.format(beg,cnt,pref,fmt),wantlist=True) }}"
  vars:
    beg: 1
    cnt: 10
    pref: host-
    fmt: '%0d'

您可以在 vars 部分跳过set_fact和定义my_seq,但如果您使用my_seq太多,列表生成将每次在内部完成。使用set_fact列表生成一次。

于 2017-06-29T19:59:36.197 回答
0

关于康斯坦丁的正确答案,我根据我的情况添加了完整的解决方案......

我的目标是能够重用序列值作为注册变量,以便将实例名称传递给主机名。到目前为止这有效,但我确定它可以通过嵌套变量来简化?

---
- name: Create VM based on template
  hosts: ovirt-engine
  become: yes
  become_method: sudo

  vars:
  - temp: '{{temp_fedora25}}'
  - host_pre: db
  - host_seq: a%c
  - host_cnt: 3
  - host_srt: 0x61

  tasks:

    - name: Giving Birth to lil Baby VM's
      ovirt:
         user: '{{ovirt_usr}}'
         password: '{{ovirt_pass}}'
         url: '{{engine_url}}'
         instance_name: "{{item}}"
         instance_nic: ovirtmgmt
         resource_type: template
         image: '{{temp}}'
         zone: superblade-a
         disk_alloc: preallocated
      with_sequence: start="{{host_srt}}" count="{{host_cnt}}" format="{{host_pre}}-{{host_seq}}"
于 2017-06-30T09:33:41.897 回答