ansible playbook基本操做

1、ansible playbook簡單使用shell

至關因而把模塊寫入到配置文件裏面vim

vim /etc/ansible/test.yml //寫入以下內容:spa

---
- hosts: 127.0.0.1
  remote_user: root
  tasks:
    - name: test_playbook
      shell: touch /tmp/test.txt

PS: 第一行是固定寫法,hosts指定對哪些主機進行操做,若是是多臺能夠用逗號分隔,也可使用主機組,如testhostcode

user參數指定使用什麼用戶登陸遠程機器對象

tasks指定一個任務,name爲對任務的描述,執行過程當中會打印出來,shell是ansible模塊名字,執行test.ymlblog

ansible-playbook test.yml

 

2、playbook設置變量ip

vim /etc/ansible/create_user.yml  //建立一個用戶:rem

---
- name: create_user
  hosts: 127.0.0.1
  user: root
  gather_facts: false
  vars:
    - user: "test"  
  tasks:
    - name: create user
      user: name="{{ user }}"

PS: name參數對該playbook作一個描述,能夠省略;gather_facts參數指定在如下任務部分執行前,是否執行setup模塊獲取主機相關信息;vars參數,指定變量,這裏指定一個user變量,值爲test,值必定要用引號引住;it

tasks裏面的user爲一個模塊,下面的name爲user模塊的一個參數,增長的用戶名字調用了上面user變量的值。

3、playbook循環class

vim /etc/ansible/while.yml  //建立文件以及修改權限:

---
- hosts: 127.0.0.1
  user: root
  gather_facts: false
  tasks:
    - name: touch files and change mode for files
      file: path=/tmp/{{ item }} state=touch mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt

PS: with_items爲循環的對象

 

4、playbook中的條件判斷

vim /etc/ansible/when.yml  //寫入以下內容:

---
- hosts: testhost
  user: root
  gather_facts: True
  tasks:
    - name: user when
      shell: touch /tmp/when.txt
      when: ansible_eno16777736.ipv4.address=="192.168.1.99"

PS: 只有知足when裏面的條件時,纔會去執行shell裏面的內容;ansible 127.0.0.1 -m setup能夠查看全部facter信息,即when裏面條件在這裏面去設置。

 

5、playbook中的handlers(tasks知足條件以後才執行)

vim /etc/ansible/handlers //寫入以下內容:

---
- name: handlers test
  hosts: 127.0.0.1
  user: root
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt
      notify: test handlers
  handlers:
    - name: test handlers
      shell: echo "1111" >> /tmp/aaa.txt

PS:只有當copy模塊真正執行後,纔會去調用下面handlers相關操做,copy與notify的順序沒有關係;若是aaa.txt與passwd內容是同樣的,就不會去執行handlers裏面的shell命令。適用於配置文件發生更改後重啓服務的操做。

相關文章
相關標籤/搜索