如何使用循环加速本地操作(with_items或with_sequence)

时间:2017-06-29 13:32:17

标签: ansible

鉴于以下剧本:

---
- name: test local_action with_items
  hosts: localhost
  gather_facts: false
  tasks:
    - name: "add something to a file"
      shell: echo '{{item}}' >> foo.txt
      with_items:
      - "aaaaa"
      - "aaaaa"
# using 40 items

---
- name: test local_action with_items
  hosts: localhost
  gather_facts: false
  tasks:
    - name: "add something to a file"
      shell: echo '{{item}}' >> foo.txt
      with_sequence: count=40

后一部剧本运行5秒钟。

Using a bash loop is obviously much(1000次)更快,需要5毫秒:

time for i in $(seq 1 40); do echo $i >> foo.txt;     done

现在很明显Ansible有一些开销,但有没有可能加快速度呢?

1 个答案:

答案 0 :(得分:1)

使用shell模块代替raw模块。它将与bash循环一样快。

---
- name: test local_action with_items
  hosts: localhost
  gather_facts: false
  tasks:
    - name: "add something to a file"
      raw: echo '{{item}}' >> foo.txt
      with_sequence: count=40
...

无论如何,如果你想要表现,可以用C语言编写你的代码。