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