Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

153.5. ansible-playbook - run an ansible playbook

定義組

# cat /etc/ansible/hosts
[www]
192.168.2.23
		

創建yml檔案

# cat test.yml
---
- hosts: www
  user: root
  tasks:
  - name: no selinux
    action: command /usr/sbin/setenforce 0

  - name: no iptables
    action: service name=iptables state=stopped

  - name: made up task just to show variables work here
    action: command /bin/echo release is $release
		

執行任務

# ansible-playbook test.yml -u root -T 1

PLAY [www] *********************

GATHERING FACTS *********************
ok: [192.168.2.23]

TASK: [no selinux] *********************
ok: [192.168.2.23]

TASK: [no iptables] *********************
ok: [192.168.2.23]

TASK: [made up task just to show variables work here] *********************
ok: [192.168.2.23]

PLAY RECAP *********************
192.168.2.23                   : ok=4    changed=2    unreachable=0    failed=0
		
# ansible-playbook update.yml --list-hosts

playbook: update.yml

  play #1 (all): host count=11
    192.168.2.10
    192.168.2.11
    192.168.2.12
    192.168.2.13
    192.168.2.15
    192.168.6.10
    192.168.6.11
    192.168.6.12
    192.168.6.13
    192.168.6.15
    192.168.2.9
		

153.5.1. 包含檔案用法

我們將下面的playbook檔案分成三個檔案,這樣更靈活。

---
- hosts: all
  remote_user: username
  sudo: yes
    
  tasks:
    - yum: name=wget state=present
      when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'
    - yum: name=gcc state=present
      when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'			
			

tasks/cenos.yml

- yum: name=wget state=present
- yum: name=gcc state=present			
			

tasks/deban.yml

- apt: pkg=wget state=present
- apt: pkg=gcc state=present			
			

playbook.yml

---
- hosts: all
  remote_user: username
  sudo: yes

  tasks:
    - include: tasks/centos.yml
      when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'
    - include: tasks/debian.yml
      when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'			
			

執行playbook

# ansible-playbook playbook.yml