Ansible自動化運維筆記3(playbook)

1.基本語法

playbook文件格式爲yaml語法.示例以下:
1.1 nginx.yamljavascript

---
- hosts: all
  tasks:
      - name: Install Nginx Package
        yum: name=nginx state=present

      - name: Copy Nginx.conf
        template: src=./nginx.conf.j2 dest=/etc/nginx/nginx.conf owner=root group=root mode=0644 validate='nginx -t -c %s'
        notify:
           - Restart Nginx Service
  handlers:
      - name: Restart Nginx Service
        service: name=nginx state=restarted

---第一行表示該文件是yaml文件,非必須,建議寫上css

  • hosts:all 定義該playbook針對的目標主機,all表示針對全部主機,這個參數支持Ad-Hoc模式的全部參數
    tasks: 定義該playbook全部的tasks集合
  • name: Install Nginx Package定義一個task的名稱,建議根據task實際任務命名
    yum: name=nginx state=present 定義一個狀態的action,這裏使用yum模塊,實現nginx軟件包的安裝
    第6行-第9行使用template模板去管理/etc/nginx/nginx.conf文件,owner,group定義該文件的屬主及屬組,使用validate參數指文件生成後使用nginx -t -c 檢測配置文件語法,notify是觸發handlers,若是同步後,文件md5值有變化的話會觸發handler
    第10-12行定一個一個handler狀態讓Nginx去重啓,

1.2 主機清單文件java

cat /tmp/hosts

[nginx]
192.168.1.1
192.168.1.2
[nginx:vars]
ansible_python_interpreter=/usr/bin/python2.6

1.3 nginx.conf.j2node

user                                    admin  admin;
worker_processes                        8;
worker_cpu_affinity                     {{ ansible_processor_cores }};
error_log                               /export/servers/nginx/logs/nginx_error.log  warn;
pid                                     /export/servers/nginx/run/nginx.pid;
worker_rlimit_nofile                    65535;
events 
{
                                        use epoll;
                                        worker_connections 65535;
}
http 
{
        include                         mime.types;
        default_type                    application/octet-stream;
        server_tokens                   on;
        log_format main                 '$remote_addr - $remote_user [$time_local] "$http_x_forwarded_for" "$http_j_forwarded_for" '
                                                        '"$request" $status $bytes_sent '
                                                        '"$http_referer" "$http_user_agent" '
                                                        '"$gzip_ratio"';
        #charset                        utf-8;
        server_names_hash_bucket_size   128;
        client_header_buffer_size       32k;
        large_client_header_buffers     4 32k;
        client_max_body_size            300m;
        sendfile                        on;
        tcp_nopush                      on;
        keepalive_timeout               0;
        tcp_nodelay                     on;
        client_body_buffer_size         512k;
        fastcgi_intercept_errors        on;
        proxy_connect_timeout           90;
        proxy_read_timeout              180;
        proxy_send_timeout              180;
        proxy_buffer_size               256k;
        proxy_buffers                   4 256k;
        proxy_busy_buffers_size         256k;
        proxy_temp_file_write_size      256k;
        proxy_intercept_errors          on;
        server_name_in_redirect         off;
        proxy_hide_header       X-Powered-By;

        gzip                            on;
        gzip_min_length                 100;
        gzip_buffers                    4 16k;
        gzip_http_version               1.0;
        gzip_comp_level                 9;
        gzip_types                      text/plain application/x-javascript text/css application/xml;
        gzip_vary                       on;
        gzip_proxied                       any;

include domains/*;
###########status#########
#        server
#                {
#                 listen                 80;
#                 server_name            status.360buy.com;
#        location / {
#                 stub_status            on;
#                 access_log             off;
#                 }
#        }
}

1.hosts文件裏面定義了一個nginx組,裏面有2個IP
2.組變量ansible_python_interpreter是ansible自帶的影藏變量,是facts套件提供的;若是目標機器上python版本多,指定一個版原本運行
3.nginx.conf.j2是nginx.conf的模板文件,裏面只針對worker_processes參數經過facts套件中的cpu核心數生成,其餘配置都是默認的python

1.4 檢查yaml文件的語法是否正確nginx

$ ansible-playbook -i /tmp/hosts nginx.yaml --syntax-check

1.5 檢查yaml文件中的tasks任務shell

$ ansible-playbook -i /tmp/hosts nginx.yaml --list-task

1.6 檢查yaml文件中的生效主機json

$ ansible-playbook -i /tmp/hosts nginx.yaml --list-hosts

1.7 運行playbookapi

$ ansible-playbook -i /tmp/hosts nginx.yaml

1.8 運行playbook裏面特定的某個task,從某個task開始運行bash

$ ansible-playbook -i /tmp/hosts nginx.yaml --start-at-task='Copy Nginx.conf'

2.變量與引用

2.1 經過inventory文件定義主機以及主機組變量

太簡單了,寫了好屢次了,此次不寫了

2.2 經過playbook文件當前目錄下新建group_vars和host_vars這2個目錄(目錄名字固定,不能改)

$ cat group_vars/nginx

---
key: NGINX

在當前目錄下運行playbook的時候,會自動去找group_vars和host_vars這2個目錄

2.3 經過ansible-playbook命令行參數傳入
(1)命令行傳遞變量

$ ansible-playbook -i /tmp/hosts nginx.yaml -e "key=KEY"

(2)命令行傳遞變量文件

$ cat var.yaml
---
key: YAML
$ cat var.json
{"key":"JSON"}
$ ansible-playbook -i /tmp/hosts nginx.yaml -e "@var.json"
$ ansible-playbook -i /tmp/hosts nginx.yaml -e "@var.yaml"

2.4 在playbook文件內使用vars(用的不多)

---
- hosts: all
  vars:
        key: Ansible
  tasks:
      - name: xxx
        deubg: msg="The {{ key}}"

2.5 在playbook文件內使用vars_files引用外部變量文件(也能夠是json文件,後期開發api模式主要用這種方式)

---
- hosts: all
  vars_files:
    - var.yaml
    - var.json

2.6 使用register內的變量

ansible的task之間還能夠互相傳遞數據,把第一個task執行的結果register註冊爲變量而後傳遞給第二個task

---
- hosts: all
  tasks:
      - name: register variable
        shell: hostname
        register: info
      - name: display variable
        debug: msg="The msg is {{ info }}"
        debug: msg="The msg is {{ info['stdout'] }}"

實際跑下看下結果(-l呢是在匹配主機inventory裏面再進一步篩選,只跑192.168.1.118主機)

$ ansible-playbook -i /tmp/hosts variable.yaml -l 192.168.1.118

3.循環

3.1 標準loops

分別打印one two這2個值

---
- hosts:all
  tasks:
      - name: debug loops
        debug: msg = "name---> {{ item }}"
        with_items:
            - one
            - two

with_items:值呢是python list數據結構,每一個task會循環讀取list裏面的值,key的名稱是item,固然支持列表裏面嵌套字典,例子以下

---
- hosts:all
  tasks:
      - name: debug loops
        debug: msg = "name-----> {{ item.key }} value---->{{ item.value }}"
        with_items:
            - {key:"one",value:"value1"}
            - {key:"two",value:"value2"}

3.2 嵌套loops

實現一堆多或者多對多的合併

---
- hosts:all
  tasks:
      - name: debug loops
        debug: msg="name ----->{{ item[0] }}  value----->{{ item[1] }}"
        with_nested:
            - ['A']
            - ['a','b','c']

3.3 字典循環

---
- hosts:all
  tasks:
      - name: debug loops
        debug: msg="name ----->{{ item.key }}  value----->{{ item.value }}"
        with_dict: user

3.4 文件循環

---
- hosts:all
  tasks:
      - name: debug loops
        debug: msg="{{ item }}"
        with_fileglob:
            - /tmp/*.yaml

3.5 隨機循環

---
- hosts:all
  tasks:
      - name: debug loops
        debug: msg="{{ item }}"
        with_random_choice:
            - "ansible1"
            - "ansible2"
            - "ansible3"

3.6 條件判斷循環

---
- hosts:all
  tasks:
      - name: debug loops
        shell: cat /root/ansible
        register: host
        until: host.stdout.startswith('Master')
        retries:5
        delay:5

5秒執行一次cat /root/ansible,將結果註冊給變量host,判斷host.stdout的內容是否以Master開頭,條件成立,task運行完成,條件不成立,5秒後重試,5次還不成立,task運行失敗

4.lookups

從外部拉取信息,定義給一個變量的形式,lookups插件

相關文章
相關標籤/搜索