Ansible第二篇:ansible-playbook
一、Playbook語法
Ansible-playbook采用YAML語法編寫。
示例:
[root@LOCALHOST ~]# cat yaml/httpd.yaml
連續的項目(即列表)用 -減號來表示,key/value(字典)用冒號:分隔。
playbook語法有如下特性:
執行playbook:
[root@LOCALHOST ~]# ansible-playbook yaml/httpd.yaml PLAY [control-node] ********************************************************************************************************TASK [Gathering Facts] ***************************************************************************************************** ok: [openstack-control2] ok: [openstack-control1]TASK [install httpd package.] ********************************************************************************************** changed: [openstack-control2] changed: [openstack-control1]TASK [copy httpd configure file to remote host.] *************************************************************************** changed: [openstack-control1] changed: [openstack-control2]TASK [boot httpd service.] ************************************************************************************************* changed: [openstack-control2] changed: [openstack-control1]PLAY RECAP ***************************************************************************************************************** openstack-control1 : ok=4 changed=3 unreachable=0 failed=0 openstack-control2 : ok=4 changed=3 unreachable=0 failed=0二、Playbook中的變量
2.1 yaml文件中定義變量
[root@LOCALHOST ~]# cat yaml/vars.yaml --- - hosts: compute-noderemote_user: rootvars:pkg: httpd # 定義變量tasks:- name: install httpd serviceyum: name={{ pkg }} state=installed # 引用變量playbook中用vars關鍵字聲明變量,變量定義 變量名: 變量值
變量引用 :{{ 變量名 }}
2.2 引用外部變量
在命令行使用--extra-vars參數賦值變量;
[root@LOCALHOST ~]# cat yaml/extra_vars.yaml --- - hosts: control-noderemote_user: roottasks:- name: create a filefile:path: /tmp/{{ filename }} # 引用外部變量mode: 0644state: touch命令行使用--extra_vars傳入變量:
[root@LOCALHOST ~]# ansible-playbook yaml/extra_vars.yaml --extra-vars "filename=temp.txt"--extra_vars "變量名=變量值"
2.3 資產清單(inventory)中定義的變量
也就是在/etc/ansible/hosts文件中定義的變量;
[root@LOCALHOST ~]# cat /etc/ansible/hosts [load-node] openstack-load1 openstack-load2[compute-node] openstack-compute1 ansible_ssh_host=10.0.1.10 ansible_ssh_port=2002 ansible_ssh_user=stanley ansible_ssh_pass=etyfhzmweadf openstack-compute2[control-node] openstack-control1 filename=control1.txt # 主機變量 openstack-control2 filename=control2.txt[openstack:children] load-node compute-node control-node[openstack:vars] issue="Hello, World" # 組變量注意:組變量定義時,不要落下關鍵字vars,[組名:vars]。
在playbook中引用{{ 變量名 }}即可。
ansible內置了一些固定的主機變量名,在inventory中定義其值,如下:
ansible_ssh_host將要連接的遠程主機名.與你想要設定的主機的別名不同的話,可通過此變量設置.ansible_ssh_portssh端口號.如果不是默認的端口號,通過此變量設置.ansible_ssh_user默認的 ssh 用戶名ansible_ssh_passssh 密碼(這種方式并不安全,我們強烈建議使用 --ask-pass 或 SSH 密鑰)ansible_sudo_passsudo 密碼(這種方式并不安全,我們強烈建議使用 --ask-sudo-pass)ansible_sudo_exe (new in version 1.8)sudo 命令路徑(適用于1.8及以上版本)ansible_connection與主機的連接類型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默認使用 paramiko.1.2 以后默認使用 'smart','smart' 方式會根據是否支持 ControlPersist, 來判斷'ssh' 方式是否可行.ansible_ssh_private_key_filessh 使用的私鑰文件.適用于有多個密鑰,而你不想使用 SSH 代理的情況.ansible_shell_type目標系統的shell類型.默認情況下,命令的執行使用 'sh' 語法,可設置為 'csh' 或 'fish'.ansible_python_interpreter目標主機的 python 路徑.適用于的情況: 系統中有多個 Python, 或者命令路徑不是"/usr/bin/python",比如 \*BSD, 或者 /usr/bin/python不是 2.X 版本的 Python.我們不使用 "/usr/bin/env" 機制,因為這要求遠程用戶的路徑設置正確,且要求 "python" 可執行程序名不可為 python以外的名字(實際有可能名為python26).與 ansible_python_interpreter 的工作方式相同,可設定如 ruby 或 perl 的路徑....參考Ansible中文權威指南。
2.4 直接使用facts變量
使用命令ansible all -m setup獲取到的主機信息,其中的KEY都可以被當作變量引用:
[root@LOCALHOST ~]# cat yaml/facts_vars.yaml --- - hosts: compute-noderemote_user: roottasks:- name: write fqdn into fqdn.logshell: "echo {{ ansible_fqdn }} {{ ansible_eth1.ipv4.address }} > /tmp/fqdn.log"上述代碼中{{ ansible_fqdn }}就是直接引用的facts變量;
{{ ansible_eth1.ipv4.address }} 引用的值就相當于下面這樣。
最終{{ ansible_eth1.ipv4.address }}=10.0.1.10
2.5 注冊變量
在playbook中用register關鍵字定義一個變量,這個變量的值就是當前任務執行的輸出結果;
[root@LOCALHOST ~]# cat yaml/reg_vars.yaml --- - hosts: load-noderemote_user: roottasks:- name: show dateshell: "/bin/date"register: date # 注冊一個變量- name: Record time logshell: "echo {{ date.stdout }} > /tmp/date.log"引用注冊變量要用 {{ date.stdout }}表示標準輸出。
[root@openstack-load1 ~]# cat /tmp/date.log 2018年 03月 29日 星期四 15:52:01 CST如果直接{{ date }}這樣引用,則文件中寫入的是如下內容:
{stderr_lines: [], uchanged: True, uend: u2018-03-29 15:49:52.609894, failed: False, ustdout: u2018\u5e74 03\u6708 29\u65e5 \u661f\u671f\u56db 15:49:52 CST, ucmd: u/bin/date, urc: 0, ustart: u2018-03-29 15:49:52.602918, ustderr: u, udelta: u0:00:00.006976, stdout_lines: [u2018\u5e74 03\u6708 29\u65e5 \u661f\u671f\u56db 15:49:52 CST]}2.6 變量優先級
上述這些變量定義的方法,它們的優先級如下:
三、Playbook中的方法
3.1 handlers
在需要被監控的任務(tasks)中定義一個notify,只有當這個任務被執行時,才會觸發notify對應的handlers去執行相應操作。
[root@LOCALHOST ~]# cat yaml/httpd.yaml --- - hosts: control-noderemote_user: rootvars:- pkg: httpdtasks:- name: "install httpd package."yum: name={{ pkg }} state=installed- name: "copy httpd configure file to remote host."copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.confnotify: restart httpd- name: "boot httpd service."service: name=httpd state=startedhandlers:- name: restart httpdservice: name=httpd state=restarted在使用handlers的過程中,有以下幾點需要注意:
3.2 tags
tags用于讓用戶選擇運行playbook中的部分代碼。ansible具有冪等性,因此會自動跳過沒有變化的部分,即便如此,有些代碼為測試其確實沒有發生變化的時間依然會非常地長。此時,如果確信其沒有變化,就可以通過tags跳過此些代碼片斷。
ansible的標簽(Tags)功能可以給角色(Roles)、文件、單獨的任務,甚至整個Playbook打上標簽,然后利用這些標簽來指定要運行Playbook中的個別任務,或不執行指定的任務。
[root@LOCALHOST ~]# cat yaml/httpd.yaml --- - hosts: control-noderemote_user: rootvars:- pkg: httpdtasks:- name: "install httpd package."yum: name={{ pkg }} state=installed- name: "copy httpd configure file to remote host."copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.confnotify: restart httpd- name: "start httpd service."tags:- start_httpd # 給“start httpd service”這個任務打個標簽service: name=httpd state=startedhandlers:- name: restart httpdservice: name=httpd state=restarted在命令行中調用:
[root@LOCALHOST ~]# ansible-playbook yaml/httpd.yaml --tags start_httpdPLAY [control-node] ********************************************************************************************************TASK [Gathering Facts] ***************************************************************************************************** ok: [openstack-control1] ok: [openstack-control2]TASK [start httpd service.] ************************************************************************************************ ok: [openstack-control1] ok: [openstack-control2]PLAY RECAP ***************************************************************************************************************** openstack-control1 : ok=2 changed=0 unreachable=0 failed=0 openstack-control2 : ok=2 changed=0 unreachable=0 failed=0四、Playbook的流程控制
4.1 when 條件判斷
當關鍵字when后面的條件滿足時(也就是通過運算得到的結果為true時),才會執行當前任務。
示例如下(yaml/when.yaml):
--- - hosts: load-node,imgremote_user: roottasks:- name: "touch flag file"command: "touch /tmp/this_is_{{ ansible_distribution }}_system" when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == '6') or(ansible_distribution == "Debian" and ansible_distribution_major_version == '7')上述代碼中,ansible_distribution和ansible_distribution_major_version都是是Facts變量,分別表示Linux發行版和版本號
執行結果如下圖:
image.png4.2 循環語句
Playbook中的循環類型,如下表:
| 標準循環 | with_items |
| 遍歷字典 | with_dict |
| 遍歷目錄文件 | with_fileglob |
| 遍歷文件列表的內容 | with_file |
| 嵌套循環 | with_nested |
| 并行遍歷列表 | with_together |
| 遍歷列表和索引 | with_indexed_items |
| 重試循環 | until |
| 查找第一個匹配文件 | with_first_found |
| 隨機選擇 | with_random_choice |
| 在序列中循環 | with_sequence |
注意:列表中前三個為常用的循環語句。
4.2.1 標準循環 with_items
示例1(with_items_1.yaml):
--- - name: when and with_itemshosts: load-noderemote_user: rootgather_facts: false tasks:- name: Create thress groupsgroup: name=testgroup6 state=presentignore_errors: yesregister: excu_result- name: Append excu_result to tmp.txtshell: "echo {{ excu_result }} > /tmp/tmp.txt"- name: Create some usersuser: name={{ item }} group=testgroup6 state=presentwhen: excu_result|successwith_items:- testuser1- testuser2- testuser3釋義:
gather_facts: false表示運行此playbook時不收集目標主機的系統信息。因為默認此項是開啟的,每次運行playbook都會收集主機facts,這會影響playbook的運行速度。將gather_facts設為false即可關閉。
when:excu_result|success的意思為當變量excu_result執行結果為成功狀態,則執行當前的任務。其中success為Ansible內部過濾器方法,返回True代表命令運行成功。還有excu_result|failed表示excu_result執行結果為失敗狀態;excu_result|skipped表示excu_result執行被跳過。
with_items的值還可以寫成[testuser1, testuser2, testuser3]
示例2:
添加多個用戶,并將用戶加入不同的組內:
4.2.2 遍歷字典 with_dict
輸出用戶的姓名和電話:
--- - hosts: load-noderemote_user: roottasks:- name: print phone recordsdebug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.phone }})"with_dict: {'alice':{'name':'Alice Appleworth', 'phone':'13243252136'}, 'bob':{'name':'Bob Banarama', 'phone': '18766761211'}}注意:Playbook中對字典的循環,與python中對字典循環類似,取值方法也一樣。
4.2.3 遍歷目錄文件 with_fileglob
遍歷/root/sh/目錄下的所有文件,并將其拷貝至目標主機。
[root@LOCALHOST ~]# cat yaml/with_fileglob.yaml --- - hosts: DH-TESTremote_user: rootgather_facts: falsetasks:- name: create a directoryfile: path=/root/script state=directoryignore_errors: yesregister: result- name: copy some scriptscopy: src={{ item }} dest=/root/script owner=root mode=600when: result|successwith_fileglob:- /root/sh/*注意:with_fileglob匹配單個目錄中的所有文件,非遞歸匹配模式。
作者: Jeson老師
鏈接:http://www.imooc.com/article/22753
執行結果如下圖:
image.png4.2.4 其它循環
其它循環請參考 Jeson老師的手記
五、Playbook任務計時插件
Github地址: https://github.com/jlafon/ansible-profile
安裝這個插件后會顯示 ansible-playbook 執行每一個任務所花費的時間。
這個插件安裝很簡單,只需要簡單的三個命令即可完成安裝。在你的 playbook 文件的目錄下創建一個目錄,目錄名 callback_plugins 然后將下載的 profile_tasks.py 文件放到該目錄下即可。
# mkdir callback_plugins # cd callback_plugins # wget https://raw.githubusercontent.com/jlafon/ansible-profile/master/callback_plugins/profile_tasks.py image.png六、Playbook異常處理
6.1 ignore_errors
在有些情況下,一些必須運行的命令或腳本會報一些錯誤,而這些錯誤并不一定真的說明有問題,但是經常會給接下來要運行的任務造成困擾,甚至直接導致playbook運行中斷。
這時候,我們可以在相關任務中添加ignore_errors: true來屏蔽當前任務的報錯信息。ansible也將視該任務運行成功,不再報錯,這樣就不會對接下來要運行的任務造成額外困擾。但是要注意的是,我們不應過度依賴ignore_errors,因為它會隱藏所有的報錯信息,而應該把精力集中在尋找報錯的原因上面,這樣才能從根本上解決問題。
例如:
[root@LOCALHOST ~]# cat yaml/httpd.yaml --- - hosts: load-noderemote_user: rootvars:- pkg: httpdtasks:- name: "install httpd package."yum: name={{ pkg }} state=installed- name: "copy httpd configure file to remote host."copy: src=/root/config/httpd.conf dest=/etc/httpd/conf/httpd.confnotify: restart httpdignore_errors: true # 忽略錯誤- name: "start httpd service."tags:- start_httpdservice: name=httpd state=startedhandlers:- name: restart httpdservice: name=httpd state=restarted上述代碼中,任務"copy httpd configure file to remote host."中的src是一個不存在的路徑,所以此任務運行一定會出錯。這個playbook運行結果如下圖:
image.png從運行結果圖中可以看到有兩個...ignoring,表示忽略了這些錯誤,并繼續執行下面的任務。
6.2 failed_when
當滿足一定的條件時,主動拋出錯誤。
[root@LOCALHOST ~]# cat yaml/failed_when.yaml --- - hosts: DH-TESTremote_user: rootgather_facts: falsetasks:- name: get processshell: ps aux | wc -l register: process_countfailed_when: process_count > 3- name: touch a filefile: path=/tmp/test3.txt state=touch owner=root mode=0700failed_when: process_count > 3當進程數大于3時主動拋出錯誤,后續任務就不會執行了。如果不滿足條件,則不會拋出錯誤。
6.3 changed_when
[root@LOCALHOST ~]# cat yaml/changed_when.yaml --- - hosts: DH-TESTremote_user: rootgather_facts: falsetasks:- name: touch a filefile: path=/tmp/changed_test state=touch上述Playbook執行結果如下圖:
image.png如果想要關閉狀態改變的提示,則可以添加changed_when: false,如下:
[root@LOCALHOST ~]# cat yaml/changed_when.yaml --- - hosts: DH-TESTremote_user: rootgather_facts: falsetasks:- name: touch a filefile: path=/tmp/changed_testi2 state=touchchanged_when: false # 關閉狀態改變提示執行結果如下圖:
image.png七、Roles
Roles是一種利用在大型Playbook中的劇本配置模式,它有著自己特定的結構。用于層次性、結構化地組織playbook。roles能夠根據層次型結構自動裝載變量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。簡單來講,roles就是通過分別將變量、文件、任務、模板及處理器放置于單獨的目錄中,并可以便捷地include它們的一種機制。角色一般用于基于主機構建服務的場景中,但也可以是用于構建守護進程等場景中。
劇本roles設計思路:將公共任務、資源、變量等對象盡可能獨立。
一個roles的案例如下所示:
site.yml # 主入口文件 webservers.yml # webserver類型服務所用的劇本 dbservers.yml # 數據庫類型的服務所用的劇本 files/ # 存放通用的將要被上傳的文件 templates/ # 存放通用的模板文件 roles/ # roles目錄名稱是固定的common/ # 此目錄下的各個組件是所有角色共用的tasks/ # 存放通用的任務文件handlers/ # 存放通用的處理器文件vars/ # 存放通用的變量文件 meta/ # 存放通用的角色依賴文件webservers/ # 存放webserver類型的服務的各個組件 files/ # 存放webserver角色需要的上傳文件templates/ # 存放webserver角色需要的模板文件tasks/handlers/vars/meta/而在playbook中,可以這樣使用roles:
--- - hosts: webserversroles:- common- webservers也可以向roles傳遞參數,例如:
--- - hosts: webserversroles:- common- { role: foo_app_instance, dir: '/opt/a', port: 5000 }- { role: foo_app_instance, dir: '/opt/b', port: 5001 }甚至也可以條件式地使用roles,例如:
---- hosts: webserversroles:- { role: some_role, when: "ansible_os_family == 'RedHat'"7.1 創建role的步驟
(1) 創建以roles命名的目錄;
(2) 在roles目錄中分別創建以各角色名稱命名的目錄,如webservers等;
(3) 在每個角色命名的目錄中分別創建files、handlers、meta、tasks、templates和vars目錄;用不到的目錄可以創建為空目錄,也可以不創建;
(4) 在roles目錄的同級目錄下創建一個yaml文件,如:site.yml ,在此文件中調用各角色;
7.2 role內各目錄中可用的文件
tasks目錄:至少應該包含一個名為main.yml的文件,其定義了此角色的任務列表;此文件可以使用include包含其它的位于此目錄中的task文件;
files目錄:存放由copy或script等模塊調用的文件;
templates目錄:template模塊會自動在此目錄中尋找Jinja2模板文件;
handlers目錄:此目錄中應當包含一個main.yml文件,用于定義此角色用到的各handler;在handler中使用include包含的其它的handler文件也應該位于此目錄中;
vars目錄:應當包含一個main.yml文件,用于定義此角色用到的變量;
meta目錄:應當包含一個main.yml文件,用于定義此角色的特殊設定及其依賴關系;ansible 1.3及其以后的版本才支持;
default目錄:為當前角色設定默認變量時使用此目錄;應當包含一個main.yml文件;
7.3 簡單部署LAMP的Roles案例
先看一下這個roles的目錄結構:
[root@LOCALHOST ansible-examples-master]# tree [root@LOCALHOST ansible-examples-master]# tree lamp_simple lamp_simple ├── group_vars │ ├── all │ └── dbservers ├── hosts ├── LICENSE.md ├── README.md ├── roles │ ├── common │ │ ├── handlers │ │ │ └── main.yml │ │ ├── tasks │ │ │ └── main.yml │ │ └── templates │ │ └── ntp.conf.j2 │ ├── db │ │ ├── handlers │ │ │ └── main.yml │ │ ├── tasks │ │ │ └── main.yml │ │ └── templates │ │ └── my.cnf.j2 │ └── web │ ├── handlers │ │ └── main.yml │ ├── tasks │ │ ├── copy_code.yml │ │ ├── install_httpd.yml │ │ └── main.yml │ └── templates │ └── index.php.j2 └── site.yml14 directories, 17 files查看各個playbook的內容:
- 查看主機清單文件
# cat lamp_simple/hosts
- 查看主入口文件
# cat lamp_simeple/site.yml
- 查看變量文件:
# cat lamp_simple/group_vars/all
--- # Variables listed here are applicable to all host groupshttpd_port: 80 ntpserver: 192.168.1.2 repository: https://github.com/bennojoy/mywebapp.git# cat lamp_simple/group_vars/dbservers
--- # The variables file used by the playbooks in the dbservers group. # These don't have to be explicitly imported by vars_files: they are autopopulated.mysqlservice: mysqld mysql_port: 3306 dbuser: foouser dbname: foodb upassword: abc- 查看通用hanlder文件:
# cat lamp_simple/roles/common/handlers/main.yml
--- # Handler to handle common notifications. Handlers are called by other plays. # See http://docs.ansible.com/playbooks_intro.html for more information about handlers.- name: restart ntpservice: name=ntpd state=restarted- name: restart iptablesservice: name=iptables state=restarted- 查看通用tasks文件:
# cat lamp_simple/roles/common/tasks/main.yml
--- # This playbook contains common plays that will be run on all nodes.- name: Install ntpyum: name=ntp state=presenttags: ntp- name: Configure ntp filetemplate: src=ntp.conf.j2 dest=/etc/ntp.conftags: ntpnotify: restart ntp- name: Start the ntp serviceservice: name=ntpd state=started enabled=yestags: ntp- name: test to see if selinux is runningcommand: getenforceregister: sestatuschanged_when: false- 查看通用模板文件:
# cat lamp_simple/roles/common/templates/ntp.conf.j2
driftfile /var/lib/ntp/driftrestrict 127.0.0.1 restrict -6 ::1server {{ ntpserver }}includefile /etc/ntp/crypto/pwkeys /etc/ntp/keys- 查看db角色的handlers文件:
# cat lamp_simple/roles/db/handlers/main.yml
--- # Handler to handle DB tier notifications- name: restart mysqlservice: name=mysqld state=restarted- name: restart iptablesservice: name=iptables state=restarted[root@LOCALHOST ansible-examples-master]# cat lamp_simple/roles/db/handlers/main.yml --- # Handler to handle DB tier notifications- name: restart mysqlservice: name=mysqld state=restarted- name: restart iptablesservice: name=iptables state=restarted- 查看db角色的tasks文件:
# cat lamp_simple/roles/db/tasks/main.yml
--- # This playbook will install mysql and create db user and give permissions.- name: Install Mysql packageyum: name={{ item }} state=installedwith_items:- mysql-server- MySQL-python- libselinux-python- libsemanage-python- name: Configure SELinux to start mysql on any portseboolean: name=mysql_connect_any state=true persistent=yeswhen: sestatus.rc != 0- name: Create Mysql configuration filetemplate: src=my.cnf.j2 dest=/etc/my.cnfnotify:- restart mysql- name: Start Mysql Serviceservice: name=mysqld state=started enabled=yes- name: insert iptables rulelineinfile: dest=/etc/sysconfig/iptables state=present regexp="{{ mysql_port }}"insertafter="^:OUTPUT " line="-A INPUT -p tcp --dport {{ mysql_port }} -j ACCEPT"notify: restart iptables- name: Create Application Databasemysql_db: name={{ dbname }} state=present- name: Create Application DB Usermysql_user: name={{ dbuser }} password={{ upassword }} priv=*.*:ALL host='%' state=present- 查看db角色的模板文件:
# cat lamp_simple/roles/db/templates/my.cnf.j2
[mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 port={{ mysql_port }}[mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid- 查看web角色的handlers文件:
# cat lamp_simple/roles/web/handlers/main.yml
--- # Handler for the webtier: handlers are called by other plays. # See http://docs.ansible.com/playbooks_intro.html for more information about handlers.- name: restart iptablesservice: name=iptables state=restarted- 查看web角色的tasks文件:
# cat lamp_simple/roles/web/tasks/main.yml
--- - include: install_httpd.yml - include: copy_code.yml# cat lamp_simple/roles/web/tasks/install_httpd.yml
--- # These tasks install http and the php modules.- name: Install http and php etcyum: name={{ item }} state=presentwith_items:- httpd- php- php-mysql- git- libsemanage-python- libselinux-python- name: insert iptables rule for httpdlineinfile: dest=/etc/sysconfig/iptables create=yes state=present regexp="{{ httpd_port }}" insertafter="^:OUTPUT "line="-A INPUT -p tcp --dport {{ httpd_port }} -j ACCEPT"notify: restart iptables- name: http service stateservice: name=httpd state=started enabled=yes- name: Configure SELinux to allow httpd to connect to remote databaseseboolean: name=httpd_can_network_connect_db state=true persistent=yeswhen: sestatus.rc != 0`# cat lamp_simple/roles/web/tasks/copy_code.yml
--- # These tasks are responsible for copying the latest dev/production code from # the version control system.- name: Copy the code from repositorygit: repo={{ repository }} dest=/var/www/html/- name: Creates the index.php filetemplate: src=index.php.j2 dest=/var/www/html/index.php查看web角色的模板文件:
# cat lamp_simple/roles/web/templates/index.php.j2
<html><head><title>Ansible Application</title></head><body></br><a href=http://{{ ansible_default_ipv4.address }}/index.html>Homepage</a></br> <?php Print "Hello, World! I am a web server configured using Ansible and I am : ";echo exec('hostname');Print "</BR>"; echo "List of Databases: </BR>";{% for host in groups['dbservers'] %}$link = mysqli_connect('{{ hostvars[host].ansible_default_ipv4.address }}', '{{ hostvars[host].dbuser }}', '{{ hostvars[host].upassword }}') or die(mysqli_connect_error($link));{% endfor %}$res = mysqli_query($link, "SHOW DATABASES;");while ($row = mysqli_fetch_assoc($res)) {echo $row['Database'] . "\n";} ?> </body> </html>執行這個roles
# ansile-playbook -i lamp_simple/hosts lamp_simple/site.yml
八、Ansible Galaxy
Ansible Galaxy是Ansible官方Roles分享平臺(galaxy.ansible.com),在Galaxy平臺上所有人可以免費上傳或下載Roles,在這里好的技巧、思想、架構得以積累和傳播。
8.1 ansible-galaxy命令的用法:
[root@LOCALHOST tasks]# ansible-galaxy --help Usage: ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...Options:-h, --help show this help message and exit-c, --ignore-certs Ignore SSL certificate validation errors.-s API_SERVER, --server=API_SERVERThe API server destination-v, --verbose verbose mode (-vvv for more, -vvvv to enableconnection debugging)--version show program's version number and exitSee 'ansible-galaxy <command> --help' for more information on a specific command.搜索lamp相關的roles:
命令:ansible-galaxy search lamp
結果如下圖:
來安裝一個搜索到的角色:
命令:ansible-galaxy install vivaserver.lamp
根據輸出提示,安裝的role放在/root/.ansible/roles/vivaserver.lamp
查看這個role目錄結構:
[root@LOCALHOST vivaserver.lamp]# tree /root/.ansible/roles/vivaserver.lamp/ /root/.ansible/roles/vivaserver.lamp/ ├── files │ ├── favicon.ico │ └── www.html ├── LICENSE ├── meta │ └── main.yml ├── README.md ├── screenshot.png └── tasks└── main.yml3 directories, 7 files按作者搜索roles:
[root@LOCALHOST ~]# ansible-galaxy search zabbix --author dj-wasabiFound 5 roles matching your search:Name Description---- -----------dj-wasabi.zabbix-javagateway Installing and maintaining zabbix-javagateway for RedHat/Debian/Ubuntu.dj-wasabi.zabbix-server Installing and maintaining zabbix-server for RedHat/Debian/Ubuntu.dj-wasabi.zabbix-web Installing and maintaining zabbix-web for RedHat/Debian/Ubuntu.dj-wasabi.zabbix-proxy Installing and maintaining zabbix-proxy for RedHat/Debian/Ubuntu.dj-wasabi.zabbix-agent Installing and maintaining zabbix-agent for RedHat/Debian/Ubuntu.上述命令中 dj-wasabi是作者的用戶名
8.2 批量安裝多個roles
# cat roles.txt user1.role1,v1.0.0 user2.role2,v0.5 user2.role3安裝:
# ansible-galaxy install -r roles.txt總結
以上是生活随笔為你收集整理的Ansible第二篇:ansible-playbook的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分布式单点登录框架XXL-SSO
- 下一篇: MongoDB ( 五 )高级_索引