ansible-playbook源代码批量部署nginx

2020-01-21 10:33:32 浏览数 (1)

简介

家里的服务器新开了两台虚拟机,想做nginx负载均衡的实验,但是要重新安装各种服务,就很麻烦,正好最近学了ansible-playbook,就想试着写一下一键部署脚本

代码

具体的安装方式我前几篇博客已经说了 话不都说,上代码

代码语言:javascript复制
vi installnginx.yml
- hosts: test2
  remote_user: root
  tasks:    #这后面千万不要加空格,不知道被哪家的教程坑了,我拍错了一个多小时
  - name: mkdir nginx
    file: path=/home/nginx state=directory
  - name: copynginx package
    copy: src=./nginx-1.12.0.tar.gz  dest=/home/nginx-1.12.0.tar.gz  ##拉取nginx解压吧
    tags: cppkg
  - name: tar-nginx
    shell: cd /home;tar -zxf nginx-1.12.0.tar.gz  ##解压nginx包
  - name: installpakger
    yum: name={{ item }} state=latest    ##安装依赖包
    with_items:
      - openssl-devel
      - pcre-devel
      - zlib-devel
      - gcc
      - gcc-c  
  - name: installnginx
    shell: cd /home/nginx-1.12.0;./configure --prefix=/home/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module  --with-pcre;make&& make install      ####编译安装
  - name: copyshell
    copy: src=./create_users.sh dest=/home/create_users.sh  ##拉取创建用户的shell脚本
  - name: createuser nginx
    shell: /bin/bash /home/create_users.sh
    tags: addnginx
    notify: start nginx servic
    handler:
  - name: start nginx service
    shell: /home/nginx/sbin/nginx


创建用户脚本
vi create_users.sh
#!/bin/bash
ab=sudo cat /etc/passwd |grep nginx |wc -c
查找系统中有没有nginx用户
if [ $ab==0 ]; then
        sudo groupadd nginx
        sudo useradd -g nginx -s /sbin/nologin nginx
fi

创建主机清单

代码语言:javascript复制
➜  vi hosts
[test2]
192.168.30.105  ansible_ssh_user=root
192.168.30.107  ansible_ssh_user=root

➜  ansible ansible -i ./hosts test2 --list
  hosts (2):
    192.168.30.105
    192.168.30.107

#然后下载nginx源代码包
   ➜ wget http://mirrors.sohu.com/nginx/nginx-1.12.0.tar.gz
#执行
ansible-playbook -i ./hosts 2.yml

等待一会就好了

0 人点赞