1. 程式人生 > 其它 >Ansible 的指令碼 --- playbook 劇本(LNMP構建)

Ansible 的指令碼 --- playbook 劇本(LNMP構建)

playbooks劇本

playbooks 組成

(1)Tasks:任務,即通過 task 呼叫 ansible 的模板將多個操作組織在一個 playbook 中執行

(2)Variables:變數

(3)Templates:模板

(4)Handlers:處理器,當changed狀態條件滿足時,(notify)觸發執行的操作

(5)Roles:角色

示例:
vim test1.yaml
---                                                              #yaml檔案以---開頭,以表明這是一個yaml檔案,可省略
- name: first play                                               #定義一個play的名稱,可省略
 gather_facts: false                                             #設定不進行facts資訊收集,這可以加快執行速度,可省略,預設為true
 hosts: webservers                                               #指定要執行任務的被管理主機組,如多個主機組用冒號分隔
 remote_user: root                                               #指定被管理主機上執行任務的使用者
 tasks:                                                          #定義任務列表,任務列表中的各任務按次序逐個在hosts中指定的主機上執行
   - name: test connection                                       #自定義任務名稱
    ping:                                                        #使用 module: [options] 格式來定義一個任務
   - name: disable selinux
    command: '/sbin/setenforce 0'                                #command模組和shell模組無需使用key=value格式,直接用單引號加上命令即可
    ignore_errors: True                                          #如執行命令的返回值不為0,就會報錯,tasks停止,可使用ignore_errors忽略失敗的任務
   - name: disable firewalld
    service: name=firewalld state=stopped                        #使用 module: options 格式來定義任務,option使用key=value格式
   - name: install httpd
    yum: name=httpd state=latest                                 #state這裡指定的是最新的版本(latest)
   - name: install configuration file for httpd
    copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf    #這裡需要一個事先準備好的/opt/httpd.conf檔案
    notify: "restart httpd"                                      #如以上操作後為changed的狀態時,會通過notify指定的名稱觸發對應名稱的handlers操作
   - name: start httpd service
    service: enabled=true name=httpd state=started
  handlers:                                                      #handlers中定義的就是觸發任務,此處handlers中的任務使用的是service模組
   - name: restart httpd                                         #notify和handlers中任務的名稱必須一致
    service: name=httpd state=restarted
##Ansible在執行完某個任務之後並不會立即去執行對應的handler,而是在當前play中所有普通任務都執行完後再去執行handler,這樣的好處是可以多次觸發notify,但最後只執行一次對應的handler,從而避免多次重啟。

執行playbook

ansible-playbook test1.yaml

補充引數:

-k(-ask-pass):用來互動輸入ssh密碼

-K(-ask-become-pass):用來互動輸入sudo密碼

-u:指定使用者

ansible-playbook test1.yaml --syntax-check                     #檢查yaml檔案的語法是否正確,只是部分語法並不能精準檢查

ansible-playbook test1.yaml --list-task                        #檢查tasks任務

ansible-playbook test1.yaml --list-hosts                       #檢查生效的主機

ansible-playbook test1.yaml --start-at-task='install httpd'    #指定從某個task開始執行

定義、引用變數

- name: second play
  hosts: dbservers
  remote_user: root
  vars:                                                              #定義變數
   - groupname: mysql                                                #格式為 key: value
   - username: nginx
  tasks:
   - name: create group
     group: name={{groupname}} system=yes gid=306                    #使用 {{key}} 引用變數的值
   - name: create user
     user: name={{username}} uid=306 group={{groupname}} 
   - name: copy file
     copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt     #在setup模組中可以獲取facts變數資訊

ansible-playbook test1.yaml -e "username=nginx"                      #在命令列裡定義變數,覆蓋劇本里的值

指定遠端主機sudo切換使用者許可權執行

---

- hosts: dbservers
  remote_user: zhangsan            
  become: yes                     #2.6版本以後的引數,之前是sudo,意思為切換使用者執行
  become_user: root               #指定sudo使用者為root

執行playbook時:ansible-playbook test1.yml -K <密碼>

when條件判斷

在Ansible中,提供的唯一一個通用的條件判斷是when指令,當when指令的值為true時,則該任務執行,否則不執行該任務。

when一個比較常見的應用場景是實現跳過某個主機不執行任務或者只有滿足條件的主機執行任務

vim test2.yaml
---
- hosts: all
  remote_user: root
  tasks:
   - name: shutdown host 
     command: /sbin/shutdown -r now
     when: ansible_default_ipv4.address == "192.168.150.10"      #.address為前一個變數的子變數,when指令中的變數名不需要手動加上 {{}}
或 
     when: inventory_hostname == "<主機名>"
    
ansible-playbook test2.yaml

迭代(迴圈

Ansible提供了很多種迴圈結構,一般都命名為with_items,作用等同於 loop 迴圈。

vim test3.yaml
---
- name: play1
  hosts: dbservers
  gather_facts: false
  tasks: 
    - name: create directories
      file:                                                             #縱向寫的格式,模組:引數
        path: "{{item}}"                                                  
        state: directory
      with_items:                                                       #等同於 loop:
        - /tmp/test1
        - /tmp/test2
    - name: add users
      user: name={{item.name}} state=present groups={{item.groups}}     #橫向寫的格式,模組=引數
      with_items:
        - name: test1                                             
          groups: wheel
        - name: test2
          groups: root
或
      with_items:
        - {name:'test1', groups:'wheel'}
        - {name:'test2', groups:'root'}

ansible-playbook test3.yaml

Templates 模組傳遞不同變數

Jinja是基於Python的模板引擎。Template類是Jinja的一個重要元件,可以看作是一個編譯過的模板檔案,用來產生目標文字,傳遞Python的變數給模板去替換模板中的標記,將配置檔案改為以.j2為字尾的檔案,然後在主機清單定義變數值,將.j2字尾的檔案複製到遠端主機上時裡面的變數會變為主機清單中定義的值

1、先準備一個以 .j2 為字尾的 template 模板檔案,設定引用的變數
cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2

vim /opt/httpd.conf.j2
Listen {{http_port}}                                #42行,修改
ServerName {{server_name}}                #95行,修改
DocumentRoot "{{root_dir}}"               #119行,修改

2、修改主機清單檔案,使用主機變數定義一個變數名相同,而值不同的變數
vim /etc/ansible/hosts       
[webservers]
192.168.80.11 http_port=192.168.150.10:80 server_name=www.accp.com:80 root_dir=/etc/httpd/htdocs

[dbservers]
192.168.80.12 http_port=192.168.150.15:80 server_name=www.benet.com:80 root_dir=/etc/httpd/htdocs

3、編寫 playbook 
vim apache.yaml
---
- hosts: all
  remote_user: root
  vars:
    - package: httpd
    - service: httpd
  tasks:
    - name: install httpd package
      yum: name={{package}} state=latest
    - name: install configure file
      template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf     #使用template模板
      notify:
        - restart httpd
    - name: create root dir
      file: path=/etc/httpd/htdocs state=directory
    - name: start httpd server
      service: name={{service}} enabled=true state=started
  handlers:
    - name: restart httpd
      service: name={{service}} state=restarted

ansible-playbook apache.yaml

示例yum安裝LNMP

vim /etc/ansible/hosts

vim /opy/nginx.repo                                           #準備nginx的下載源
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

mkdir /etc/ansible/lnmp
vim /etc/ansible/lnmp/
- name: nginx
  gather_facts: false
  hosts: lnmpservers
  remote_user: root
  tasks:
    - name: test connection
     ping:
    - name: disable seliux
     command: '/sbin/setenforce 0'               
     ignore_errors: true
    - name: set yum
     copy: src=/opt/nginx.repo dest=/etc/yum.repos.d/nginx.repo                      #複製宿主機的nginx下載原始檔
    - name: install nginx
     yum: name=nginx state=latest
    - name: start nginx service
     service: name=nginx state=started enabled=yes
- name: mysql
  gather_facts: false
  hosts: lnmpservers
  remote_user: root
  tasks:
    - name: remove mariadb
     yum: name=mariadb* state=absent
    - name: wget
     command: wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
    - name: install mysql
     yum: name=mysql57-community-release-el7-10.noarch.rpm
    - name: install mysql
     yum: name=mysql-community-server state=latest
    - name: start mysqld service
     service: name=mysqld state=started enabled=yes
    - name: genggai mima                                                                                       #獲取mysql的登入密碼並進行更改,需要大小寫字母加符號和數字的組合
     shell: mysqladmin -u root -p"$(grep "password" /var/log/mysqld.log | awk 'NR==1{print $NF}')" password 'Admin@123'
    - name: shouquan                                                                                              #授予登入許可權
     shell: mysql -uroot -p'Admin@123' -e "grant all privileges on *.* to 'root'@'%' IDENTIFIED BY 'Admin@123';" -e "flush privileges;"
    - name: remove mysql57
     yum: name=mysql57-community-release-el7-10.noarch state=absent
- name: php
  gather_facts: false
  hosts: lnmpservers
  remote_user: root
  tasks:
    - name: download libargon2 epel epel
     shell: rpm -Uvh http://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/l/libargon2-20161029-3.el7.x86_64.rpm && rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm  && rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
     ignore_errors: true
    - name: install php
     shell: yum -y install php72w php72w-cli php72w-common php72w-devel php72w-embedded php72w-gd php72w-mbstring php72w-pdo php72w-xml php72w-fpm php72w-mysqlnd php72w-opcache php72w-redis
     ignore_errors: true
    - name: start php
     service: name=php-fpm state=started enabled=yes
    - name: for peizhi nginx zhichi php jiexi
     copy: src=/opt/default.conf dest=/etc/nginx/conf.d/default.conf                #複製宿主機的配置檔案
    - name: modify index.php
     copy: src=/opt/index.php dest=/usr/share/nginx/html/index.php               #複製宿主機的php首頁我檔案
    - name: restart nginx
     service: name=nginx state=restarted

#在/opt目錄準備首頁檔案和nginx的配置檔案

vim /opt/index.php#配置一個簡單的php首頁檔案呼叫資料

vim /opt/default.conf #取消註釋,支援php服務

web頁面訪問http://192.168.150.5/index.php