Ansible_playbook实战-安装nginx,管理配置文件

ansible playbook介绍

Ansible playbook是将要做的所有操作汇集到一个或者几个yaml文件中去,其实就跟我们写shell脚本一样,只不过这个playbook有它自己的语法和规则。

好处很明显:方便维护、升级;可以反复使用;将复杂的步骤逻辑化。

示例1

vi test.yml #内容如下

---
- hosts: 192.168.111.140
  remote_user: root
  tasks:
    - name: test_playbook
      shell: touch /tmp/lishiming.txt

#``说明:第一行需要有三个杠,第二行一个杠后面就是空格,在后面就是紧跟元素内容

#同一个列表中的元素应该保持相同的缩进。否则会被当做错误处理。
#lay中hosts,variables,roles,tasks等对象的表示方法都是键值中间以":"分隔表示,":"后面还要增加一个空格。

#hosts ``指定了对哪些主机进行参作,如果是多台机器可以用逗号分隔,也可以使用主机组,在/etc/ansible/hosts里定义;
#user``参数指定了使用什么用户登录远程主机操作;

remote_user:指定远端主机中的哪个用户来登录远端系统,在远端系统执行 task 的用户,可以任意指定,也可以使用 sudo,但是用户必须要有执行相应 task 的权限。``

#tasks``指定了一个任务,其下面的name参数同样是对任务的描述,在执行过程中会打印出来,shell是ansible模块名字

执行:
ansible-playbook test.yml

示例2

vi create_user.yml #内容如下

---
- name: create_user
  hosts: 192.168.111.140
  user: root
  gather_facts: false
  vars:
    - user: "test"
  tasks:
    - name: create user
      user: name="{{ user }}"
[root@jinkai01 ~]# ansible-playbook create_user.yml 

PLAY [create_user] ****************************************************************************

TASK [create user] ****************************************************************************
changed: [192.168.111.140]

PLAY RECAP ************************************************************************************
192.168.111.140            : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

#说明:name参数对该playbook实现的功能做一个概述,后面执行过程中,会打印 name变量的值 ,可以省略;
#gather_facts参数指定了在以下任务部分执行前,是否先执行setup模块获取主机相关信息,这在后面的task会使用到setup获取的信息时用到<ansible 192.168.111.140 -m setup>
#vars参数,指定了变量,这里指字一个user变量,其值为test ,需要注意的是,变量值一定要用引号引住;
#user提定了调用user模块,name是user模块里的一个参数,而增加的用户名字调用了上面user变量的值。

playbook中的循环

vi while.yml #内容如下

---
- hosts: test
  user: root
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt

#说明: with_items为循环的对象
给1.txt 2.txt 3.txt 循环对象设定权限,前提是对象必须存在
[root@jinkai01 ~]# ansible-playbook while.yml 

PLAY [test] ***********************************************************************************

TASK [Gathering Facts] ************************************************************************
ok: [192.168.111.141]
ok: [192.168.111.140]

TASK [change mode for files] ******************************************************************
ok: [192.168.111.140] => (item=1.txt)
changed: [192.168.111.141] => (item=1.txt)
changed: [192.168.111.141] => (item=2.txt)
ok: [192.168.111.140] => (item=2.txt)
changed: [192.168.111.141] => (item=3.txt)
ok: [192.168.111.140] => (item=3.txt)

PLAY RECAP ************************************************************************************
192.168.111.140            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.111.141            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

playbook中的条件判断

vi when.yml #内容如下

---
- hosts: test
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_ens33.ipv4.address == "192.168.111.140"

#说明:这里的ansible_ens33.ipv4.address就是通过setup模块查看到的facter信息
条件判断:当匹配到的IP地址为192.168.111.140,则执行touch /tmp/when.txt
[root@jinkai01 ~]# ansible-playbook when.yml 

PLAY [test] ***********************************************************************************

TASK [Gathering Facts] ************************************************************************
ok: [192.168.111.141]
ok: [192.168.111.140]

TASK [use when] *******************************************************************************
skipping: [192.168.111.141]
[WARNING]: Consider using the file module with state=touch rather than running 'touch'.  If
you need to use command because file is insufficient you can add 'warn: false' to this command
task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
changed: [192.168.111.140]

PLAY RECAP ************************************************************************************
192.168.111.140            : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.111.141            : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
[root@jinkai01 ~]# ansible 192.168.111.140 -m shell -a 'ls -l /tmp/when.txt'
192.168.111.140 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 12月  9 23:53 /tmp/when.txt

playbook中的handlers

执行task之后,服务器发生变化之后要执行的一些操作,比如我们修改了配置文件后,需要重启一下服务 vi handlers.yml #加入如下内容

---
- name: handlers test
  hosts: aminglinux02
  user: root
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt
      notify: test handlers
  handlers:
    - name: test handlers
      shell: echo "111111" >> /tmp/aaa.txt

#说明,只有copy模块真正执行后,才会去调用下面的handlers相关的操作。这种比较适合配置文件发生更改后,重启服务的操作
[root@jinkai01 ~]# ansible-playbook handlers.yml 

PLAY [handlers test] **************************************************************************

TASK [Gathering Facts] ************************************************************************
ok: [192.168.111.140]

TASK [copy file] ******************************************************************************
changed: [192.168.111.140]

RUNNING HANDLER [test handlers] ***************************************************************
changed: [192.168.111.140]

PLAY RECAP ************************************************************************************
192.168.111.140            : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

ansible playbook实战:安装Nginx

思路:先在一台机器上编译安装好nginx、打包,然后再用ansible去下发

cd /etc/ansible   #进入ansible配置文件目录 
mkdir  nginx_install   #创建一个nginx_install的目录,方便管理
cd nginx_install
mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
#说明:roles目录下有两个角色,common为一些准备操作,install为安装nginx的操作。
#每个角色下面又有几个目录,handlers下面是当发生改变时要执行的操作,通常用在配置文件发生改变,重启服务。
#files为安装时用到的一些文件,meta为说明信息,说明角色依赖等信息,tasks里面是核心的配置文件,
#templates通常存一些配置文件,启动脚本等模板文件,vars下为定义的变量

需要事先准备好安装用到的文件,具体如下**:**

`#在一台机器上事先编译安装好nginx``,配置好启动脚本,配置好配置文件```

#安装好后,我们需要把nginx目录打包,并放到/etc/ansible/nginx_install/roles/install/files/下面,名字为nginx.tar.gz
[root@jinkai01 local]# tar czvf nginx.tar.gz nginx/
[root@jinkai01 local]# mv nginx.tar.gz
/etc/ansible/nginx_install/roles/install/files/
#启动脚本、配置文件都要放到/etc/ansible/nginx_install/roles/install/templates下面
[root@jinkai01 local]# cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates
[root@jinkai01 local]# cp /usr/local/nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates

cd  /etc/ansible/nginx_install/roles

定义common的tasks,nginx是需要一些依赖包的

vim  ./common/tasks/main.yml #内容如下
- name: Install initializtion require software
  yum: name={{ item }} state=installed
  with_items:
    - zlib-devel
- pcre-devel

定义变量

vim /etc/ansible/nginx_install/roles/install/vars/main.yml //内容如下
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx

首先要把所有用到的文档拷贝到目标机器

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
- 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
- name: Copy Nginx Config
  template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644

接下来会建立用户,启动服务,删除压缩包

vim   /etc/ansible/nginx_install/roles/install/tasks/install.yml #内容如下
- name: Create Nginx User
  user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin
- name: Start Nginx Service
  shell: /etc/init.d/nginx start
- name: Add Boot Start Nginx Service
  shell: chkconfig --level 345 nginx on
- name: Delete Nginx compression files
  shell: rm -rf /tmp/nginx.tar.gz

再创建main.yml并且把copy和install调用

vim   /etc/ansible/nginx_install/roles/install/tasks/main.yml #内容如下
- include: copy.yml
- include: install.yml

到此两个roles:common和install就定义完成了,接下来要定义一个入口配置文件

vim  /etc/ansible/nginx_install/install.yml  #内容如下
---
- hosts: testhost
  remote_user: root
  gather_facts: True
  roles:
    - common
- install

执行:

ansible-playbook /etc/ansible/nginx_install/install.yml

[root@jinkai01 roles]# ansible-playbook /etc/ansible/nginx_install/install.yml

PLAY [192.168.111.140] ****

TASK [Gathering Facts] ****

ok: [192.168.111.140]

TASK [common : Install initializtion require software] ****

[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is

deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{ item

}}", please usename: ['zlib-devel', 'pcre-devel']` and remove the loop. This feature will

be removed in version 2.11. Deprecation warnings can be disabled by setting

deprecation_warnings=False in ansible.cfg.

ok: [192.168.111.140] => (item=[u'zlib-devel', u'pcre-devel'])

TASK [install : Copy Nginx Software] **

changed: [192.168.111.140]

TASK [install : Uncompression Nginx Software] *****

[WARNING]: Consider using the unarchive module rather than running 'tar'. If you need to use

command because unarchive is insufficient you can add 'warn: false' to this command task or

set 'command_warnings=False' in ansible.cfg to get rid of this message.

changed: [192.168.111.140]

TASK [install : Copy Nginx Start Script] **

ok: [192.168.111.140]

TASK [install : Copy Nginx Config] ****

ok: [192.168.111.140]

TASK [install : Create Nginx User] ****

changed: [192.168.111.140]

TASK [install : Start Nginx Service] **

changed: [192.168.111.140]

TASK [install : Add Boot Start Nginx Service] *****

changed: [192.168.111.140]

TASK [install : Delete Nginx compression files] ***

[WARNING]: Consider using the file module with state=absent rather than running 'rm'. If you

need to use command because file is insufficient you can add 'warn: false' to this command

task or set 'command_warnings=False' in ansible.cfg to get rid of this message.

changed: [192.168.111.140]

PLAY RECAP ****

192.168.111.140 : ok=10 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

ansible playbook实战:管理配置文件

生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook

创建几个关键目录

mkdir  -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
#其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令

关于回滚,需要在执行playbook之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证new/files下面的配置和线上的配置一致

先把nginx.conf和vhosts目录放到files目录下面

cd /usr/local/nginx/conf/
cp -r nginx.conf vhost  /etc/ansible/nginx_config/roles/new/files/

定义变量

vim /etc/ansible/nginx_config/roles/new/vars/main.yml #内容如下
nginx_basedir: /usr/local/nginx

重载服务

vim /etc/ansible/nginx_config/roles/new/handlers/main.yml  //定义重新加载nginx服务
- name: restart nginx
  shell: /etc/init.d/nginx reload

定义核心任务

vim /etc/ansible/nginx_config/roles/new/tasks/main.yml //这是核心的任务
- name: copy conf file
  copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root mode=0644
  with_items:
    - { src: nginx.conf, dest: conf/nginx.conf }
    - { src: vhosts, dest: conf/ }
  notify: restart nginx

定义入口

vim /etc/ansible/nginx_config/update.yml // 最后是定义总入口配置
---
- hosts: 192.168.111.140
  user: root
  roles:
  - new

执行:

ansible-playbook /etc/ansible/nginx_config/update.yml

而回滚的backup.yml对应的roles为old

rsync -av  /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/

回滚操作就是把旧的配置覆盖,然后重新加载nginx服务, 每次改动nginx配置文件之前先备份到old里,对应目录为/etc/ansible/nginx_config/roles/old/files

vim /etc/ansible/nginx_config/rollback.yml // 最后是定义总入口配置
---
- hosts: testhost
  user: root
  roles:
  - old 

猜你喜欢

转载自blog.51cto.com/11451960/2640801