抽出变量

稍细心观察下方代码,你就会发现其实这一段代码除了name属性其他都是重复的:

---
- hosts: static_page
  tasks:
    - name: Ensure git installed
      sudo: yes
      apt:
        name: git
        state: present

    - name: Ensure apache2 installed
      sudo: yes
      apt:
          name: apache2
          state: present

所以,需要把安装的两个工具名:git和apache2,作为参数抽出去:

---
- hosts: static_page

  vars:
    packages:
      - git
      - apache2

  tasks:
    - name: Ensure packages installed
      sudo: yes
      apt:
        name: "{{ item }}"
        state: present
      with_items: "{{ packages }}"

其中with_items和item都是ansible中的关键字,这里就会遍历vars里面的packages具体内容,就相当于Java中的: For item : with_items(packages)。 抽出变量后,记得要重新执行一次,以验证是否有语法错误。

results matching ""

    No results matching ""