Ansible运维实战
1.Ansible自动化安装nginx
(1).环境准备
我们创建两台虚拟机分别为server节点、host1节点
两个节点根据节点规划来修改主机名
我们在server节点下安装ansible、其余节点不进行配置
节点 | Ip地址 |
Server节点 | 192.168.77.171 |
Host1节点 | 192.168.77.172 |
我们先创建一个nginx角色
[root@server ~]# ansible-galaxy init /etc/ansible/roles/nginx
将在当前目录下创建一个名为 nginx 的新目录,并填充标准的角色结构。角色结构如下:
[root@server ~]# tree /etc/ansible/roles/nginx//etc/ansible/roles/nginx/├── defaults│ └── main.yml├── files├── handlers│ └── main.yml├── meta│ └── main.yml├── README.md├── tasks│ └── main.yml├── templates├── tests│ ├── inventory│ └── test.yml└── vars└── main.yml
我们先用wget命令在server节点上拉取nginx-1.9.6.tar.gz压缩包然后解压压缩包进行编译安装
[root@server ~]# wget http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz[root@server ~]# tar -zxvf nginx-1.9.6.tar.gz[root@server ~]# cd nginx-1.9.6[root@server nginx-1.9.6]# ./configure --prefix=/usr/local/nginx #编译安装[root@server nginx-1.9.6]# make && make install
将nginx-1.9.6.tar.gz复制到/etc/ansible/roles/nginx/files目录下
[root@server ~]# cp nginx-1.9.6.tar.gz /etc/ansible/roles/nginx/files/
(2).文件内容
定义配置文件
[root@server ~]# vi /etc/ansible/roles/nginx/tasks/main.yml[root@server ~]# cat /etc/ansible/roles/nginx/tasks/main.yml- name: 创建 Nginx 用户user:name: "{{ nginx_user }}"system: yesshell: /sbin/nologinstate: present- name: 安装依赖包yum:name: zlib-devel,pcre-devel,gccstate: present- name: 复制nginx压缩包copy:src: "{{ nginx_package_path }}"dest: /root/nginx-1.9.6.tar.gzowner: rootgroup: rootmode: 0644- name: 解压压缩包unarchive:src: "/root/nginx-1.9.6.tar.gz"dest: "/root/"remote_src: yes # 如果文件已经在远程主机上,则设置为 no- name: 编译安装 Nginxshell: >cd /root/nginx-1.9.6 &&./configure --prefix=/usr/local/nginx &&make && make install- name: 编写 Nginx 启动文件template:src: "{{ nginx_service_j2_file_path }}"dest: /etc/systemd/system/nginx.serviceowner: rootgroup: rootmode: '0755'notify: daemon-reload- name: 编写 Nginx 配置文件template:src: "{{ nginx_conf_j2_file_path }}"dest: /usr/local/nginx/conf/nginx.confowner: rootgroup: rootmode: '0644'notify: reload nginx- name: 检查 Nginx 配置文件语法command: /usr/local/nginx/sbin/nginx -tregister: nginx_testchanged_when: falsefailed_when: "'test failed' in nginx_test.stdout"- name: 启动 Nginx 服务并设置开机自启systemd:name: nginxstate: startedenabled: truewhen: nginx_test is succeeded- name: 删除 Nginx 压缩包file:path: /root/nginx-1.9.6.tar.gzstate: absent
定义templates生成配置文件
Nginx配置文件
[root@server ~]# vi /etc/ansible/roles/nginx/templates/nginx.conf.j2[root@server ~]# cat /etc/ansible/roles/nginx/templates/nginx.conf.j2user {{ nginx_user }}; # 设置 Nginx 服务使用的系统用户worker_processes {{ ansible_processor_vcpus }}; # 工作进程数error_log /usr/local/nginx/logs/error.log warn; # Nginx 的错误日志pid /usr/local/nginx/logs/nginx.pid; # Nginx 启动时的 PID 文件events {worker_connections 1024; # 每个进程允许的最大连接数}http { # HTTP 请求配置,一个 http 可以包含多个 server# 定义 Content-Typeinclude /usr/local/nginx/conf/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 /usr/local/nginx/logs/access.log main;# 高效文件传输sendfile on;keepalive_timeout 65;server { # HTTP 服务配置listen {{ nginxport }};server_name localhost;location / {root /usr/local/nginx/html; # 页面存放目录index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root /usr/local/nginx/html;}}include /usr/local/nginx/conf.d/*.conf;}
Nginx启动脚本
[root@server ~]# vi /etc/ansible/roles/nginx/templates/nginx.service.j2[root@server ~]# cat /etc/ansible/roles/nginx/templates/nginx.service.j2[Unit]Description=A high performance web server and a reverse proxy serverAfter=network.target[Service]Type=forkingPIDFile=/usr/local/nginx/logs/nginx.pidExecStartPre=/usr/local/nginx/sbin/nginx -t -q -g 'daemon on; master_process on;'ExecStart=/usr/local/nginx/sbin/nginx -g 'daemon on; master_process on;'ExecReload=/usr/local/nginx/sbin/nginx -s reloadExecStop=/bin/kill -s QUIT $MAINPIDPrivateTmp=true[Install]WantedBy=multi-user.target
定义变量
[root@server ~]# vi /etc/ansible/roles/nginx/vars/main.yml[root@server ~]# cat /etc/ansible/roles/nginx/vars/main.ymlnginx_user: qiunginx_package: nginx-1.9.6.tar.gznginx_package_path: /etc/ansible/roles/nginx/files/nginx-1.9.6.tar.gznginx_service_j2_file_path: /etc/ansible/roles/nginx/templates/nginx.service.j2nginx_conf_j2_file_path: /etc/ansible/roles/nginx/templates/nginx.conf.j2nginxport: 80
定义触发
因为上面通知已经定义,所以,还需要定义一个触发
[root@server ~]# vi /etc/ansible/roles/nginx/handlers/main.yml[root@server ~]# cat /etc/ansible/roles/nginx/handlers/main.yml- name: daemon-reloadsystemd: daemon-reload=yes- name: reload nginxsystemd: name=nginx state=reloaded
定义剧本文件
[root@server ~]# vi /etc/ansible/roles/nginx/install.yml[root@server ~]# cat /etc/ansible/roles/nginx/install.yml---- hosts: host1remote_user: rootroles:- nginx
定义之后的角色结构
[root@server ~]# tree /etc/ansible/roles/nginx//etc/ansible/roles/nginx/├── defaults│?? └── main.yml├── files│?? └── nginx-1.9.6.tar.gz├── handlers│?? └── main.yml├── install.yml├── meta│?? └── main.yml├── README.md├── tasks│?? └── main.yml├── templates│?? ├── nginx.conf.j2│?? └── nginx.service.j2├── tests│?? ├── inventory│?? └── test.yml└── vars└── main.yml
(3).执行文件
检查yml文件语法是否正确
[root@server ~]# ansible-playbook --syntax-check /etc/ansible/roles/nginx/install.yml# 检查install.yml会自动去检查其他的yml文件的语法。
执行roles.yml文件
[root@server ~]# ansible-playbook /etc/ansible/roles/nginx/install.ymlPLAY [host1] *****************************************************************************************************************************TASK [Gathering Facts] *******************************************************************************************************************ok: [192.168.77.172]TASK [nginx : 创建 Nginx 用户] ***************************************************************************************************************changed: [192.168.77.172]TASK [nginx : 安装依赖包] *********************************************************************************************************************changed: [192.168.77.172]TASK [复制nginx压缩包] ************************************************************************************************************************changed: [192.168.77.172]TASK [nginx : 解压压缩包] *********************************************************************************************************************changed: [192.168.77.172]TASK [nginx : 编译安装 Nginx] ****************************************************************************************************************changed: [192.168.77.172]TASK [nginx : 编写 Nginx 启动文件] *************************************************************************************************************changed: [192.168.77.172]TASK [nginx : 编写 Nginx 配置文件] *************************************************************************************************************changed: [192.168.77.172]TASK [nginx : 检查 Nginx 配置文件语法] ***********************************************************************************************************ok: [192.168.77.172]TASK [nginx : 启动 Nginx 服务并设置开机自启] ********************************************************************************************************changed: [192.168.77.172]TASK [nginx : 删除 Nginx 压缩包] **************************************************************************************************************changed: [192.168.77.172]RUNNING HANDLER [nginx : daemon-reload] **************************************************************************************************ok: [192.168.77.172]RUNNING HANDLER [reload nginx] ***********************************************************************************************************changed: [192.168.77.172]PLAY RECAP *******************************************************************************************************************************192.168.77.172 : ok=13 changed=10 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
查看服务启动状态
[root@host1 ~]# systemctl status nginx
2.管理配置文件
生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook。
(1).环境准备
创建角色目录结构
[root@server ~]# mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
(2).文件内容
定义配置文件
new目录
[root@server ~]# vi /etc/ansible/nginx_config/roles/new/tasks/main.yml[root@server ~]# cat /etc/ansible/nginx_config/roles/new/tasks/main.yml- name: copy conf filecopy: src="{{ item.src }}" dest="{{ nginx_basedir }}/{{ item.dest }}" backup=yes owner=root group=root mode=0644with_items:- { src: '/etc/ansible/nginx_config/roles/new/files/nginx.conf' , dest: 'conf/nginx.conf' }- { src: '/etc/ansible/nginx_config/roles/new/files/vhosts' , dest: 'conf/vhosts' }notify: restart nginx
old目录
[root@server ~]# vi /etc/ansible/nginx_config/roles/old/tasks/main.yml[root@server ~]# cat /etc/ansible/nginx_config/roles/old/tasks/main.yml- name: copy conf filecopy: src="{{ item.src }}" dest="{{ nginx_basedir }}/{{ item.dest }}" backup=yes owner=root group=root mode=0644with_items:- { src: '/etc/ansible/nginx_config/roles/old/files/nginx.conf' , dest: 'conf/nginx.conf' }- { src: '/etc/ansible/nginx_config/roles/old/files/vhosts' , dest: 'conf/vhosts' }notify: restart nginx
定义files目录下内容
new目录和old目录都要配置
把nginx.conf和vhosts目录放到files目录下面
[root@server ~]# cd /usr/local/nginx/conf/[root@server conf]# cp -r nginx.conf vhosts /etc/ansible/nginx_config/roles/new/files/[root@server conf]# ls /etc/ansible/nginx_config/roles/new/files/nginx.conf vhosts
定义变量
new目录和old目录都要配置
[root@server ~]# vi /etc/ansible/nginx_config/roles/new/vars/main.yml[root@server ~]# cat /etc/ansible/nginx_config/roles/new/vars/main.ymlnginx_basedir: /usr/local/nginx
定义触发
[root@server ~]# vi /etc/ansible/nginx_config/roles/new/handlers/main.yml[root@server ~]# cat /etc/ansible/nginx_config/roles/new/handlers/main.yml- name: restart nginxsystemd:name: nginxstate: restarted
定义剧本文件
new目录
[root@server ~]# vi /etc/ansible/nginx_config/update.yml[root@server ~]# cat /etc/ansible/nginx_config/update.yml---- hosts: host1remote_user: rootroles:- new
old目录
[root@server ~]# vi /etc/ansible/nginx_config/backup.yml[root@server ~]# cat /etc/ansible/nginx_config/backup.yml---- hosts: host1remote_user: rootroles:- old
定义之后的角色结构
[root@server ~]# tree /etc/ansible/nginx_config//etc/ansible/nginx_config/├── backup.yml├── roles│ ├── new│ │ ├── files│ │ │ ├── nginx.conf│ │ │ └── vhosts│ │ ├── handlers│ │ │ └── main.yml│ │ ├── tasks│ │ │ └── main.yml│ │ └── vars│ │ └── main.yml│ └── old│ ├── files│ │ ├── nginx.conf│ │ └── vhosts│ ├── handlers│ │ └── main.yml│ ├── tasks│ │ └── main.yml│ └── vars│ └── main.yml└── update.yml
其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令,tasks为执行的任务,vars为定义的变量。
(3).执行文件
在执行update.yml前,应备份当前配置文件,当执行之后发现错误,则进行回滚操作。命令如下:
执行update.yml文件之前一定要使用rsync命令备份配置文件
回滚操作就是把旧的配置覆盖,然后重新加载nginx服务, 每次改动nginx配置文件之前先备份到old里,对应目录为/etc/ansible/nginx_config/roles/old/files。
[root@server ~]# rsync -av /etc/ansible/nginx_config/roles/new/files/ /etc/ansible/nginx_config/roles/old/files/sending incremental file list./nginx.confsent 2,807 bytes received 39 bytes 5,692.00 bytes/sectotal size is 2,655 speedup is 0.93
修改new/files目录下的nginx.conf配置文件内容为123
[root@server ~]# echo "123" > /etc/ansible/nginx_config/roles/new/files/nginx.conf[root@server ~]# cat /etc/ansible/nginx_config/roles/new/files/nginx.conf123
然后执行update.yml文件
[root@server ~]# ansible-playbook /etc/ansible/nginx_config/update.ymlPLAY [host1] ************************************************************************************************************************TASK [Gathering Facts] **************************************************************************************************************ok: [192.168.77.172]TASK [new : copy conf file] *********************************************************************************************************changed: [192.168.77.172] => (item={u'dest': u'conf/nginx.conf', u'src': u'/etc/ansible/nginx_config/roles/new/files/nginx.conf'})ok: [192.168.77.172] => (item={u'dest': u'conf/vhosts', u'src': u'/etc/ansible/nginx_config/roles/new/files/vhosts'})RUNNING HANDLER [new : restart nginx] ***********************************************************************************************fatal: [192.168.77.172]: FAILED! => {"changed": false, "msg": "Unable to restart service nginx: Job for nginx.service failed because the control process exited with error code. See \"systemctl status nginx.service\" and \"journalctl -xe\" for details.\n"}NO MORE HOSTS LEFT ******************************************************************************************************************PLAY RECAP **************************************************************************************************************************192.168.77.172 : ok=2 changed=1 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
因为配置了错误的nginx配置文件所以nginx服务重启不了报错了,我们这时候想把配置文件还原需要执行backup.yml文件
[root@server ~]# ansible-playbook /etc/ansible/nginx_config/backup.ymlPLAY [host1] ************************************************************************************************************************TASK [Gathering Facts] **************************************************************************************************************ok: [192.168.77.172]TASK [old : copy conf file] *********************************************************************************************************changed: [192.168.77.172] => (item={u'dest': u'conf/nginx.conf', u'src': u'/etc/ansible/nginx_config/roles/old/files/nginx.conf'})ok: [192.168.77.172] => (item={u'dest': u'conf/vhosts', u'src': u'/etc/ansible/nginx_config/roles/old/files/vhosts'})RUNNING HANDLER [old : restart nginx] ***********************************************************************************************changed: [192.168.77.172]PLAY RECAP **************************************************************************************************************************192.168.77.172 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
我们这样就把配置文件还原到执行update.yml文件之前的样子了。
至此Ansible-运维实战部分结束。