ansible-playbook使用教程

• playbook 是什麼?

– playbook 是 ansible 用於配置,部署,和管理託管主機
 劇本。通過 playbook 的詳細描述,執行其中的一系列
 tasks,可以讓遠端主機達到預期的狀態。
– 也可以這麼理解,playbook 字面意思,即劇本,現實中
 由演員按照劇本表演,在 Ansible 中由計算機進行表
 演,由計算機安裝,部署應用,提供對外服務,以及組織
 計算機處理各種各樣的事情playbook是什麼

• 爲什麼要使用playbook

 – 執行一些簡單的任務,使用ad-hoc命令可以方便的解決
 問題,但是有時一個設施過於複雜,需要大量的操作時候,
 執行的 ad-hoc 命令是不適合的,這時最好使用playbook,
 就像執行 shell 命令與寫 shell 腳本一樣,也可以理解爲
 批處理任務
– 使用 playbook 你可以方便的重用編寫的代碼,可以移
 植到不同的機器上面,像函數一樣,最大化的利用代碼
 在使用 Ansible 的過程中,你也會發現,你所處理的大
 部分操作都是編寫 playbookplaybook語法基礎

• playbook 語法格式

– playbook由 YAML 語言編寫,遵循 YAML 標準
– 在同一行中,#之後的內容表示註釋
– 同一個列表中的元素應該保持相同的縮進
– playbook 由一個或多個 play 組成
– play 中 hosts,variables,roles,tasks 等對象的表示
方法都是鍵值中間以 “: ” 分隔表示
– YAML 還有一個小的怪癖. 所有的 YAML 文件開始行都
應該是 —. 這是 YAML 格式的一部分, 表明一個文件的
開始playbook語法基礎

• playbook 構成

– Target: 定義將要執行 playbook 的遠程主機組
– Variable: 定義 playbook 運行時需要使用的變量
– Tasks: 定義將要在遠程主機上執行的任務列表
– Handler: 定義 task 執行完成以後需要調用的任務playbook語法基礎

• Playbook執行結果

• 使用 ansible-playbook 運行playbook文件,得到輸
出內容爲 JSON 格式。並且由不同顏色組成,便於識
別。一般而言
• 綠色代表執行成功
*代表系統代表系統狀態發生改變
• 紅色代表執行失敗playbook語法基礎
• 第一個playbook

- hosts: all
  remote_user: root
  tasks:
# 第一行,表示開始
– hosts 行的內容是一個或多個組或主機的 patterns,以
逗號爲分隔符
– remote_user 就是賬戶名
– tasks
– 每一個 play 包含了一個 task 列表(任務列表).
– 一個 task 在其所對應的所有主機上(通過 host
pattern 匹配的所有主機)執行完畢之後,下一個 task
纔會執行.
– 有一點需要明白的是(很重要),在一個 play 之中,
所有 hosts 會獲取相同的任務指令,這是 play 的一個
目的所在,也就是將一組選出的 hosts 映射到 task,執
行相同的操作playbook語法基礎


使用方法

環境準備

6臺機器
 1 ansible  管理機器
 2 web1  託管機器
 3 web2  託管機器
 4 db1    託管機器
 5 db2    託管機器
 6 cache   託管機器

安裝

[root@ansible ~]# yum repolist
[root@ansible ~]# yum install -y ansible

安裝完成以後執行,沒有報錯,正確顯示版本即可

ansible –version
ansible 2.4.2.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/root/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

配置本地解析

[root@ansible ~]# cat /etc/hosts
192.168.1.1 ansible
192.168.1.2 web1
192.168.1.3 web2
192.168.1.4 db1
192.168.1.5 db2
192.168.1.6 cache

ansible.cfg 中 inventony 指定主機分組文件的路徑和地址,默認分組文件 hosts

hosts 的配置    //在配置文件最後添加

[root@ansible ~]# vim /etc/ansible/hosts
[web]
web1
web2

[db]
db[1:2]         //意思是db1到db2

[other]
cache

[other]
cache ansible_ssh_user="root" ansible_ssh_pass="123"
修改配置文件

[root@ansible ~]# vim /etc/ansible/ansible.cfg
61 host_key_checking = False //去掉註釋

測試結果
[root@ansible ~]# ansible cache -m ping           //測試結果 成功結果如下
cache | SUCCESS => {
    "changed": false, 
    "ping": "pong"
} 
添加子組
[root@ansible ansible]# vim /etc/ansible/hosts

[app:children]          //添加子組  app包含db和web部分
db
web

[web:vars]              
ansible_ssh_user="root"
ansible_ssh_pass="123"
• 列出要執行的主機,不執行任何操作

ansible all –list-hosts

• 批量檢測主機

ansible all -m ping

• 批量執行命令

ansible all -m command -a ‘命令’ -k

• 自定義配置文件

– 創建任意文件夾
– 在文件夾裏面創建配置文件 ansible.cfg
[defaults]
inventory = myhosts //指定文件
host_key_checking = False

- 在文件夾裏創建主機文件

[root@ansible ooxx]# vim myhosts
[app1]
web1
db1

[app2]
web2
db2

[app]
cache

給所有主機部署密鑰

創建密鑰

[root@ansible ~]# ssh-keygen -t rsa -b 2048 -N ''

給所有主機發送密鑰

[root@ansible ~]# cd /root/.ssh/
[root@ansible .ssh]# ansible all -m authorized_key -a "user=root exclusive=true manage_dir=true key='$(< /root/.ssh/id_rsa.pub)'" -k

案例

爲web1安裝Apache
並把監聽端口改爲8080
設置默認主頁 hello world
啓動服務,並設置爲開機自啓

- hosts: web1
  remote_user: root
  tasks:
        - name: install the latest version of Apache
          yum:
            name: httpd
            state: installed
        - lineinfile:
            path: /etc/httpd/conf/httpd.conf
            regexp: "^Listen"
            line: "Listen 8080"
        - shell: echo "hello world" > index.html
          args:
            chdir: /var/www/html
        - service:
            name: "httpd"
            enabled: yes
            state: started

爲cache添加用戶jj
把123456設置爲默認密碼,並使用密碼過濾器
使該用戶第一次登錄強制修改密碼

---
- hosts: cache
  remote_user: root
  vars:
    username: "jj"
  tasks:
    - user:
        name: "{{username}}"
        password: "{{'123456' |password_hash('sha512')}}"
    - shell: chage -d 0 "{{username}}"

密碼過濾器:
password_hash(‘sha512’)


爲web添加用戶zhang3
並使用忽略錯誤,避免用戶存在 停止腳本 //當返回值爲1時,停止運行
默認密碼爲123123
使該用戶第一次登錄時強制修改密碼

---
- hosts: web
  remote_user: root
  vars:
    username: "zhang3"
  tasks:
    - shell: useradd "{{username}}"
      ignore_errors: True
    - shell: echo 123123 |passwd --stdin "{{username}}"
    - shell: chage -d 0 "{{username}}"

爲cache安裝httpd
修改配置文件 把ServerName改爲localhost
修改配置文件 把監聽端口改爲8080
設置默認網頁 hello world
利用handlers 在配置Apache時自動重啓

---
  - hosts: cache
    remote_user: root
    tasks:
      - name: install the latest version of Apache
        yum:
          name: httpd
          state: installed
        notify:
          - boot start
          - restart httpd
      - lineinfile:
          path: /etc/httpd/conf/httpd.conf
          regexp: "^Listen"
          line: "Listen 8080"
        notify:
          - restart httpd
      - lineinfile:
          path: /etc/httpd/conf/httpd.conf
          regexp: "^#ServerName"
          line: "ServerName localhost"
        notify:
          - restart httpd
      - shell: echo "hello world" > index.html
        args:
          chdir: /var/www/html
    handlers:
      - name: restart httpd
        service:
          name: httpd
          state: restarted
      - name: boot start
        service:
          name: httpd
          enabled: yes

循環添加多用戶

---
  - hosts: db2
    remote_user: root
    tasks:
      - name: creater user
        user:
          name: "{{item.name}}"
          password: "{{item.pwd |password_hash('sha512')}}"
          group: "{{item.group}}"
        with_items:
          - { name:"nb",pwd:"aa",group:"a" }
          - { name:"dd",pwd:"bb",group:"b" }
          - { name:"cc",pwd:"cc",group:"c" }
          - { name:"xx",pwd:"dd",group:"d" }

把系統平均負載高於0.7的web服務器停掉

---
- hosts: web
  remote_user: root
  tasks:
    - shell: uptime | awk '{printf("%.2f",$(NF-2))}'
      register: result
    - service: name=httpd state=stopped
      when: result.stdout |float > 0.7
#追加 debug 調試信息
#   - name: Show debug info
#     debug: var=ooxx

~
“`

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章