ansible條件,循環,roles用法

roles做爲ansible重要的企業實戰解決方案。nginx

批量建立文件,使用循環

---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: create some files
      file: name=/data/{{ item }} state=touch
      with_items:
        - file1
        - file2
      when: ansible_distribution_major_version == "7"

迭代嵌套自變量,使用循環

---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: create some groups
      group: name={{item}}
      when: ansible_distribution_major_version == "7" 
      with_items:
        - g1
        - g2
        - g3

    - name: create some users
      user: name={{item.name}} group={{item.group}}
      when: ansible_distribution_major_version == "7"
      with_items:
        - { name: 'user1',group: 'g1'}
        - { name: 'user1',group: 'g2'}
        - { name: 'user1',group: 'g3'}

使用for循環

---
- hosts websrvs
  remote_user: root
  vars:
    #定義一個列表類型的變量,名稱爲ports
    ports: 
      - 81
      - 82
      - 83

  tasks:
    - name: copy conf file
      template: src=for1.conf.j2 dest=/data/for1.conf

touch for1.conf.j2
循環建立配置,而且能夠使用if條件判斷web

{% for port in ports %}
server{
    listem {{ port }}
}
{% endfor %}

roles的使用

  • 將playbook中使用的功能拆開,分們別類,在playbook中引入便可,實現了功能複用,適合大型項目。
  • 在一個playbook中調用多個roles
- hosts: websrvs
  remote_user: root
  roles:
    - role: httpd
    - role: nginx
  • 在一個roles的task中調用其餘roles中的tasks.

main.ymlcode

- include: temp.yml
- include: roles/htpd/tasks/copyfile.yml
  • 在一個playbook,給每一個roles打上tag
- hosts: websrvs
  remote_user: root
  roles:
    - { role: httpd, tasg: ['web',httpd'] }
    - { role: nginx, tags: ['web','nginx'],when: ansible_distribution_major_version == "7" }
  • 調用帶有tag的任務
ansible-playbook -t web some_role.yml
相關文章
相關標籤/搜索