天天看點

ansible - PlayBookPlayBook-(1) YAML語言介紹PlayBookplaybook-(2)playbook的其他元素playbook-(3) 角色

PlayBook-(1)

 YAML語言介紹

參考連結: http://docs.ansible.com/ansible/YAMLSyntax.html ansible裡面的配置檔案是通過YMAL檔案來實作的。下面是YMAL語言的特點:

  1. 可讀性高
  2. 和腳本語言互動好
  3. 使用的是實作語言的資料類型
  4. 有一個一緻的資訊模型
  5. 基于流來處理
  6. 表達能力強,可拓展性比較好

YAML語言文法特點:

  •    下面是一個介紹YAML的 小例子:
  1. name: Tom
  2. age: 35
  3. spouce:
  4. name: Tik
  5. age: 34
  6. children:
  7. - name: JK
  8. age: 19
  9. - name: HK
  10. age: 12

        說明:表示Tom今年35歲,有一個幸福的四口之家,妻子叫做Tik,今年34歲;倆孩子JK和HK活潑可愛。

   接下來就把這上面的代碼儲存成一個test.yaml的檔案放到和test.py同級的目錄下,并且用python2.7執行即可。 python代碼:    

  1. #!/usr/bin/python
  2. import yaml
  3. file = open('test.yaml')
  4. read_file = yaml.load(file)
  5. print read_file

執行結果:會傳遞出一個字典的格式出來

  1. [[email protected] ~]# python test.py
  2. {'age': 35, 'spouce': {'age': 34, 'name': 'Tik'}, 'name': 'Tom', 'children': [{'age': 19, 'name': 'JK'}, {'age': 12, 'name': 'HK'}]}
  • YAML檔案最常見的層次和結構,對應的就是python中的字典和清單兩種類型:

    還是用上面的python讀取檔案的例子來試試,生成清單 

  1. [[email protected] ~]# cat test2.yaml #yaml檔案
  2. - apple
  3. - banana
  4. - orange
  5. - pear
  6. [[email protected] ~]# cat test2.py #python檔案
  7. #!/usr/bin/python
  8. import yaml
  9. file = open('test2.yaml')
  10. read_file = yaml.load(file)
  11. print read_file
  12. [[email protected] ~]# python test2.py #執行結果
  13. ['apple', 'banana', 'orange', 'pear']

     再來一發玩玩吧:

  1. node_a:
  2. counttime: 300
  3. external:
  4. iface: eth0
  5. port: 5566
  6. internal:
  7. iface: eth1
  8. port: 5577
  9. broadcast:
  10. client: 1000
  11. server: 99
  12. node_b:
  13. 0:
  14. ip: 10.1.1.1
  15. name: b1
  16. 1:
  17. ip: 10.1.1.2
  18. name: b2

       不行,老哥最後來一發

  1. name: Example Developer
  2. job: DeveLoper
  3. skill: Elipt
  4. employed: True
  5. foods:
  6. - apple
  7. - orange
  8. - mango
  9. language:
  10. ruby: Elit
  11. python: Elit
  12. dotnet: Lame

PlayBook

    需要一個yaml格式的檔案編排一個任務去執行。

  • 組成部分(核心元素):
    • hosts
    • users
    • 任務
    • 變量
    • 模闆:包含模闆文法的文本檔案
    • 處理器:有特定條件觸發的任務
    • 角色
  • 基本元件:
    • hosts:運作指定任務的目标主機
    • remote_user:遠端主機上執行任務的使用者
    • sudo_user:可選方式
    • tasks:任務清單
      • 子產品,子產品參數
      • 格式:
        • action:module arguments
        • module:arguments
  • 簡單的小案例:
    •  建立使用者的小playbook:
  1. - hosts: all
  2. remote_user: root
  3. tasks:
  4. - name: create a user user3 #任務名稱
  5. user: name=user3 system=true uid=307 #執行任務
  6. - name: create a user user4 #任務名稱
  7. user: name=user4 system=true uid=308
  • 檢查playbook
  1. [[email protected] ~]# ansible-playbook --check first.yaml
  2. PLAY [all] *********************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.7]
  5. ok: [172.1.1.12]
  6. TASK [create a user user3] *****************************************************
  7. changed: [172.1.1.7]
  8. changed: [172.1.1.12]
  9. TASK [create a user user4] *****************************************************
  10. changed: [172.1.1.7]
  11. changed: [172.1.1.12]
  12. PLAY RECAP *********************************************************************
  13. 172.1.1.12 : ok=3 changed=2 unreachable=0 failed=0
  14. 172.1.1.7 : ok=3 changed=2 unreachable=0 failed=0
  15. [[email protected] ~]# ansible-playbook --list-hosts first.yaml
  16. playbook: first.yaml
  17. play #1 (all): all TAGS: []
  18. pattern: [u'all']
  19. hosts (2):
  20. 172.1.1.12
  21. 172.1.1.7
  • 運作playbook
  1. [[email protected] ~]# ansible-playbook first.yaml #執行
  2. PLAY [all] *********************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.12]
  5. ok: [172.1.1.7]
  6. TASK [create a user user3] *****************************************************
  7. changed: [172.1.1.7]
  8. changed: [172.1.1.12]
  9. TASK [create a user user4] *****************************************************
  10. changed: [172.1.1.7]
  11. changed: [172.1.1.12]
  12. PLAY RECAP *********************************************************************
  13. 172.1.1.12 : ok=3 changed=2 unreachable=0 failed=0
  14. 172.1.1.7 : ok=3 changed=2 unreachable=0 failed=0

安裝httpd使其監聽在8080端口,       yaml檔案如下

  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install httpd
  5. yum: name=httpd state=present
  6. - name: copy configure file
  7. copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  8. - name: start service
  9. service: name=httpd state=started
  10. - name: execute ss command
  11. shell: ss -tnl | grep 80

      準備好httpd的配置檔案:       測試執行:ansible-playbook --check httpd.yaml       正式執行:ansible-playbook httpd.yaml

  • handlers:在特定條件下觸發條件,重新開機服務
    • 接收到其他任務的通知時才被觸發
  • task:任務的狀态在運作後為chenged時,可通過notify通知給相應的handles
    • 通過tags打标簽,可以結合ansible-playbook -t 标簽名稱 yaml檔案執行

改變配置檔案之後重新開機httpd服務:

  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install httpd
  5. yum: name=httpd state=present
  6. - name: copy configure file
  7. copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  8. notify: restart httpd
  9. - name: start service
  10. service: name=httpd state=started
  11. handlers:
  12. - name: restart httpd
  13. service: name=httpd state=restarted
  • tag:打标簽機制---通過執行标簽對應的任務片段執行對應的task
  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install httpd
  5. yum: name=httpd state=present
  6. tags: insthttpd
  7. - name: copy configure file
  8. copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  9. tags: instconf
  10. notify: restart httpd
  11. - name: start service
  12. service: name=httpd state=started
  13. tags: restarthttpd
  14. handlers:
  15. - name: restart httpd
  16. service: name=httpd state=restarted

測試:ansible-playbook --check -t restarthttpd httpd3.yaml 執行:ansible-playbook -t restarthtpd httpd3.yaml

  • variables:變量,隻能以字母開頭
    • facts:用setup子產品來擷取facts的;可以直接調用
    • ansible-playbook指令的指令行中的自定義變量
      • -e VARS,--extra-vars=VARS
    • 通過roles也能傳遞變量
    • Host Inventory:實作想不通的主機傳遞不同的變量
      • 向不同的主機傳遞不同的變量:IP/HOSTNAME varrable=value1 value2
      • 向組中的主機傳遞相同的變量:
        • [groupnames:vars]

                                  variable=value

  • inventory參數:用于定義遠端連接配接目标主機需要的參數,而非傳遞給playbook的參數
    • ansible_ssh_host
    • ansible_ssh_porty
    • ansible_ssh_pass
    • ansible_ssh_user
    • ansible_sudo_pass
  • 模闆:

實作自定義安裝軟體包{{ pkgnames }}:

  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install {{ pkgs }}
  5. yum: name={{ pkgs }} state=present

測試:ansible-playbook --check -e pkgs=memcached install_var.yaml  執行:ansible-playbook -e pkgs=memcached install_var.yaml 實作自定義修改主機名的操作: 1. 首先修改/etc/ansbile/hosts檔案:

  1. [[email protected] ~]# vim /etc/ansible/hosts
  2. [webservers]
  3. 172.1.1.12 hname=www1
  4. 172.1.1.7 hname=www2

2.其次編寫hostname.yaml檔案

  1. [[email protected] ~]# vim hostname.yaml
  2. - hosts: webservers remote_user: root tasks: - name: set hostname hostname: name={{ hname }}

3.測試: ansible-playbook --check hostname.yaml  4.執行: ansible-playbook hostname.yaml 

playbook-(2)

playbook的其他元素

變量

  • 變量:一定要記得{{ varname }}
    • ansible facts
    • ansible-playbook -e "var=value"
      • host variable: host inventory
      • group variable:

                                [groupname:vars]                                 var=value

  • roles
  • 變量的調用:{{ variable }}

模闆(templates)

  • 文本檔案,嵌套有腳本(使用模闆程式設計語言編寫)
  • jinjs2:基于Python
    • 字面量:
      • 字元串:使用單引号或者雙引号
      • 數字:整數和浮點數
      • 清單
      • 元組
      • 字典
      • 布爾值
    • 算術運算:+    -    *     /           //      %       **n
    • 比較操作:==     !=           >              <                         >=                       <=
    • 邏輯運算:and           or                    not
  • template子產品:基于模闆的方式生成一個檔案複制到遠端主機
    • *src:jinjia2檔案路徑(server端)
    • *dest:用戶端檔案存放路徑

擷取虛拟CPU數量:

  1. [[email protected] ~]# ansible all -m setup | grep ansible_processor_vcpus
  2. "ansible_processor_vcpus": 1,
  3. "ansible_processor_vcpus": 1,

nginx使用epel源安裝執行個體:         1.在主要端下載下傳好nginx的epel檔案:

  1. [[email protected] ~]# cat nginx.repo
  2. [nginx]
  3. name=nginx repo
  4. baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
  5. gpgcheck=0
  6. enabled=1

        2.然後epel檔案推送到被控端

  1. [[email protected] ~]# ansible all -m copy -a "src=~/nginx.repo dest=/etc/yum.repos.d/"

        3.主要端執行安裝指令

  1. [[email protected] ~]# ansible all -m yum -a "name=nginx state=present"

       4.配置檔案模闆推送                 * 遠端複制一個nginx.conf配置檔案來當做模闆檔案,并重命名

  1. [[email protected] ~]# scp 172.1.1.12:/etc/nginx/nginx.conf ./
  2. nginx.conf 100% 643 0.6KB/s 00:00
  3. [[email protected] ~]# mv nginx.conf nginx.conf.j2

                *編輯模闆檔案:

  1. [[email protected] ~]# egrep -v "^#|^$" nginx.conf.j2 user nginx; worker_processes {{ ansible_processor_vcpus }}; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; server { listen {{ http_port }}; server_name localhost; charset koi8-r; location / { root /usr/share/nginx/html; index index.html index.htm; } } }

                 *編輯hosts檔案:   

  1. [[email protected] ~]# cat /etc/ansible/hosts
  2. # This is the default ansible 'hosts' file.
  3. #
  4. # It should live in /etc/ansible/hosts
  5. #
  6. # - Comments begin with the '#' character
  7. # - Blank lines are ignored
  8. # - Groups of hosts are delimited by [header] elements
  9. # - You can enter hostnames or ip addresses
  10. # - A hostname/ip can be a member of multiple groups
  11. [webservers]
  12. 172.1.1.12 hname=www1
  13. 172.1.1.7 hname=www2
  14. [webservers:vars]
  15. http_port=8080

    或者寫成這樣以便區分:

  1. [[email protected] ~]# cat /etc/ansible/hosts
  2. # This is the default ansible 'hosts' file.
  3. #
  4. # It should live in /etc/ansible/hosts
  5. #
  6. # - Comments begin with the '#' character
  7. # - Blank lines are ignored
  8. # - Groups of hosts are delimited by [header] elements
  9. # - You can enter hostnames or ip addresses
  10. # - A hostname/ip can be a member of multiple groups
  11. [webservers]
  12. 172.1.1.12 http_port=80
  13. 172.1.1.7 http_port=8080

                 *編輯yaml檔案:

  1. [[email protected] ~]# vim nginx.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. tasks:
  5. - name: install nginx
  6. yum: name=nginx state=present
  7. - name: install conf file
  8. template: src=~/nginx.conf.j2 dest=/etc/nginx/nginx.conf
  9. notify: restart nginx
  10. tags: instconf
  11. - name: start nginx service
  12. service: name=nginx state=started
  13. handlers:
  14. - name: restart nginx
  15. service: name=nginx state=restarted

                    *檢測執行:

  1. [[email protected] ~]# ansible-playbook --check nginx.yaml
  2. PLAY [webservers] **************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.7]
  5. ok: [172.1.1.12]
  6. TASK [install nginx] ***********************************************************
  7. ok: [172.1.1.7]
  8. ok: [172.1.1.12]
  9. TASK [install conf file] *******************************************************
  10. ok: [172.1.1.7]
  11. ok: [172.1.1.12]
  12. TASK [start nginx service] *****************************************************
  13. changed: [172.1.1.7]
  14. changed: [172.1.1.12]
  15. PLAY RECAP *********************************************************************
  16. 172.1.1.12 : ok=4 changed=1 unreachable=0 failed=0
  17. 172.1.1.7 : ok=4 changed=1 unreachable=0 failed=0

    沒有報錯的話就直接執行:ansible-playbook nginx.yaml

  • 條件判斷:
    • when語句:在task中使用,jinja2文法格式
    • tasks格式如下:
  1. tasks:
  2. - name: install conf to centos7
  3. templete: src=~/nginx.c7.j2 dest=/etc/nginx/
  4. when: ansible_distribution_major_version == "7"
  5. - name: install conf to centos7
  6. templete: src=~/nginx.c6.j2 dest=/etc/nginx/
  7. when: ansible_distribution_major_version == "6"

根據作業系統的不同來配置和推送不同的配置檔案:        *根據不同的作業系統拉取不同的配置檔案:

  1. [[email protected] ~]# scp 172.1.1.7:/etc/nginx/nginx.conf ./nginx.conf.c6.j2
  2. nginx.conf 100% 700 0.7KB/s 00:00
  3. [[email protected] ~]# scp 172.1.1.12:/etc/nginx/nginx.conf ./nginx.conf.c7.j2
  4. nginx.conf 100% 702 0.7KB/s 00:00

       *調整 nginx . conf . c6 . j2的配置檔案;仍然要修改其worker_processor 對應的變量為: worker_processes {{ ansible_processor_vcpus }}; listen {{ http_port }};

*調整nginx.yaml配置:

  1. [[email protected] ~]# vim nginx.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. tasks:
  5. - name: install nginx
  6. yum: name=nginx state=present
  7. - name: install conf file
  8. template: src=~/nginx.conf.c7.j2 dest=/etc/nginx/nginx.conf
  9. when: ansible_distribution_major_version == "7"
  10. notify: restart nginx
  11. tags: instconf
  12. - name: install conf file
  13. template: src=~/nginx.conf.c6.j2 dest=/etc/nginx/nginx.conf
  14. when: ansible_distribution_major_version == "6"
  15. notify: restart nginx
  16. tags: instconf
  17. - name: start nginx service
  18. service: name=nginx state=started
  19. handlers:
  20. - name: restart nginx
  21. service: name=nginx state=restarted

*執行檢查程式:ansible-playbook --check nginx.yaml *無報錯開始執行程式:ansible-playbook nginx.yaml

  • 循環:疊代操作,需要執行重複執行的任務
    • 對疊帶項的引用,固定變量名為"item"
    • 而後,要在task中使用with_items給定要疊代的元素清單
    • with_items的形式有兩種:
      • 清單方法
      • 字典方法

事例:

  1. - name: install some package
  2. yum: name={{ items }} state=present
  3. with_items:
  4. - nginx
  5. - memcached
  6. - php-fpm

疊代安裝程式事例:         *編寫yaml檔案:

  1. - host : all
  2. remote_user: root
  3. tasks:
  4. - name: install some packages
  5. yum: name={{ item }} state=present
  6. with_items:
  7. - nginx
  8. - memcached
  9. - php-fpm

       開始測試:ansible-playbook --check loop_test.yaml        執行任務:ansible-playbook loop_test.yaml 疊代建立使用者群組,并進行關聯( with_items的形式有兩種的具體應用)        *編寫yaml檔案:

  1. [[email protected] ~]#vim with_items.yaml
  2. - host: all
  3. remote_user: root
  4. tasks:
  5. - name: add some groups
  6. group: name={{ item }} state=present
  7. with_items:
  8. - group11
  9. - group12
  10. - group13
  11. - name: add some users
  12. user: name={{ item.name }} group={{ item.group }} state=present
  13. with_items:
  14. - { name: 'user11',group: 'group11' }
  15. - { name: 'user11',group: 'group11' }
  16. - { name: 'user11',group: 'group11' }

        *測試執行:ansible-playbook --check  with_items . yaml

*無報錯最終執行:ansible-playbook with_items.yaml

playbook-(3)

角色

  •   在網絡中的主機如果要協調的過程,實作不同的分組之間的公共任務的執行,以減少重複執行。比如時間同步;
  •    每一個角色就是一個目錄;

   (1): 角色的集合:

  1. roles/
  2. mysql/
  3. httpd/
  4. nginx/
  5. memcached/

   (2):  每個角色,以特定的層級目錄結構進行 組織

  1. mysql/
  2. files/ #存放由copy或者script子產品等調用的檔案
  3. templates/ #template子產品查找所需要的模闆檔案位置
  4. tasks/ #至少包含一個main.yaml檔案,其他檔案的執行需要通過include包含
  5. handlers/ #至少包含一個main.yaml的檔案, 其他檔案的執行需要通過include包含
  6. vars/ # 至少包含一個main.yaml的檔案, 其他檔案的執行需要通過include包含
  7. meta/ #至少包含一個main.yaml的檔案,定義目前角色的特殊設定及其依賴關系
  8. default/ #設定預設變量時使用此目錄中的main.yaml檔案

 (3): 在playbook中調用角色:通過roles指定的任務,然後從上面的兩個對應的角色集合中找到自己的角色和對應的任務進行執行            

  1. - hosts: webservers
  2. remoute_user: root
  3. roles:
  4. - mysql
  5. - ngins
  6. - memcached
  7. - redis

  執行個體:建立一個nginx執行個體

(1)task檔案

  1. [[email protected] ~]# mkdir /etc/ansible/roles/nginx/{files,tasks,templates,handlers,vars,default,meta} -pv
  2. [[email protected] ~]# cd /etc/ansible/roles/nginx/
  3. [[email protected] nginx]# vim tasks/main.yaml
  4. - name: install nginx package
  5. yum: name=nginx state=present
  6. - name: install conf file
  7. template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  8. - name: start nginx
  9. service: name=nginx state=started enabled=true

(2)templates檔案

  1. [[email protected] ~]# vim /etc/ansible/roles/nginx/templates/nginx.conf.j2
  2. user nginx;
  3. worker_processes {{ ansible_processor_vcpus }};
  4. events {
  5. worker_connections 1024;
  6. }
  7. http {
  8. include /etc/nginx/mime.types;
  9. default_type application/octet-stream;
  10. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11. '$status $body_bytes_sent "$http_referer" '
  12. '"$http_user_agent" "$http_x_forwarded_for"';
  13. access_log /var/log/nginx/access.log main;
  14. sendfile on;
  15. #tcp_nopush on;
  16. keepalive_timeout 65;
  17. #gzip on;
  18. server {
  19. listen {{ http_port }};
  20. server_name localhost;
  21. charset koi8-r;
  22. location / {
  23. root /usr/share/nginx/html;
  24. index index.html index.htm;
  25. }
  26. }
  27. }

(3)寫一個role檔案

  1. [[email protected] ~]# mkdir /ansible
  2. [[email protected] ansible]# vim nginx.yaml
  3. - hosts: webservers
  4. remote_user: root
  5. roles:
  6. - nginx

(4)删除被控主機的nginx服務和配置

  1. [[email protected] ~]# rpm -e nginx
  2. warning: /etc/nginx/nginx.conf saved as /etc/nginx/nginx.conf.rpmsave
  3. warning: file /etc/nginx/conf.d/default.conf: remove failed: No such file or directory
  4. [[email protected] ~]# rm -fr /etc/nginx/
  5. [[email protected] ~]# rpm -e nginx
  6. error: package nginx is not installed

(5)測試和執行

  1. [[email protected] ~]# cd /ansible/
  2. [[email protected] ansible]# ansible-playbook --check nginx.yaml #測試
  3. [[email protected] ansible]# ansible-playbook nginx.yaml #執行

(6)觸發器的建立 

  1. [[email protected] ansible]# vim /etc/ansible/roles/nginx/handlers/main.yaml
  2. - name: restart nginx
  3. service: name=nginx state=restarted

(7)tasks建立通知

  1. [[email protected] ansible]# vim /etc/ansible/roles/nginx/tasks/main.yaml
  2. - name: install nginx package
  3. yum: name=nginx state=present
  4. - name: install conf file
  5. template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  6. notify: restart nginx
  7. - name: start nginx
  8. service: name=nginx state=started enabled=true

(8)模拟配置檔案發生改變(修改j2檔案 )

  1. [[email protected] ansible]# vim /etc/ansible/roles/nginx/templates/nginx.conf.j2
  2. user nginx;
  3. worker_processes {{ ansible_processor_vcpus-1 }};
  4. events {
  5. worker_connections 1024;
  6. }
  7. http {
  8. include /etc/nginx/mime.types;
  9. default_type application/octet-stream;
  10. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11. '$status $body_bytes_sent "$http_referer" '
  12. '"$http_user_agent" "$http_x_forwarded_for"';
  13. access_log /var/log/nginx/access.log main;
  14. sendfile on;
  15. #tcp_nopush on;
  16. keepalive_timeout 65;
  17. #gzip on;
  18. server {
  19. listen {{ http_port }};
  20. server_name localhost;
  21. charset koi8-r;
  22. location / {
  23. root /usr/share/nginx/html;
  24. index index.html index.htm;
  25. }
  26. }
  27. }

(9) 測試和執行

  1. [[email protected] ~]# cd /ansible/
  2. [[email protected] ansible]# ansible-playbook --check nginx.yaml #測試
  3. [[email protected] ansible]# ansible-playbook nginx.yaml #執行

添加通知

(1)修改tasks配置

  1. [[email protected] ansible]# vim /etc/ansible/roles/nginx/tasks/main.yaml
  2. - name: install nginx package
  3. yum: name=nginx state=present
  4. - name: install conf file
  5. template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  6. notify: restart nginx
  7. tags: instconf
  8. - name: start nginx
  9. service: name=nginx state=started enabled=true

(2) 測試和執行

  1. [[email protected] ~]# cd /ansible/
  2. [[email protected] ansible]# ansible-playbook -t instconf --check nginx.yaml #測試
  3. [[email protected] ansible]# ansible-playbook -t instconf nginx.yaml #執行

var變量的使用

  1. [[email protected] ansible]# vim /ansible/useradd.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. vars:
  5. - groupname: testgroup1
  6. - username: testuser1
  7. tasks:
  8. - name: create group
  9. group: name={{ groupname }} state=present
  10. - name: create user
  11. user: name={{ username }} state=present

       測試和執行

  1. [[email protected] ~]# cd /ansible/
  2. [[email protected] ansible]# ansible-playbook -t instconf --check useradd.yaml #測試
  3. [[email protected] ansible]# ansible-playbook -t instconf useradd.yaml #執行

在playbook中定義變量的方式:

還是結合上述的ngin執行個體: (1)定義vars變量檔案

  1. [[email protected] ansible]# vim /etc/ansible/roles/nginx/vars/main.yaml
  2. username: daemon

(2)修改j2檔案:

  1. [[email protected] ansible]# vim /etc/ansible/roles/nginx/templates/nginx.conf.j2
  2. user {{ username }};
  3. worker_processes {{ ansible_processor_vcpus-1 }};
  4. events {
  5. worker_connections 1024;
  6. }
  7. http {
  8. include /etc/nginx/mime.types;
  9. default_type application/octet-stream;
  10. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11. '$status $body_bytes_sent "$http_referer" '
  12. '"$http_user_agent" "$http_x_forwarded_for"';
  13. access_log /var/log/nginx/access.log main;
  14. sendfile on;
  15. #tcp_nopush on;
  16. keepalive_timeout 65;
  17. #gzip on;
  18. server {
  19. listen {{ http_port }};
  20. server_name localhost;
  21. charset koi8-r;
  22. location / {
  23. root /usr/share/nginx/html;
  24. index index.html index.htm;
  25. }
  26. }
  27. }

(3) 測試和執行

  1. [[email protected] ~]# cd /ansible/
  2. [[email protected] ansible]# ansible-playbook -t instconf --check nginx.yaml #測試
  3. [[email protected] ansible]# ansible-playbook -t instconf nginx.yaml #執行在

在playbook中調用角色的方法:

(1)在playbook中調用角色:通過roles指定的任務,然後從上面的兩個對應的角色集合中找到自己的角色和對應的任務進行執行            

  1. - hosts: webservers
  2. remoute_user: root
  3. roles:
  4. - mysql
  5. - ngins
  6. - memcached
  7. - redis

(2)通過變量指明方法:其中鍵role用于指定角色名稱;後續的k/v用于傳遞變量給角色                                             還可以基于條件測試實作角色調用,

  1. - hosts: webservers
  2. remote_user: root
  3. roles:
  4. - { role: nginx,username :nginx }

第二種方法的執行個體(不指定條件):

  1. [[email protected] ~]# vim /ansible/nginx.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. roles:
  5. - { role: nginx,username :nginx }

執行程式:

  1. [[email protected] ~]# ansible-playbook --check nginx.yaml #執行
  2. PLAY [webservers] **************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.7]
  5. ok: [172.1.1.12]
  6. TASK [install nginx] ***********************************************************
  7. ok: [172.1.1.7]
  8. ok: [172.1.1.12]
  9. TASK [install conf file] *******************************************************
  10. ok: [172.1.1.7]
  11. ok: [172.1.1.12]
  12. TASK [start nginx service] *****************************************************
  13. ok: [172.1.1.7]
  14. ok: [172.1.1.12]
  15. PLAY RECAP *********************************************************************
  16. 172.1.1.12 : ok=4 changed=0 unreachable=0 failed=0
  17. 172.1.1.7 : ok=4 changed=0 unreachable=0 failed=0
  18. [[email protected] ~]# ansible all -m shell -a "ps -ef | grep nginx" #傳回結果
  19. 172.1.1.7 | SUCCESS | rc=0 >>
  20. root 10412 1 0 10:21 ? 00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
  21. nginx 10414 10412 0 10:21 ? 00:00:00 nginx: worker process
  22. root 12949 12948 0 11:00 pts/1 00:00:00 /bin/sh -c ps -ef | grep nginx
  23. root 12951 12949 0 11:00 pts/1 00:00:00 grep nginx
  24. 172.1.1.12 | SUCCESS | rc=0 >>
  25. root 4080 1 0 18:06 ? 00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
  26. nginx 4081 4080 0 18:06 ? 00:00:00 nginx: worker process
  27. root 5013 5008 0 18:54 pts/2 00:00:00 /bin/sh -c ps -ef | grep nginx
  28. root 5015 5013 0 18:54 pts/2 00:00:00 grep nginx

第二種方法的執行個體(指定條件)

  1. - hosts: webservers
  2. remote_user: root
  3. roles:
  4. - { role: nginx,username: nginx,when:"ansible_distribution_major_version == '7'" }按條件安裝

按條件安裝memcached軟體: 建立角色:

  1. [[email protected] ~]# mkdir -pv /etc/ansible/roles/memcached/tasks
  2. [[email protected] tasks]# cd /etc/ansible/roles/memcached
  3. [[email protected] memcached]# vim tasks/main.yaml
  4. - name: install package
  5. yum: name=memcached state=present
  6. - name: start memcached
  7. service: name=memcached state=started enabled=true

建立執行入口檔案

  1. [[email protected] memcached]# cd /ansible/
  2. [[email protected] memcached]# vim nginx_memcached.yaml
  3. - hosts: all
  4. remote_user: root
  5. roles:
  6. - { role: nginx, when: ansible_distribution_major_version == '7' }
  7. - { role: memcached, when: ansible_hostname == 'memcached' }

模闆檔案的建立:

  1. [[email protected] ansible]# cd /etc/ansible/roles/memcached/
  2. [[email protected] memcached]# mkdir templates
  3. [[email protected] memcached]# scp 172.1.1.7:/etc/sysconfig/memcached ./templates/
  4. [[email protected] memcached]# vim templates/memcached
  5. PORT="11211"
  6. USER="memcached"
  7. MAXCONN="1024"
  8. CACHESIZE="{{ ansible_memtotal_mb//4 }}"
  9. OPTIONS=""
  10. [[email protected] memcached]# cd templates/
  11. [[email protected] templates]# mv memcached memcached.j2

再次修改角色檔案:

  1. [[email protected] templates]# vim ../tasks/main.yaml
  2. - name: install package
  3. yum: name=memcached state=present
  4. - name: install conf
  5. template: src=memcached.j2 dest=/etc/sysconfig/memcached
  6. notify: restart memcached
  7. tags: memconf
  8. - name: start memcached
  9. service: name=memcached state=started enabled=true

建立handlers檔案:

  1. [[email protected] memcached]# mkdir handlers
  2. [[email protected] memcached]# vim handlers/main.yaml
  3. - name: restart memched
  4. service: name=memcached state=restarted

執行測試:

  1. [[email protected] ansible]# ansible-playbook --check nginx_memcached.yaml
  2. [[email protected] ansible]# ansible-playbook -t memconf --check nginx_memcached.yaml

驗證:

  1. [[email protected] ansible]# ansible all -m shell -a "cat /etc/sysconfig/memcached"
  2. 172.1.1.7 | SUCCESS | rc=0 >>
  3. PORT="11211"
  4. USER="memcached"
  5. MAXCONN="1024"
  6. CACHESIZE="245"
  7. OPTIONS=""

站點:www.ansible.com.cn

繼續閱讀