playbook做爲ansible重要的企業實戰解決方案。如下是個人aliyun ansible學習筆記。html
建立playbook文件linux
touch playbooktest.yml vim playbooktest.yml
編寫playbooknginx
--- - hosts: websrvs remote_user: root task: - name: hello command: hostname
執行playbookansible-playbook playbooktest.yml
web
palybook採用YAML語言編寫,有多個劇本組成,每一個劇本由若干個task組成,每一個task調用不一樣的模塊,最終在目標機器上執行。ansible playbook至關於linux shell腳本。yaml.org 查看更多的語法詳情
shell
第一種編寫方式vim
--- - hosts: websrvs remote_user: root tasks: - name: create new file file: name=/data/newfile state=touch - name: create a new user user: name=test2 system=yes - name: insall package yum: name=httpd - name: copy files copy: src=/var/www/html/index.html
第二種編寫方式app
--- - hosts: websrvs remote_user: root tasks: - name: create new file file: name: /data/newfile state: touch - name: create a new user user: name: test2 system: yes - name: insall package yum: name:httpd - name: copy files copy: src:/var/www/html/index.html
只進行檢查,不真正執行ansible-playbook test.yml --check
ansible-playbook -C test.yml
學習
--- - hosts: websrvs remote_user: root tasks: - name: install httpd yum: name=httpd tags: installed - name: config file copy: src=files/httpd.conf dest=/etc/httpd/conf/ backup=yes notify: - restart service - check the nginx process - name: restart httpd service: name=httpd state=start enableed=yes tags: rshttpd handlers: - name: restart service service: name=httpd state=restarted - name: check the nginx process shell: killall -0 nginix> /tmp/nginx.log
添加tags後,能夠經過tags調用,經過指定標籤執行特定task.ansible-playbook -t installed,rshttpd httpd.yml
rest
ansible變量只能數字字母下劃線組成,且只能字母開頭,包括系統變量和自定義變量。code
ansible websrvs -m setup -a 'filter=ansible_fqdn'
--- - hosts: websrvs remote_user: root tasks: - name: create new file file: name: /data/newfile state: touch - name: create a new user user: name: test2 system: yes - name: insall package yum: name: {{ pkname }}
執行playbook並經過-e傳入變量ansbible-playbook app.yml -e 'pkname=httpd pkname2=vbss'
--- - hosts: websrvs remote_user: root vars: - pkname1: httpd - pkname2: vbs tasks: - name: create new file file: name: /data/newfile state: touch - name: insall package yum: name: {{ pkname }}
執行playbook自動引用內部定義的變量ansbible-playbook app.yml
/etc/ansible/hosts
[webserver] 192.168.1.2 http_port=81 192.168.1.4 http_port=82
playbook引用hosts中的變量
--- - hosts: websrvs remote_user: root vars: - pkname1: httpd - pkname2: vbs tasks: - name: set hostname hostname: name=wwww.{{http_port}}.baidu.com