序列

之前想要產生一堆使用者,例如 user01, user02, user03… ,那時候在想用 with_items 或 loop 要怎麼做?好像沒有好的方法,找了好一會,才在 Ansible 文件裡找到,原來 Ansible 已經有內建序列可以這樣用了。

序列的用法可以參考這裡:ansible.builtin.sequence lookup – generate a list based on a number sequence

只要在 task 加上 with_sequence ,就可以了。

以文件裡的例子來說明,

- name: create some test users
  ansible.builtin.user:
    name: "{{ item }}"
    state: present
    groups: "evens"
  with_sequence: start=0 end=32 format=testuser%02x

這主要是使用 user 模組來建立測試使用者

  • with_sequence 表示要使用 sequence,後面的 start, end, format 是參數
  • start 表示從 0 開始
  • end 表示到 32 就結束
  • format 表示要格式化為 user00, user01, user02 這樣子,所以 item 內容就是 user00, user01, user02…

如果是要間隔 2,類似 2, 4, 6, 8 的話,可以用 stride,例如

- debug:
    msg: "{{ item }}"
  with_sequence: start=0 end=10 stride=2 format="hello %02d"

最後要說的參數是 count,這個參數不能跟 end 一起用,count 主要是指要有 10 個,例如

- debug:
    msg: "{{ item }}"
  with_sequence: start=0 count=10 stride=2 format="hello %02d"

這樣會出現 “hello 00”, “hello 02”, “hello 04”, “hello 06”, … “hello 18”,共十次。

使用 with_sequence,之後就不用挖空心思去想怎麼產生出連續的數列了。