Ansible Roles

一、Ansible Roles基本概述

1.Ansible Roles介绍
roles不管是Ansible还是saltstack,我在写一键部署的时候,都不可能把所有的步骤全部写入到一个'剧本'文件当中,我们肯定需要把不同的工作模块,拆分开来,解耦,那么说到解耦,我们就需要用到roles官方推荐,因为roles的目录结构层次更加清晰。

例如:我们之前推荐大家写一个base.yml里面写所有基础优化的项目,其实把所有东西摞进去也是很鸡肋的,不如我们把这些功能全部拆分开,谁需要使用,就调用即可。

建议:每个roles最好只使用一个tasks这样方便我们去调用,能够很好的做到解耦。(SOA)

ansible剧本中 script模块怎样写_nginx

production                # inventory file for production servers
staging                   # inventory file for staging environment

group_vars/
   group1.yml             # here we assign variables to particular groups
   group2.yml
host_vars/
   hostname1.yml          # here we assign variables to particular systems
   hostname2.yml

library/                  # if any custom modules, put them here (optional)
module_utils/             # if any custom module_utils to support modules, put them here (optional)
filter_plugins/           # if any custom filter plugins, put them here (optional)

site.yml                  # master playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""
2.创建roles目录

手动创建

[root@m01 roles]# mkdir nginx/{tasks,files,templates,vars,handlers,meta} -p

[root@m01 roles]# tree nginx/
nginx/
├── files
├── handlers
├── meta
├── tasks
├── templates
└── vars

使用命令创建

[root@m01 roles]# ansible-galaxy init nginx
- Role nginx was created successfully

[root@m01 roles]# tree nginx
nginx					#项目目录名称
├── defaults			#默认的变量(优先级很低)
│   └── main.yml
├── files				#存放文件,使用copy模块时自动获取
├── handlers			#存放触发器的配置
│   └── main.yml
├── meta				#依赖的服务,执行该项目时先执行其他的项目
│   └── main.yml
├── README.md
├── tasks				#默认执行的playbook
│   └── main.yml
├── templates			#存放jinja2模板,使用template模块时自动获取
├── tests
│   ├── inventory
│   └── test.yml
└── vars				#存放变量
    └── main.yml
3.Ansible Roles依赖关系
`roles`允许你再使用roles时自动引入其他的roles。role依赖关系存储在roles目录中meta/main.yml文件中。

例如:推送wordpress并解压,前提条件,必须要安装nginx和php,把服务跑起来,才能运行wordpress的页面,此时我们就可以在wordpress的roles中定义依赖nginx和php的roles
[root@m01 roles]# vim /etc/ansible/roles/wordpress/meta/main.yml
dependencies:
  - { role: nginx }
  - { role: php }
  
如果编写了meta目录下的main.yml文件,那么Ansible会自动先执行meta目录中main.yml文件中的dependencies文件,如上所示,就会先执行nginx和php的安装。

二、重构playbook

1.配置主机清单
[root@m01 roles]# vim /etc/ansible/hosts 
[lb_server]
lb01 ansible_ssh_pass='1'
lb02 ansible_ssh_pass='1'

[web_group]
web01 ansible_ssh_pass='1'
web02 ansible_ssh_pass='1'

[nfs_server]
nfs ansible_ssh_pass='1'

[rsync_server]
backup ansible_ssh_pass='1'

[db_server]
db01 ansible_ssh_pass='1'

[nginx:children]
web_group
lb_server
2.配置hosts
[root@m01 roles]# vim /etc/hosts
10.0.0.4 lb01
10.0.0.5 lb02
10.0.0.7 web01
10.0.0.8 web02
10.0.0.31 nfs
10.0.0.41 backup
10.0.0.51 db01
3.优化部分
[root@m01 roles]# cat base/tasks/main.yml 

    - name: Stop Firewalld
      systemd:
        name: firewalld
        state: stopped
        enabled: no

    - name: Stop Selinux
      selinux:
        state: disabled

    - name: Create www Group
      group:
        name: www
        gid: 666
        state: present
      when: ansible_fqdn != "db01"

    - name: Create www User
      user:
        name: www
        uid: 666
        group: www
        shell: /sbin/nologin
        create_home: false
        state: present
      when: ansible_fqdn != "db01"
4.nginx部分

1)准备包和配置文件

[root@m01 roles]# cd nginx/files/
[root@m01 files]# ll
total 772
-rw-r--r-- 1 root root 784272 Dec 10 09:13 nginx-1.16.1-1.el7.ngx.x86_64.rpm
-rw-r--r-- 1 root root    641 Dec 24 17:16 nginx.conf

2)安装nginx

[root@m01 roles]# vim nginx/tasks/main.yml 

    - name: Push nginx rpm
      copy:       
       src: nginx-1.16.1-1.el7.ngx.x86_64.rpm
        dest: /tmp/

    - name: Install Nginx Server
      yum:
        name: /tmp/nginx-1.16.1-1.el7.ngx.x86_64.rpm
        state: present

    - name: Config Nginx Server
      copy:
        src: nginx.conf
        dest: /etc/nginx/
      notify: restart_nginx

    - name: Start Nginx Server
      systemd:
        name: nginx
        state: started

3)配置触发器

[root@m01 roles]# vim nginx/handlers/main.yml 
- name: restart_nginx
  systemd:
    name: nginx
    state: restarted
5.php部分

1)准备配置文件

[root@m01 roles]# cd php/files/
[root@m01 files]# ll
total 19508
-rw-r--r-- 1 root root    62646 Dec 21 11:04 php.ini
-rw-r--r-- 1 root root 19889622 Nov 22 15:52 php.tar.gz
-rw-r--r-- 1 root root    17962 Dec 22 15:10 www.conf

2)编写安装PHP的剧本

[root@m01 roles]# vim php/tasks/main.yml

    - name: Tar php Package
      unarchive:
        src: php.tar.gz
        dest: /tmp/

    - name: Check php Install Status
      shell: "rpm -qa | grep php | wc -l"
      register: get_php_install_status
      changed_when: false

    - name: Install php Server
      shell: "yum localinstall -y /tmp/*.rpm"
      when: get_php_install_status.stdout_lines == 0

    - name: Config php Server
      copy:
        src: "{{ item.src }}"
        dest: "{{ item.dest }}"
      with_items:
        - { src: "php.ini", dest: "/etc" }
        - { src: "www.conf", dest: "/etc/php-fpm.d/" }
      notify: restart_php

    - name: Start php Server
      systemd:
        name: php-fpm
        state: started

3)配置触发器

[root@m01 roles]# vim php/handlers/main.yml 
- name: restart_php
  systemd:
    name: php-fpm
    state: restarted
6.数据库部分
[root@m01 roles]# cat mariadb/tasks/main.yml 

    - name: Install Mariadb Server
      yum:
        name: mariadb-server
        state: present

    - name: Install MySQL-python Server
      yum:
        name: MySQL-python
        state: present

    - name: Start Mariadb Server
      systemd:
        name: mariadb
        state: started
        enabled: yes

    - name: Create wordpress Database
      mysql_db:
        name: wordpress
        state: present

    - name: Create wordpress Database User
      mysql_user:
        name: "wp"
        host: "172.16.1.%"
        password: "123456"
        priv: 'wordpress.*:ALL'
        state: present
7.博客部分

1)准备文件

[root@m01 roles]# cd wordpress/files/
[root@m01 files]# ll
total 10848
-rw-r--r-- 1 root root      259 Dec 23 18:01 linux.wp.com.conf
-rw-r--r-- 1 root root 11098483 Sep 12 17:52 wordpress-5.0.3-zh_CN.tar.gz
-rw-r--r-- 1 root root     3009 Dec 22 16:00 wp-config.php

博客nginx文件80端口

[root@m01 roles]# cat wordpress/files/linux.wp.com.conf 
server { 
    listen 80;
    server_name linux.wp.com;
    root /code/wordpress;
    index index.php;

    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    

}

2)编写剧本

[root@m01 roles]# vim wordpress/tasks/main.yml

    - name: Create code Dir
      file:
        path: /code
        state: directory

    - name: Tar wordpress Code
      unarchive:
        src: wordpress-5.0.3-zh_CN.tar.gz
        dest: /code/

    - name: Config wordpress DB
      copy:
        src: wp-config.php
        dest: /code/wordpress/

    - name: Chown Code Dir
      file:
        path: /code
        state: directory
        owner: www
        group: www
        recurse: yes

    - name: Config Nginx wordpress
      copy:
        src: linux.wp.com.conf
        dest: /etc/nginx/conf.d/
      notify: restart_nginx

3)配置触发器

[root@m01 roles]# vim wordpress/handlers/main.yml 
- name: restart_nginx
  systemd:
    name: nginx
    state: restarted

8.负载均衡部分
1)准备文件

[root@m01 roles]# cd upstream/templates/
[root@m01 templates]# ll
total 4
-rw-r--r-- 1 root root 270 Dec 24 16:07 upstream.j2

2)编写剧本

[root@m01 roles]# vim upstream/tasks/main.yml 
- name: Config Nginx Upstream
  template:
    src: upstream.j2
    dest: /etc/nginx/conf.d/upstream.conf
  notify: restart_upstream

- name: Start Nginx Server
  systemd:
    name: nginx
    state: started

3)配置触发器

[root@m01 roles]# vim upstream/handlers/main.yml 
- name: restert_upstream
  systemd:
    name: nginx
    state: restarted

4)配置变量文件

```powershell
[root@m01 project]# vim upstream_vars.yml
server_name: linux.wp.com
web_port: 80
net_ip: 172.16.1
9.配置keepalived高可用

1)准备文件

[root@m01 roles]# cd keepalived/templates/
[root@m01 templates]# ll
total 4
-rw-r--r-- 1 root root 381 Dec 24 16:38 keepalived.j2

2)编写剧本

[root@m01 roles]# vim keepalived/tasks/main.yml 
- name: Install keepalived Server
  yum:
    name: keepalived
    state: present

- name: Config keepalived Server
  template:
    src: keepalived.j2
    dest: /etc/keepalived/keepalived.conf

- name: Start keepalived Server
  systemd:
    name: keepalived
    state: started
10.整合剧本
[root@m01 product]# cat site.yml 
- name: 优化部分
  hosts: allsize
  roles:
    - base

- name: 安装nginx
  hosts: nginx
  roles:
    - nginx

- name: 安装php和搭建博客
  hosts: web_group
  roles:
    - php
    - wordpress

- name: 安装数据库
  hosts: db_server
  roles:
    - mariadb

- name: 配置负载均衡和高可用
  hosts: lb_server
  roles:
    - upstream
    - keepalived
# 注意:
main.yml文件中不能有- hosts: web_group
  tasks: