--- - hosts: test #指定主機組 remote_user: root #指定ssh登陸的用戶 tasks: - name: test server ping:
使用sudo切換html
--- - hosts: test remote_user: root become: yes #become參數在2.6版本用於指定sudo become_user: admin #sudo的用戶 tasks: - name: test server ping:
tasks: - name: task_name #任務名稱 module: module_args #使用的模塊,以及模塊參數,列如yum: name=nginx state=present
--- - hosts: 10.1.210.51 remote_user: root tasks: - name: install package #使用yum安裝包 yum: name=httpd state=present - name: start httpd #啓動該服務 service: name=httpd state=started
執行:nginx
--- - hosts: 10.1.210.53 remote_user: root tasks: - name: test facts var shell: echo "{{ ansible_all_ipv4_addresses }}" > host_ip.txt
#單獨主機變量,優先級高於公共變量 host varname=value #主機組變量 [groupname:vars] #爲指定主機組自定義變量,vars爲關鍵字 varname=value
列如:web
vi /etc/ansible/hosts 10.1.210.51 business=card #變量名爲business值爲card 10.1.210.53 [dev] 10.1.210.33 10.1.210.32 [dev:vars] #組變量定義 myname=wd
示例:shell
[root@app52 ~]# cat test.yaml --- - hosts: 10.1.210.51 remote_user: root tasks: - name: test facts from hosts debug: var=business #使用debug打印變量的值,var參數測試變量不須要用{{ }}
運行playbook:json
3.playbook中定義變量vim
格式:服務器
vars: - varname1: value1 - varname2: value2
示例:app
--- - hosts: 10.1.210.51 remote_user: root vars: - pkg_name: httpd - pkg_cmd: /usr/sbin/httpd tasks: - name: restart httpd service: name={{ pkg_name }} state=restarted - name: copy cmd copy: src={{ pkg_cmd }} dest=/tmp/
運行playbook:ssh
4.命令行中定義變量curl
ansible-playbook -e 'varname=value’ #該方式定義的變量優先級最高
5.經過文件引用變量。
[root@app52 ~]# cat /tmp/myvars.yml var1: value1 var2: value2
playbook中使用
--- - hosts: 10.1.210.51 remote_user: root vars_files: - /tmp/myvars.yml #變量文件 tasks: - name: test myvar debug: msg="{{ var1 }}/{{ var2 }}" #這裏的var1變量和var2變量來自於文件/tmp/myvars.yml
運行結果:
6.在roles中定義變量,後續在介紹roles在講解。
vim /tmp/nginx.conf.j2 user nginx; worker_processes {{ ansible_processor_vcpus }}; #使用cpu個數做爲woeker數量 error_log /var/log/nginx_error.log crit; pid /var/run/nginx.pid; include /usr/share/nginx/modules/*.conf; worker_rlimit_nofile 65535; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; gzip on; server { listen 80; server_name {{ ansible_fqdn }} #使用主機名做爲hostname access_log /var/log/access.log; error_log /var/log/error.log; } }
2.playbook中使用
--- - hosts: 10.1.210.53 remote_user: root vars: - package_name: nginx - config_path: /etc/nginx/nginx.conf tasks: - name: install epel yum: name=epel-release - name: install package yum: name={{ package_name }} - name: copy config file template: src=/tmp/nginx.conf.j2 dest={{ config_path }} backup=yes #backup用於備份 - name: start service service: name={{ package_name }} state=started
運行playbook
- hosts: 10.1.210.53 remote_user: root vars: - package_name: nginx - config_path: /etc/nginx/nginx.conf tasks: - name: install epel yum: name=epel-release - name: install package yum: name={{ package_name }} - name: copy config file template: src=/tmp/nginx.conf.j2 dest={{ config_path }} backup=yes notify: #當配置文件發生變化時候,通知hanler觸發task - stop service - start service handlers: - name: stop service service: name={{ package_name }} state=stopped - name: start service service: name={{ package_name }} state=started
運行playbook
--- - hosts: 10.1.210.51 remote_user: root tasks: - name: exec tag1 shell: cat /etc/passwd tags: tag1 - name: exec tag2 file: path=/tmp/b.txt state=touch tags: tag2 - name: view password shell: cat /etc/passwd
列出tag
指定運行某個tag任務
跳過tag任務運行
從以上結果可看出,跳過了tag1和tag2任務,只運行了view password任務。
示例一:使用facts變量測試
tasks: - name: "shut down Debian flavored systems" command: /sbin/shutdown -t now when: ansible_facts['os_family'] == "Debian" #當操做系統是Debian才執行該任務
示例二:使用邏輯運算進行多條件判斷
tasks: - name: "shut down CentOS 6 and Debian 7 systems" command: /sbin/shutdown -t now when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or (ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "7")
兩個條件使用and還能夠以下表示
tasks: - name: "shut down CentOS 6 systems" command: /sbin/shutdown -t now when: - ansible_facts['distribution'] == "CentOS" - ansible_facts['distribution_major_version'] == "6" #同時知足系統是CentOS且版本是6
示例三:根據任務的執行結果狀態來判斷任務是否執行,這裏使用register來保存了任務執行結果,後續會介紹。
--- - hosts: 10.1.210.51 name: test when remote_user: root tasks: - name: task1 command: /bin/false register: result #將本次任務結果保存在變量中 ignore_errors: True #忽略錯誤執行,可確保任務錯誤也能執行下一個任務 - name: pre task failed file: path=/tmp/failed.txt state=touch when: result is failed #判斷result結果是不是failed - name: pre task successed state=touch file: path=/tmp/success.txt when: result is succeeded #判斷result結果是不是succeeded - name: pre task skipped state=touch file: path=/tmp/skip.txt when: result is skipped #判斷結果是不是skipped
運行一下:
如上圖,紅色的部分任務都跳過了未執行,這是由於result結果是failded,因此只執行了「pre task failed」這個任務。
示例4:使用變量進行測試
--- - hosts: 10.1.210.51 name: test var when remote_user: root vars: - flag: true #變量定義 tasks: - name: test server ping: when: flag #判斷變量flag爲true執行 - name: create file file: path=/tmp/myfile.txt state=touch when: not flag #變量flag不爲true執行
執行結果:
一樣能夠看到create file 任務被跳過了。
register註冊變量,用於保存任務結果,可用於保存配置或when關鍵字判斷,這是很是有用了,在上個示例中使用了任務結果做爲判斷條件。例如,你能夠將文件中的配置或者json內容保存在變量中,能夠供後續使用:
--- - hosts: 10.1.210.51 name: test register remote_user: root tasks: - name: read conf shell: cat /tmp/nginx.conf register: nginx_conf #註冊變量 - name: copy conf copy: content={{ nginx_conf }} dest=/etc/nginx/nginx.conf #使用變量
還能夠配合循環使用,如下示例展現了批量建立軟連接:
- name: registered variable usage as a loop list hosts: all tasks: - name: retrieve the list of home directories command: ls /home register: home_dirs - name: add home dirs to the backup spooler file: path: /mnt/bkspool/{{ item }} src: /home/{{ item }} state: link loop: "{{ home_dirs.stdout_lines }}"
--- - hosts: localhost remote_user: root tasks: - name: create user user: name={{ item }} state=present with_items: - zabbix - admin
執行結果:
示例二:循環中使用register註冊變量
- hosts: localhost remote_user: root tasks: - command: echo {{ item }} with_items: [ 0, 2, 4, 6, 8, 10 ] register: num - debug: msg="{% for i in num.results %} {{i.stdout}} {% endfor %}"
注意,將with_items迭代後的結果註冊爲變量時,其註冊結果也是列表式的,且其key爲"results"。具體的結果比較長,可使用debug模塊的var或msg參數觀察變量的結果。以上示例運行結果以下:
2.with_dict迭代字典
--- - hosts: localhost remote_user: root tasks: - debug: msg="{{ item.key }} / {{ item.value }}" with_dict: { ip: 10.1.210.51, hostname: app52, gateway: 10.1.210.1}
以上示例中字典是已經存在了,除此以外字典能夠來源於變量、facts等。例如使用facts進行迭代
--- - hosts: localhost remote_user: root tasks: - debug: msg="{{item.key}} / {{item.value}}" with_dict: "{{ ansible_cmdline }}"
若是將全部的play都寫在一個playbook中,很容易致使這個playbook文件變得臃腫龐大,且不易讀。所以,能夠將多個不一樣任務分別寫在不一樣的playbook中,而後使用include將其包含進去便可。include能夠導入兩種文件:導入task文件、導入playbook。
示例:建立task.yml任務列表
vim task.yml - name: task1 debug: msg="exec task1" - name: task2 debug: msg="exec task2"
在目標playbook中倒入任務
---
- hosts: 10.1.210.51
remote_user: root
tasks:
- include: task.yml
執行playbook:
示例2:直接導入其餘playbook,不過在ansible2.8將移除,2.8中將使用import_playbook
--- - hosts: 10.1.210.51 remote_user: root tasks: - include: task.yml - include: test_when.yml - include: test_with.yml
例如:一個nginx角色的目錄結構能夠是:
.
└── nginx
├── default
├── files
├── handlers
├── meta
├── tasks
├── templates
└── vars
多個role目錄:
├── httpd #http role │ ├── default │ ├── files │ ├── handlers │ ├── meta │ ├── tasks │ ├── templates │ └── vars └── nginx #nginx role ├── default ├── files ├── handlers ├── meta ├── tasks ├── templates └── vars
1、建立對應的目錄結構:
[root@app52 ~]# mkdir -pv roles/nginx/{files,templates,vars,tasks,handlers,meta,default} mkdir: 已建立目錄 "roles" mkdir: 已建立目錄 "roles/nginx" mkdir: 已建立目錄 "roles/nginx/files" mkdir: 已建立目錄 "roles/nginx/templates" mkdir: 已建立目錄 "roles/nginx/vars" mkdir: 已建立目錄 "roles/nginx/tasks" mkdir: 已建立目錄 "roles/nginx/handlers" mkdir: 已建立目錄 "roles/nginx/meta" mkdir: 已建立目錄 "roles/nginx/default」
2、定義變量
[root@app52 ~]# vi roles/nginx/vars/main.yml pkg_name: nginx #安裝包名稱 listen_port: 80 #監聽端口
3、編寫任務
這裏能夠把任務模塊化,最後在main.yml包含它們
[root@app52 ~]# vi roles/nginx/tasks/yum.yml - name: install epel yum: name=epel-release state=present - name: install nginx pkg yum: name={{ pkg_name }} state=present [root@app52 ~]# vi roles/nginx/tasks/copy.yml - name: copy nginx.conf template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf - name: copy index.html copy: src=index.html dest=/var/www/html/ notify: reload [root@app52 ~]# vi roles/nginx/tasks/start_service.yml - name: start nginx service: name=nginx state=restarted [root@app52 ~]# vi roles/nginx/tasks/main.yml - include: yum.yml - include: copy.yml - include: start_service.yml
4、準備配置文件以及index.html
#index.html [root@app52 ~]# vi roles/nginx/files/index.html <h1>Hello wd</h1> #配置文件模版 [root@app52 ~]# vi roles/nginx/templates/nginx.conf.j2 user nginx; worker_processes {{ ansible_processor_vcpus }}; #使用cpu個數做爲woeker數量 error_log /var/log/nginx_error.log crit; pid /var/run/nginx.pid; include /usr/share/nginx/modules/*.conf; worker_rlimit_nofile 65535; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; gzip on; server { listen {{ listen_port }}; server_name {{ ansible_all_ipv4_addresses[0] }} ; #使用IP地址做爲server name root /var/www/html ; access_log /var/log/access.log; error_log /var/log/error.log; } }
5、編寫handlers
若是在task中使用了notify,則就須要寫對應的handlers,上述我使用了reload這個handler,因此這裏須要定義:
[root@app52 ~]# vi roles/nginx/handlers/main.yml - name: reload service: name=nginx state=reloaded
6、在角色同級目錄編寫playbook引入角色
[root@app52 ~]# vi roles/install_nginx.yml - hosts: web #指定使用role的主機或主機組 remote_user: root #指定用戶 roles: #使用的role,能夠有多個 - nginx
最後的目錄結構爲:
[root@app52 ~]# tree roles/ roles/ ├── install_nginx.yml └── nginx ├── default ├── files │ └── index.html ├── handlers │ └── main.yml ├── meta ├── tasks │ ├── copy.yml │ ├── main.yml │ ├── start_service.yml │ └── yum.yml ├── templates │ └── nginx.conf.j2 └── vars └── main.yml 8 directories, 9 files
7、運行playbook並測試
如紅色部分,curl測試nginx 安裝成功。