欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中Ansible模塊的Playbook的具體使用

 更新時間:2020年05月28日 15:04:01   作者:mb5cd21e691f31a  
這篇文章主要介紹了python中Ansible模塊的Playbook的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

Playbook

在上一節(jié)中,我們詳細介紹了Ansible提供的一些常用模塊??梢钥吹剑珹nsible中的每個模塊專注于某一方面的功能。雖然每個模塊實現(xiàn)的功能都比較簡單,但是,將各個模塊組合起來就可以實現(xiàn)比較復雜的功能。在Ansible中,將各個模塊組合起來的文件是一個YAML格式的配置文件。這個配置文件,在Ansible中稱為Playbook。

在這一節(jié)中,我們將循序漸進地介紹Ansible中的Playbook,我們將首先介紹Playbook的定義,然后介紹如何使用Playbook完成遠程服務器部署,之后詳細介紹Playbook的基本語法,使用Playbook的基本講法就能夠完成大部分的部署任務。

在這一節(jié)中,找們將介紹如何使用Playbook的基本語法完成nginx與MongoDB的部署,最后,我們介紹了部分Playbook的高級語法。

1、Playbook的定義

Playbook不同于其他使用單個模塊操作遠程服務器,Playbook的功能更加強大。如果只使用Playbook的基本功能,那么,Playbook是一個非常簡單的配、管理和部署系統(tǒng)。此外,Playbook也可以實現(xiàn)各種高級功能,如指定任務的執(zhí)行順序,委派其他主機來執(zhí)行某一個任務,與監(jiān)控服務器和負載均衡組件進行交互等。

有一個非常恰當?shù)谋扔?,Ansible中的模塊類似于Linux下的命令,Ansible中的Playbook類似于Linux下的Shell腳本文件。Shell腳本文件將各個Linux命令組合起來,以此實現(xiàn)復雜的功能,Playbook將各個模塊組合起來也可以實現(xiàn)復雜的部署功能。在shell腳本中,除了調(diào)用Linux命令以外,還有一些基本的語法,如變量定義、if語句、for循環(huán)等。在Playbook中,一方面通過YAML格式進行定義提高Playbook的可讀性、可維護性,降低工程師的學習負擔;另一方面,Ansible提供了若干可以應用在Playbook中的選項,以便工程師實現(xiàn)更加高級的功能。

一個Playbook可以包含一到多個Play,每一個Play是一個完整的部署任務。在Play中,我們需要指定對哪些遠程服務器執(zhí)行操作,以及對這些遠程服務器執(zhí)行哪些操作。

下面是一個名為first_playbook.yml的Playbook。在這個Playbook中,我們定義了兩個Play,前者用來在數(shù)據(jù)庫服務器上部署MongoDB,后者用來在web服務器上部署“應用”。這里只是為了對Playbook進行演示,并沒有真的部署應用。

[root@python ~]# vim first_playbook.yml

---
- hosts: dbservers
 become: yes
 become_method: sudo
 tasks:
 - name: install mongodb
  yum: name=mongodb-server state=present

- hosts: webservers
 tasks:
 - name: copy file
  copy: src=/tmp/data.txt dest=/tmp/data.txt

 - name: change mode
  file: dest=/tmp/data.txt mode=655 owner=root group=root

這個Playbook中包含了兩個Play。一個Playbook可以包含一到多個Play,所以即使Playbook中值包含一個Play,也需要使用列表的形式進行定義。在YAML語法中,“- hosts”前面的“-”表示定義列表。

在Ansible中,一個Play必須包含以下兩項:

1. hosts:需要對哪些遠程服務器執(zhí)行操作
2. tasks:需要在這些服務器上執(zhí)行的任務列表

例如,對web服務器進行部署時,我們僅僅使用了hosts和tasks兩個選項。前者表示對哪些服務器執(zhí)行操作,后者表示對服務器執(zhí)行哪些操作。在部署數(shù)據(jù)庫服務器時需要安裝軟件,因此使用了become與become_method兩個選項,用來表示使用管理員的身份去安裝MongoDB數(shù)據(jù)庫。

一個Play可以包含一到多個task,因此task也必須以YAML的列表形式進行定義??梢钥吹?,在這個例子中,對數(shù)據(jù)庫服務器進行操作時僅包含了一個task,對web服務器進行部署時包含了兩個task。

在Ansible中,task有兩種定義形式:

1. action:module options

2. module:options

前一種形式是Ansible的舊版本語法,第2種形式是新版本的語法,直接使用模塊的名稱作為鍵,使用模塊的參數(shù)作為值。如下所示:

- name: install httpd
 yum: name=httpd update_cache=yes state=present

在安裝Apache的例子中,“name=httpd update_cache=yes state=present”是一個完整的字符串,而不是一個字典。只是字符串的值是一個“key=value”形式的參數(shù)。

在參數(shù)較多時,為了增加Playbook的可讀性,我們也可以像下面這樣定義一個task:

- name: install httpd
 yum: >
  name=httpd
  update_cache=yes
  state=present

在Ansible中,當參數(shù)較長時,除了使用“>”進行折疊換行以外,也可以使用縮進字塊的形式:

- name: install httpd
 yum: 
  name: httpd
  update_cache: yes
  state: present

雖然從字面來看,這兩種指定參數(shù)的方式相差不大。但是,從YAML的語法來說,這是完全不同的兩個方法。前者是一個比較長的字符串,后者是一個字典。

task的定義中,name是可選的。所以,像下面這樣定義task也是完全合法的:

- yum: name=httpd update_cache=yes state=present

name的作用在于,執(zhí)行Playbook時作為注釋進行顯示,以便使用者知道當前執(zhí)行到哪一步。因此,在定義task時,一般都會定義name字段。

在實際工作中,雖然一個Playbook可以包含多個Play,但是為了Playbook的可讀性和可維護性,我們一般只會在Playbook中編寫一個Play。例如,對于這里的例子,我們可以將first_playbook.yml這個Playbook拆分成兩個Playbook,分別名為db.yml與web.yml。其中,db.yml文件包含了與數(shù)據(jù)庫服務器相關(guān)的部署任務,web.yml文件包含了與web服務器相關(guān)的部署任務。

當我們需要部署數(shù)據(jù)庫服務器和web服務器時,可以先執(zhí)行db.yml文件,再執(zhí)行web.yml文件。除此之外,Ansible還提供了一種便捷方式來處理這種情況。例如,我們可以編寫一個名為all.yml的Playbook,它的內(nèi)容如下:

---
- include: db.yml
- include: web.yml

include選項是Ansible提供的,用于在一個Playbook中導入其他Playbook。在Ansible中,只需要使用include選項導入其他Playbook文件,執(zhí)行這個Playbook時,被導入的Playbook便會依次執(zhí)行。

上面詳細介紹了Ansible的Playbook定義,這個Playbook定義雖然比較簡單,但是,是一個比較完整的Playbook例子。在實際工作中使用的Playbook也不會比這個Playbook復雜很多。

我們接下來將介紹如何使用ansible-playbook命令執(zhí)行Playbook,然后再介紹Playbook的其他語法。

2、ansible拆分playbook.yml

查看一下所需文件是否正確

[root@python ~]# cat hosts 
127.0.0.1
[webservers]
192.168.1.60
[dbservers]
192.168.1.80
[common:children]
dbservers
webservers
[root@python ~]# cat /etc/ansible/ansible.cfg 
[defaults]
remote_user = root
remote_port = 22
inventory = /root/hosts

拆分playbook.yml

[root@python ~]# cat db.yml 
---
- hosts: dbservers
 become: yes
 become_method: sudo
 tasks:
 - name: install mongodb
  yum: name=mongodb-server state=present #mongodb-server 可歡成其他服務如(git)
[root@python ~]# cat web.yml 
---
- hosts: webservers
 tasks:
 - name: copy file
  copy: src=/tmp/data.txt dest=/opt/data.txt 
 - name: change mode
  file: dest=/opt/data.txt mode=655 owner=root group=root
[root@python ~]# cat all.yml 
---
- include: db.yml
- include: web.yml
[root@python ~]# touch /tmp/data.txt
[root@python ~]# touch /opt/data.txt

3、使用Ansible-playbook執(zhí)行Playbook

上一小節(jié)中,我們簡單地介紹了Playbook的定義。那么,當我們有了一個Playbook文件以后,如何執(zhí)行這個文件完成應用部署呢?我們知道,Ansible安裝完成以后存在多個可執(zhí)行的命令行工具,其中,ansible-playbook便是用于執(zhí)行Playbook的命令行工具。

ansible-playbook的執(zhí)行方式如下:

ansible-playbook first_playbook.yml

ansible-playbook命令也有若干命令行選項,其中,有部分選項與ansible命令相同。Ansible中也存在一些ansible-playbook特有的命令行選項。

ansible-playbook命令與ansible命令相同的命令行選項:

-T --timeout:建立SSH連接的超時時間
--key-file --private-key:建立SSH連接的私鑰文件
-i --inventory-file:指定Inventory文件,默認是/etc/ansible/hosts
-f --forks:并發(fā)執(zhí)行的進程數(shù),默認為5
--list-hosts:playbooks匹配的服務器列表。

ansible-playbook也有一個名為--list-hosts的選項,該選項的作用是列出匹配的服務器列表。例如,在我們這個 Playbook的例子中,hosts文件的內(nèi)容如下:

127.0.0.1
[webservers]
192.168.1.60
[dbservers]
192.168.1.80
[common:children]
dbservers
webservers

我們知道,Ansible中的Play定義了需要對哪些服務器執(zhí)行哪些操作,也就是說,每一個Play都可以指定匹配的遠程服務器。在我們這個Playbook的例子中,對數(shù)據(jù)庫服務器安裝MongoDB,對web服務器部署“應用“。因此,ansible-playbook命令與ansible命令的--list-hosts選項輸出的結(jié)果將會大不相同。ansible-playbook命令的--list-hosts選項輸出的結(jié)果如下:

[root@python ~]# ansible-playbook all.yml --list-hosts

ansible-playbook命令有一些特有的選項,如下所示:

--list-tasks:列出任務列表
--step:每執(zhí)行一個任務后停止,等待用戶確認
--syntax-check:檢查Playbook語法
-C --check:檢查當前這個Playbook是否會修改遠程服務器,相當于預測Playbook的執(zhí)行結(jié)果。

這里的幾個選項,除了--step以外,其他幾個選項都不會執(zhí)行Playbook中的任務。這些選項存在主要是為了便于調(diào)試Playbook。例如,--list-tasks選項,該選項用來顯示當前Playbook中的任務列表。當Playbook比較大時,可以通過這個方式快速查看任務列表。如下所示:

[root@python ~]# ansible-playbook all.yml --list-tasks
playbook: all.yml

 play #1 (dbservers): dbservers  TAGS: []
  tasks:
   install mongodb  TAGS: []

 play #2 (webservers): webservers TAGS: []
  tasks:
   copy file TAGS: []
   change mode  TAGS: []

當我們查看任務列表時,任務的名稱就是task的name字段。因此,name的定義需要具有較好的描述性,讓使用者通過名字就能知道該任務需要做什么事情。

--step選項類似于編程語言中的單步調(diào)試。當我們使--step選項執(zhí)行Playbook時,ansible-playbook在每一個任務之前都會停住,等侍用戶輸入yes,、no或continue。如下所示:

[root@python ~]# ansible-playbook all.yml --step
[DEPRECATION WARNING]: 'include' for playbook includes. You should use 
'import_playbook' instead. This feature will be removed in version 2.12. 
Deprecation warnings can be disabled by setting deprecation_warnings=False in 
ansible.cfg.

PLAY [dbservers] ***************************************************************
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: y

Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: *********************

TASK [Gathering Facts] *********************************************************
ok: [192.168.1.80]
Perform task: TASK: install mongodb (N)o/(y)es/(c)ontinue: y

Perform task: TASK: install mongodb (N)o/(y)es/(c)ontinue: *********************

TASK [install mongodb] *********************************************************
changed: [192.168.1.80]

PLAY [webservers] **************************************************************
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: y

Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: *********************

TASK [Gathering Facts] *********************************************************
ok: [192.168.1.60]
Perform task: TASK: copy file (N)o/(y)es/(c)ontinue: y

Perform task: TASK: copy file (N)o/(y)es/(c)ontinue: ***************************

TASK [copy file] ***************************************************************
changed: [192.168.1.60]
Perform task: TASK: change mode (N)o/(y)es/(c)ontinue: y

Perform task: TASK: change mode (N)o/(y)es/(c)ontinue: *************************

TASK [change mode] *************************************************************
changed: [192.168.1.60]

PLAY RECAP *********************************************************************
192.168.1.60        : ok=3  changed=2  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0  
192.168.1.80        : ok=2  changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0 

輸入yes以后,任務將會繼續(xù)執(zhí)行,并在下一個任務時停止,等待用戶繼續(xù)輸入。當我們輸入continue時,Ansible會執(zhí)行完當前這個Play,當執(zhí)行到下一個Play時再停止,并等待用戶輸入。

二、Playbook的詳細語法

到目前為止,我們已經(jīng)學習了如何編寫Playbook以及如何運行Playbook。但是,我們僅僅介紹了最簡單的Playbook。在這一節(jié)中,我們將會介紹Playbook是如何通過不同的選項提供豐富多樣的功能。靈活使用這些選項,能夠編寫出形式各異的Playbook,以此應對自動部署中的各種情況。

在定義Play時,只有hosts與tasks是必選選項,其他選項都是根據(jù)需要添加的。在這一小節(jié)中。我們將介紹Playbook提供的不同功能,以Playbook的功能為線索,介紹Play與task中可以使用的選項。

(1)權(quán)限

在Ansible中,默認使用當前用戶連接遠程服務器執(zhí)行操作。我們也可以在anaible.cfg文件中配置連接遠程服務器的默認用戶。此外,如果是不同的用戶使用不同類型的遠程服務器,那么也可以在Playbook的Play定義中指定連接遠程服務器的用戶。例如,我們可以指定執(zhí)行Play的用戶:

---
- hosts: webservers
 remote_user: root

用戶可以細分每一個task,如下所示:

---
- hosts: werbservers
 remote_user: root
 tasks:
  - name: test connection
   ping:
    remote_user: yourname

很多時候,我們需要的不是以某個特定用戶連接遠程服務器,而是在需要更高級別的權(quán)限時,使用管理員身份去執(zhí)行操作。在ansible中,可以通過become與become_ method選項實現(xiàn):

---
- hosts: werbservers
 remote_user: root
 become: yes

與remote_user選項類似,我們也可以為單個任務使用管理員權(quán)限,如下所示:

---
- hosts: werbservers
 remote_user: yourname
 tasks:
  - name: installed nginx
   service: name=nginx state=started
   become: yes
   become_method: sudo

實例

先修改遠程服務器中test的權(quán)限為(0:0)

[root@192 ~]# vim /etc/passwd
test:x:0:0::/home/test:/bin/bash
[root@python ~]# chown test:root /etc/ansible/*
[root@python ~]# su test
[test@python root]$ cd 
[test@python ~]$ vim hosts
[db]
192.168.1.60

[test@python ~]$ vim db.yml

---
- hosts: db
 remote_user: root       #遠程服務器登陸的用戶
 tasks:
  - name: installed nginx
   become: yes
   become_method: sudo
   ping:
    remote_user: root     #遠程服務器登陸的用戶
[test@python ~]$ vim /etc/ansible/ansible.cfg 

[defaults]
inventory = /home/test/hosts

執(zhí)行一下

[test@python ~]$ sudo ansible-playbook db.yml --step

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

  #1) Respect the privacy of others.
  #2) Think before you type.
  #3) With great power comes great responsibility.

[sudo] password for test: 

PLAY [db] **********************************************************************
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: y

Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: *********************

TASK [Gathering Facts] *********************************************************
Enter passphrase for key '/root/.ssh/id_rsa': 
ok: [192.168.1.60]
Perform task: TASK: installed nginx (N)o/(y)es/(c)ontinue: 

Perform task: TASK: installed nginx (N)o/(y)es/(c)ontinue: *********************

PLAY RECAP *********************************************************************
192.168.1.60        : ok=1  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0 

(2)通知

在Ansible中,模塊是冪等的。例如,我們要在遠程服務器上創(chuàng)建一個用戶,如果該用戶已經(jīng)存在,那么Ansible不會將該用戶刪除以后重新創(chuàng)建,而是直接返回成功,并通過changed字段表示是否對遠程服務器進行了修改。

考慮這樣一種需求:我們要通過Ansible修改Apache的配置文件,并重啟Apache服務,使得新的配置文件生效。由于Ansible的模塊是冪等的,當我們修改Apache的配置文件時,如果配置文件的內(nèi)容已經(jīng)與我們想要修改成的內(nèi)容一樣(例如,不小心將Ansible執(zhí)行了兩次的情況),那么,Ansible就什么也不做。既然Apache的配置文件并沒有真的被修改,那么我們也不應該去重啟Apache的服務器。在Ansible中,通過notify與handler機制來實現(xiàn)這里的功能。

在下面的例子中,我們首先嘗試安裝Apache,然后修改Apache的配置文件。如果配置文件被修改,則通過notify選項通知handler進行后續(xù)處理。

handler是Ansible提供的條件機制,與tasks比較類似,都是去執(zhí)行某些操作。但是,handler只有在被notify觸發(fā)以后才會執(zhí)行,如果沒有被觸發(fā)則不會執(zhí)行。在Playbook中,如果task后面存在notify選項,那么,當Ansible識別到task改變了系統(tǒng)的狀態(tài),就會通過notify去觸發(fā)handler。

Ansibie是通過什么條件判斷notify觸發(fā)的是哪一個handler呢?很簡單,在Ansible中,task使用handler的名字作為參數(shù),以此來觸發(fā)特定的handler。例如,在我們這里的例子中,notify觸發(fā)的是“restart apache"這個handler, handlers中也存在一個名為" restart apache“的handler。

---
- hosts: webservers
 tasks:
 - name: ensure apache is at the latest version
  yum: name=httpd state=latest

 - name: write the apache config file
  template: src=/srv/httpd.j2 dest=/etc/httpd.conf
  notify:
  - restart apache

 - name: ensure apache is running
  service: name=httpd state=started

 handlers:
  - name: restart apache
   service: name=httpd state=restarted

需要注意的是,handler只會在所有task執(zhí)行完后執(zhí)行。并且,即便一個handler被觸發(fā)多次,它也只會執(zhí)行一次。handler并不是在被觸發(fā)時立即執(zhí)行,而是按照Play中定義的順序執(zhí)行。一般情況下,handler都位于Play的最后,即在所有任務執(zhí)行完成以后再執(zhí)行。

Ansible官方文檔提到handler的唯一用途,就是重啟服務與服務器,正如找們這個例子所演示的。

在這個例子中,我們還用到T了template模塊。template模塊用以渲染Jinja模板。

(3)變量

在Inventory管理章節(jié),我們已經(jīng)介紹了如何定義變量。在Ansible中,還有其他幾種定義變量的方式。對于簡單的Playbook,最直接的方式是將變量定義在Playbook的vars選項中。如下所示:

- hosts: dbservers
 vars:
  mysql_port: 3307

在Playbook中定義變量,可以在模板渲染時使用。例如:Ansible官方給出的例子中,MySQL配置文件的部分模板如下:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
port={{ mysql_port }}

當變量較少的時候,定義在vars選項中完全沒有問題。當變量較多時,可以將變量保存在一個獨立的文件中,并通過vars_files選項引用該文件。如下所示:

---
- hosts: all
 vars:
  favcolor: blue
 vars_files:
  - /vars/external_vars.yml

 tasks:
 - name: this is just a placeholer
  command: /bin/echo foo

保存變量的文件是一個簡單的YAML格式的字典,如下所示:

---
# in th above example, this would be vars/external_vars.yml
somevar: somevalue
password: magic

在shell腳本中,我們可以通過獲取上一條命令的返回碼判斷命令是否執(zhí)行成功。在Ansible中,我們也可以獲取任務的執(zhí)行結(jié)果,將任務的執(zhí)行結(jié)果保存在一個變最中,并在之后引用這個變量。這樣的變量在Ansible中使用register選項獲取,也稱為注冊變量。

例如,在下面這個例子中,我們首先執(zhí)行/usr/bin/foo命令,并通過register選項獲取命令的執(zhí)行結(jié)果,將結(jié)果保存在foo_result中。在之后的task中,使用這個變量名引用/usr/bin/foo命令的執(zhí)行結(jié)果。

- hosts: web_servers
 tasks:
 - shell: /usr/bin/foo
  register: foo_result
  ignore_errors: True

 - shell: /usr/bin/bar
  when: foo_result == 5

這個例子還涉及了兩個新的選項,分別是ignore_errors與when。前者表示忽略當前task中的錯誤,后者是一個條件語句,只有條件為真時才會執(zhí)行這個task。

(4)Facts變量

在Ansible中,還有一些特殊的變量,這些變量不需要我們進行任何設置就可以直接使用,這樣的變量稱為Facts變量。Facts變量是Ansible執(zhí)行遠程部署之前從遠程服務器中獲取的系統(tǒng)信息,包括服務器的名稱、IP地址、操作系統(tǒng)、分區(qū)信息、硬件信息等。Facts變量可以配合Playbook實現(xiàn)更加個性化的功能需求。例如,將MongoDB數(shù)據(jù)庫的數(shù)據(jù)保存在/var/mongo-\<hostname>/目錄下。

我們可以通過setup模塊查看Facts變量的列表,如下所示:

ansible all -m setup

有了Facts變量以后,如何在Ansible中使用它們呢?答案是直接使用。我們可以在Playbook中直接通過變量的名字引用變量,也可以在Jinja2模板中通過變量的名字引用變量。下面是一個名為test_facts.yml的Playbook。在這個Playbook中,我們輸出了操作系統(tǒng)的類型,并且只有在操作系統(tǒng)為“RedHat"類操作系統(tǒng)時才會執(zhí)行安裝操作。

---
- hosts: dbservers
 tasks:
  - shell: echo {{ ansible_os_family }}
   register: myecho

  - debug: var=myecho.stdout_lines

  - name: install git on Red Hat Linux
   yum: name=git state=installed
   when: ansible_os_family == "RedHat"

setup模塊為了輸出結(jié)果的可讀性,對模塊的輸出進行了歸類和整理。因此,當我們要訪問復雜變量的子屬性時,需要使用嵌套結(jié)構(gòu)。例如,我們可以通過下面兩種方式訪問Ansible中的ipv4地址:

ansible_ens33['ipv4']['address']
ansible_ens33.ipv4.address

訪問復雜的變量的Playbook:

---
- hosts: dbservers
 gather_facts: yes
 tasks:
  - shell: echo {{ ansible_ens33['ipv4']['address'] }}
   register: myecho

  - debug: var=myecho.stdout_lines

  - shell: echo {{ ansible_ens33.ipv4.address }}
   register: myecho

  - debug: var=myecho.stdout_lines

在實際工作中,我們一般會在Jinja2模板中引用Facts變量。使用方式與這里的例子一樣,為了節(jié)省篇幅就不再贅述了。

在Playbook中,可以通過gather_ facts選項控制是否收集遠程服務器的信息。該選項默認取值為yes,如果確定不需要用到遠程服務器的信息,可以將該選項設置為no,以此提高Ansible部署的效率。如下所示:

---
- hosts: dbservers
 gather_factes: no
 tasks:

(5)循環(huán)

- name: Install Mysql package
 yum: name={{ item }} state=installed
 with_items:
  - mysql-server
  - MySQL-python
  - libselinux-python
  - libsemanage-python

(6)條件

有時候,一個任務是否執(zhí)行取決于一個變量的取值,或者上一個任務的執(zhí)行結(jié)果,這個時候找們就需要條件語句。再或者說,在循環(huán)的時候想要跳過一些特定的元素,在服務器部署時只對某些特定的操作系統(tǒng)進行操作。所有這些行為都可以使用條件語句解決。Ansible的Playbook不是一門編程語言,因此沒有相應的條件語句,不過Ansible提供了一個類似的選項。

在Playbook中可以通過when選項執(zhí)行條件語句,when就類似于編程語言中的if語句。

下面是一個簡單的when選項使用示例:

# 查看Linux系統(tǒng)版本:cat /etc/redhat-release
tasks:
 - name: "系統(tǒng)關(guān)機"
  command: /sbin/shutdown -t now
  when: ansible_os_family == "RedHat"  

when選項也支持多個條件語句,下面是一個YAML格式的多條件:

tasks:
 - name: "shutdown CentOS 7 systems"
  command: /sbin/shutdown -t now
  when:
   - ansible_distribution == "CentOS"
   - ansible_distribution_major_version == "7"

對于更復雜的條件可以使用and、or與括號進行定義:

tasks:
 - name: "shutdown CentOS 7 and Debian 6 systems"
  command: /sbin/shutdown -t now
  when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "7") or (ansible_distribution == "Debian" and ansible_distribution_major_version == "6")

在when選項中可以讀取變量的取值,例如:

vars:
 epic: true

tasks:
 - shell: echo "This certainly is epic!"
  when: epic

when選項可以與循環(huán)一起使用,以實現(xiàn)過濾的功能:

tasks:
 - command: echo {{ item }}
  with_items: [0, 2, 4, 6, 8, 10]
  when: item > 5

(7)任務執(zhí)行策略

在Ansible中,Playbook的執(zhí)行是以task為單位進行的。Ansible默認使用5個進程對遠程服務器執(zhí)行任務。在默認情況的任務執(zhí)行策略( linear)中,Ansible首先執(zhí)行task1,并且等到所有服務器執(zhí)行完task1以后再開始執(zhí)行task2,以此類推。從Ansible 2.0開始,Ansible支持名為free的任務執(zhí)行策略,允許執(zhí)行較快的遠程服務器提前完成Play的部署,不用等待其他遠程服務器一起執(zhí)行task。如下所示:

- hosts: all
 strategy: free
 tasks:
  ……

在這一節(jié)中,我們比較詳細地介紹了Ansible中的Playbook選項。在Ansible中,Play與task都有很多選項,每個選項可以實現(xiàn)不同的功能。Ansibie官方并沒有通過功能的形式介紹不同的選項給出一個完整的選項列表。我們也可以參考https://github.com/lorin/ansible-quickref快速了解Play與task中的選項,以及各個選項的含義。

4、案例:使用Playbook部署nginx

wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
//下載源

在這個例子中,我們使用Ansible配置一臺服務器運行nginx進程。部署nginx的Playbook如下:

---
- hosts: webservers
 become: yes
 become_method: sudo
 vars:
  worker_prosess: 4
  worker_connections: 768
  max_open_files: 65506
 tasks:
  - name: install nginx
   yum: name=nginx update_cache=yes state=present

  - name: copy nginx config file
   template: src=/root/test_ansible/nginx.conf.j2 dest=/etc/nginx/nginx.conf
   notify: restart nginx

  - name: copy index.html
   template:
    src: /root/test_ansible/index.html.j2
    dest: /usr/share/nginx/www/index.html
    mode: 0644
   notify: restart nginx
 handlers:
  - name: restart nginx
   service: name=nginx state=restarted

在這個Playbook中,我們首先通過hosts選項指定了要對哪些遠程服務器執(zhí)行操作。隨后,我們通過become與become_method選項聲明了部署時使用sudo權(quán)限。接下來,我們在vars字段中定義了三個變量,這三個變量將用在nginx的配置文件中。我們在tasks選項下定義了部署nginx服務的任務列表,包括軟件安裝、模板渲染、定制s首頁和重啟nginx進程。

為了避免配置文件在沒有任何修改的情況下重啟了nginx進程,這里使用了Ansible的handler機制。在這個Playbook中,存在兩個notify選項,以及一個handler選項。無論是nginx的配置文件,還是定制首頁發(fā)生了修改,我們都會重啟nginx進程。由于我們使用了Ansible的handlers機制,因此,在沒有任何修改的情況下,Ansible并不會重啟nginx進程。使用handler機制還有一個好處,notify多次,handler也只會執(zhí)行一次,避免了反復多次重啟nginx進程。

在這個部署nginx服務的Playbook中,我們用到了nginx.conf.j2這個配置模板。這個模板使用的是Jinja2的語法,所以后綴名為j2。模板的內(nèi)容如下:

[root@python ~]# mkdir test_ansible
[root@python ~]# vim /root/test_ansible/nginx.conf.j2
worker_processes {{ worker_prosess }};
worker_rlimit_nofile {{ max_open_files }};

events {
  worker_connections {{ worker_connections }};
}

http {
  server {
    listen    80;

    listen 443 ssl;

    server_name localhost;

    location / {
      root  /usr/share/nginx/www;
      index index.html index.htm;

      tr_files $uri $uri/ =404;
    }
  }
}

Ansible會使用我們在Playbook的vars字段中定義的變量,將Jinja2模板渲染成真實的配置文件。

我們的Playbook還用到了一個名為index.html.j2的模板,該模板用于渲染網(wǎng)站首頁。index.html.j2的內(nèi)容如下:

[root@python ~]# vim /root/test_ansible/index.html.j2
<html>
  <meta charset="utf-8">
  <head>
    <title>wellcome to ansible</title>
  </head>
  <body>
    <h1>nginx, configured by ansible</h1>
    <p>如果你能看到這個頁面,說明ansible自動部署nginx成功了!</p>

    <p>{{ ansible_hostname }}<p>
  </body>
</html>

在index.html.j2中,我們用到了一個名為ansible_hostname的變量。這個變量是Facts變量,是Ansible在執(zhí)行Playbook之前從遠程服務器獲取到的信息。因此,我們不需要定義,直接使用即可。

有了Playbook以后,使用ansible-playbook命令進行部署。如下所示:

[root@python ~]# pip install Jinja2
[root@python ~]# vim /etc/ansible/ansible.cfg 

[defaults]
inventory = /root/hosts

[root@bogon ~]# ansible-playbook nginx.yml

PLAY [webservers] **********************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************
ok: [127.0.0.1]

TASK [install nginx] *******************************************************************************************************
ok: [127.0.0.1]

TASK [copy nginx config file] **********************************************************************************************
ok: [127.0.0.1]

TASK [copy index.html] *****************************************************************************************************
ok: [127.0.0.1]

PLAY RECAP *****************************************************************************************************************
127.0.0.1         : ok=4  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0  

[root@bogon ~]# 

如果安裝失敗,可能是端口被占用,可以停止使用該端口的服務,或者更改nginx端口。

[root@bogon ~]# netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address      Foreign Address     State    PID/Program name  
tcp    0   0 0.0.0.0:111       0.0.0.0:*        LISTEN   1/systemd      
tcp    0   0 0.0.0.0:6000      0.0.0.0:*        LISTEN   7470/X       
tcp    0   0 192.168.122.1:53    0.0.0.0:*        LISTEN   7654/dnsmasq    
tcp    0   0 0.0.0.0:22       0.0.0.0:*        LISTEN   7337/sshd      
tcp    0   0 127.0.0.1:631      0.0.0.0:*        LISTEN   7340/cupsd     
tcp    0   0 127.0.0.1:6010     0.0.0.0:*        LISTEN   31653/sshd: root@pt 
tcp    0   0 127.0.0.1:6011     0.0.0.0:*        LISTEN   31653/sshd: root@pt 
tcp    0   0 127.0.0.1:6012     0.0.0.0:*        LISTEN   31653/sshd: root@pt 
tcp6    0   0 :::111         :::*          LISTEN   1/systemd      
tcp6    0   0 :::80          :::*          LISTEN   17867/httpd     
tcp6    0   0 :::6000         :::*          LISTEN   7470/X       
tcp6    0   0 :::22          :::*          LISTEN   7337/sshd      
tcp6    0   0 ::1:631         :::*          LISTEN   7340/cupsd     
tcp6    0   0 ::1:6010        :::*          LISTEN   31653/sshd: root@pt 
tcp6    0   0 ::1:6011        :::*          LISTEN   31653/sshd: root@pt 
tcp6    0   0 ::1:6012        :::*          LISTEN   31653/sshd: root@pt 
[root@bogon ~]# systemctl stop httpd.service

第二臺服務器啟動一下nginx

[root@192 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@192 ~]# nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()

瀏覽器訪問一下

到此這篇關(guān)于python中Ansible模塊的Playbook的具體使用的文章就介紹到這了,更多相關(guān)python Ansible Playbook內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 探索?Python?Restful?接口測試的奧秘

    探索?Python?Restful?接口測試的奧秘

    掌握Python?Restful?接口測試,讓你的后端服務像流水一樣順暢,本指南將帶你輕松穿梭于斷言和請求之間,搞定所有測試難題,一起來看,讓代碼在你的指尖跳舞吧!
    2023-12-12
  • Python中requests庫的基本概念與具體使用方法

    Python中requests庫的基本概念與具體使用方法

    requests庫是用python編寫的基于urllib,requests唯一的一個非轉(zhuǎn)基因的Python HTTP庫,下面這篇文章主要給大家介紹了關(guān)于Python中requests庫的基本概念與具體使用方法,需要的朋友可以參考下
    2022-08-08
  • Python大數(shù)據(jù)用Numpy Array的原因解讀

    Python大數(shù)據(jù)用Numpy Array的原因解讀

    一個Numpy數(shù)組由許多值組成,所有值的類型是相同的,Numpy 是Python科學計算的一個核心模塊,本文重點給大家介紹Python大數(shù)據(jù)Numpy Array的相關(guān)知識,感興趣的朋友一起看看吧
    2022-02-02
  • 解決python 執(zhí)行sql語句時所傳參數(shù)含有單引號的問題

    解決python 執(zhí)行sql語句時所傳參數(shù)含有單引號的問題

    這篇文章主要介紹了解決python 執(zhí)行sql語句時所傳參數(shù)含有單引號的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python文件讀寫及常用文件的打開方式

    Python文件讀寫及常用文件的打開方式

    這篇文章主要介紹了Python文件讀寫及常用文件的打開方式,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09
  • python框架flask入門之路由及簡單實現(xiàn)方法

    python框架flask入門之路由及簡單實現(xiàn)方法

    這篇文章主要介紹了python框架flask入門路由及路由簡單實現(xiàn)方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • Python圖像處理之使用OpenCV檢測對象顏色

    Python圖像處理之使用OpenCV檢測對象顏色

    OpenCV顏色檢測只是一個起點,最終目標是最終使用Python?3代碼在視頻流幀中定位彩色元素位置,下面這篇文章主要給大家介紹了關(guān)于Python圖像處理之使用OpenCV檢測對象顏色的相關(guān)資料,需要的朋友可以參考下
    2022-12-12
  • Python基礎之字符串操作常用函數(shù)集合

    Python基礎之字符串操作常用函數(shù)集合

    這篇文章主要介紹了Python基礎之字符串操作常用函數(shù)集合,需要的朋友可以參考下
    2020-02-02
  • Python與AI分析時間序列數(shù)據(jù)

    Python與AI分析時間序列數(shù)據(jù)

    預測給定輸入序列中的下一個是機器學習中的另一個重要概念.本章為您提供有關(guān)分析時間序列數(shù)據(jù)的詳細說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-05-05
  • Python為什么要保留顯式的self

    Python為什么要保留顯式的self

    本文主要介紹了Python為什么要保留顯式的self,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-06-06

最新評論