背景:尽管yum和service模块安装和管理相应服务很方便,但实际生产中,一般需要使用源码安装
思路:先在一台机器上编译安装好nginx,打包,再用ansible分发下去
1. 创建相关目录和配置文件,整体树状图
mkdir /etc/ansible/nginx_install
1.1 vim /etc/ansible/nginx_install/install.yml #总安装文件
--- - hosts: agent.huangzp.com remote_user: root gather_facts: True roles: - common - install
1.2 mkdir -p roles/commom/tasks # 安装前准备工作目录以及配置文件
commom:下面建一个tasks目录就行了
vim /etc/ansible/nginx_install/roles/common/tasks/main.yml # 入口文件main.yml,安装nginx依赖包
- name: install initaliztion require software yum: name={{ item }} state=installed with_items: - zlib-devel - pcre-devel - openssl-devel
1.3 mkdir -p roles/install/{handlers,files,meta,tasks,template,vars} # 安装主配置目录
tasks:核心配置文件,分发资源和安装nginx
1)vim /etc/ansible/nginx_install/roles/install/tasks/main.yml #入口文件,包含了 copy.yml和install.yml两个配置文件
- include: copy.yml - include: install.yml
2) vim /etc/ansible/nginx_install/roles/install/tasks/copy.yml #拷贝压缩包、解压缩、拷贝启动脚本、拷贝配置文件
- name: copy nginx software copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root #copy模块相对目录files - name: uncompression nginx software shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/ - name: copy nginx start script template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755 #template模块相对目录templates - name: copy nginx config template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root goup=root mode=0644
3)vim /etc/ansible/nginx_install/roles/install/tasks/install.yml # 创建运行用户、启动nginx服务、添加至系统服务、删除压缩文件
- name: create nginx user user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin - name: start nginx service service: name=nginx state=started - name: add boot start nginx service shell: chkconfig --level 345 nginx on - name: delete nginx compression files shell: rm -rf /tmp/nginx.tar.gz
vars:定义变量
vim /etc/ansible/nginx_install/roles/install/vars/main.yml #定义变量运行用户、端口、安装目录
nginx_user: www nginx_port: 80 nginx_basedir: /usr/local/nginx
files:存放nginx.tar.gz等文件
tar -zcf nginx.tar.gz /usr/local/nginx
cp /usr/local/nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
templates:模板配置文件,如启动脚本模板
cp /usr/local/nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/template/
cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/template/
handlers:发生改变要执行的操作,如配置文件改变,则重启服务
meta:说明信息,角色依赖等,一般用不着
2. 执行总配置文件ansible-playbook install.yml