Ansible中的每个模块专注于某一方面的功能。虽然每个模块实现的功能都比较简单,但是,将各个模块结合起来就可以实现比较复杂的功能。在Ansible中,将各个模块组合起来的文件是一个YAML格式的配置文件。这个配置文件,在Ansible中称为Playbook。
Nginx示例
--- - hosts: webservers #指定执行任务的主机,可以是一个或多个由冒号分割的主机组 vars: #定义变量 worker_processes: 4 num_cpus: 4 max_open_file: 65506 root: /data/www remote_user: heboan #指定远程主机上执行任务的用户 sudo: yes tasks: #定义任务,任务列表中的各任务按次序逐个在hosts指定的主机上执行,即在所有主机上完成一个任务后再开始第二个,如果中途出错,所有已执行的任务都回滚 - name: install depend packages command: yum install -y gcc gcc-c++ openssl-devel pcre-devel - name: unarchive nginx-1.12.2.tar.gz unarchive: src=/etc/ansible/templates/nginx/nginx-1.12.2.tar.gz dest=/home/heboan/tools - name: create nginx user user: name=nginx shell=/sbin/nologin - name: install nginx shell: cd /home/heboan/tools/nginx-1.12.2 && ./configure --prefix=/opt/app/nginx --user=nginx --group=nginx && make && make install - name: cp nginx.service copy: src=/etc/ansible/templates/nginx/nginx.service dest=/usr/lib/systemd/system/nginx.service - name: copy index.html copy: src=/etc/ansible/templates/nginx/index.html dest=/data/www/index.html - name: start nginx service: name=nginx state=started - name: write the nginx config file template: src=/etc/ansible/templates/nginx/nginx2.conf dest=/opt/app/nginx/conf/nginx.conf #这是模板,里面可以识别上面定义的变量 notify: #执行完任务(write the nginx config file)的关联操作 - reload nginx #触发此操作,下面需要定义操作内容 handlers: #定义关联操作 - name: reload nginx #关联操作任务 service: name=nginx state=restarted
user nginx; worker_processes {{worker_processes}}; error_log logs/error.log; pid logs/nginx.pid; events { worker_connections 1024; } worker_rlimit_nofile {{max_open_file}}; http { include 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 logs/access.log main; sendfile on; tcp_nopush on; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; root {{root}}; location / { } } }
[Unit] Description=nginx - high performance web server Documentation=http://nginx.org/en/docs/ After=network.target remote-fs.target nss-lookup.target [Service] Type=forking PIDFile=/opt/app/nginx/logs/nginx.pid ExecStartPre=/opt/app/nginx/sbin/nginx -t -c /opt/app/nginx/conf/nginx.conf ExecStart=/opt/app/nginx/sbin/nginx -c /opt/app/nginx/conf/nginx.conf ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s QUIT $MAINPID PrivateTmp=true [Install] WantedBy=multi-user.target