Ansible自动化管理配置工具

介绍Ansible

Ansible可以实现一条命令完成多件事情  
	一台服务器上的多件事
	多台服务器上的多件事

Ansible ad-hoc

配置文件查找优先级

ANSIBLE_CONFIG					#全局
ansible.cfg						#项目目录
.ansible.cfg
/etc/ansible/ansible.cfg

Ansible Inventory 主机清单

Ansible Ad-Hoc 模块(临时命令,不会保存)

查询语法方式: ansible-doc module_name

模块:
1.yum | yum_repository
2.copy
3.file
4.service|systemd
5.cron
6.mount
7.user
8.group
9.shell | command
10.firewalld | selinux

command shell

command shell
建议使用shell模块。 因为command不支持管道技术。

yum模块

yum:装软件

示例一、安装当前最新的Apache软件,如果存在则不安装
[root@manager ~/ansible-project1]# ansible oldboy -m yum -a "name=httpd state=latest"

#示例二、安装当前最新的Apache软件,通过epel仓库安装
[root@manager ~]# ansible oldboy -m yum -a "name=httpd enablerepo=epel state=present"

#示例三、通过公网URL安装rpm软件
[root@manager ~/ansible-project1]# ansible oldboy -m yum -a "name=http://192.168.16.236/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm state=present"

#示例五、更新所有的软件包,但排除和kernel相关的
[root@manager ~/ansible-project1]# ansible oldboy -m yum -a "name='*' state=latest exclude="kernel*""   


#示例六、删除Apache软件
[root@manager ~/ansible-project1]# ansible oldboy -m yum -a "name=httpd state=absent"

copy模块和template模块

copy模块(不能在jinja2中引用变量)
template模块在jinja2中引用变量(用法和copy模块一样)

src				#当前管理机的配置文件路径
content			#要写入的内容
dest			#目标文件的配置文件路径
owner			#属主
group			#属组
mode			#权限
backup			#备份  (每个变更进行备份)
[root@manager ~/ansible-project1]# ansible oldboy -m copy -a 'src=./hosts dest=/tmp/ owner=root group=root mode=600 backup=yes'

管理httpd配置文件
[root@manager ~/ansible-project1]# ansible oldboy -m copy -a "src=./files/httpd.conf dest=/etc/httpd/conf/httpd.conf owner=root group=root mode=0644 backup=yes"

systemd模块

systemd模块:

name:		服务名称
state: 	started stopped restarted  reloaded
enabled:   开机自启动  yes|no
1.启动httpd服务
[root@manager ~/ansible-project1]# ansible oldboy -m systemd -a "name=httpd state=started"

2.开机自启动
[root@manager ~/ansible-project1]# ansible oldboy -m systemd -a "name=httpd state=started enabled=yes"

file模块

file模块

path: /work					#在被控端哪个路径下创建目录 | 文件
state: directory  touch		# directory 目录  touch 文件
owner: root
group: root
mode: '0755'
recurse: yes 递归授权
[root@manager ~/ansible-project1]# ansible oldboy -m file -a "path=/ansible_data state=directory owner=root group=root mode=0755"

group模块

group模块

name: 		组名称
state: 		present  absent
gid:		组id
[root@manager ~/ansible-project1]# ansible oldboy -m group -a "name=test gid=8888 state=present"
[root@manager ~/ansible-project1]# ansible oldboy -m group -a "name=test state=absent"

user模块

user模块

name:				指定用户名称
uid: 				指定用户的uid
group: 				指定用户的组名称  或 组 GID
groups: 			指定用户的附加组(附加组需存在) append:yes 给一个用户追加附加组
create_home			创建用户家目录/home/Username   默认yes | no 
shell: 				指定登录用户的bash  /bin/bash  /sbin/nologin
system:             指定系统用户
password
1.创建一个dev用户,uid为9999    属于test主的组,附加组为admin,root组
[root@manager ~/ansible-project1]# ansible oldboy -m user -a "name=dev uid=9999 group=test groups=adm,root shell=/bin/bash create_home=yes"

2.追加两个组给dev用户
[root@manager ~/ansible-project1]# ansible oldboy -m user -a "name=dev groups=bin,daemon append=yes"

3.创建一个系统用户ops,没有家目录  不允许登录系统
[root@manager ~/ansible-project1]# ansible oldboy -m user -a "name=ops system=yes shell=/sbin/nologin create_home=no"


4.创建一个普通用户,可登录  devops  123456
ansible all -i localhost, -m debug -a "msg={{ '123456' | password_hash('sha512', 'mysecretsalt') }}"
    "msg": "$6$mysecretsalt$ZB9R8AirQYAXhtfhOo2qdJz52FyNI6v3L6Uc3KNRP.arBKIYpcuEyQewT5qBAHoyQFwHkW6Z551Ql.cZ53GeY0"
	
[root@manager ~/ansible-project1]# ansible oldboy -m user -a 'name=devops password="$6$mysecretsalt$ZB9R8AirQYAXhtfhOo2qdJz52FyNI6v3L6Uc3KNRP.arBKIYpcuEyQewT5qBAHoyQFwHkW6Z551Ql.cZ53GeY0"'

mount挂载模块

mount挂载模块

src:   源设备  (磁盘 | 光盘|  远程的共享的地址) src=172.16.1.31:/data
path: 	挂载点
fstype: 设备类型  nfs xfs ext4 iso9660 ....
opts: 	挂载选项  defaults
state: 
absent  mounted 		永久
present unmounted		临时
挂载172.16.1.31/data/blog  挂载至本地的/opt  
[root@manager ~/ansible-project1]# ansible oldboy -m mount -a "src=172.16.1.31:/data/blog path=/opt fstype=nfs opts=defaults state=mounted"

[root@manager ~/ansible-project1]# ansible oldboy -m mount -a "src=172.16.1.31:/data/blog path=/opt fstype=nfs opts=defaults state=unmounted"	

selinux模块

[root@manager ~/ansible-project1]# ansible oldboy -m selinux -a "state=disabled"

firewalld模块

firewalld模块

zone: 				指定区域 默认public
service: 			指定服务名称
port:				指定端口
state: 				启用或禁止
masquerade: 		开机地址伪装 yes
immediate:			临时生效 yes
permanent: 			永久生效
source: 			来源IP

rich_rule: rule service name=“ftp” audit limit value=“1/m” accept

1.放行http服务
[root@manager ~/ansible-project1]# ansible 172.16.1.31 -m firewalld -a "zone=public  service=http state=enabled immediate=yes permanent=yes"

2.放行tcp80端口
[root@manager ~/ansible-project1]# ansible 172.16.1.31 -m firewalld -a "zone=public  port=80/tcp state=enabled immediate=yes permanent=yes"

3.将5555端口转发到 172.16.1.7 22  端口 开启masquerade地址伪装
[root@manager ~/ansible-project1]# ansible 172.16.1.31 -m firewalld -a "zone=public rich_rule='rule family=ipv4 forward-port port=5555 protocol=tcp to-port=22 to-addr=172.16.1.7'  state=enabled immediate=yes"
[root@manager ~/ansible-project1]# ansible 172.16.1.31 -m firewalld -a "zone=public masquerade=yes state=enabled immediate=yes"


4.配置基于来源IP  10.0.0.1主机 放行 22 端口
[root@manager ~/ansible-project1]# ansible 172.16.1.31 -m firewalld -a "zone=public rich_rule='rule family=ipv4 source address=10.0.0.100/32 service name=ssh accept'  state=enabled immediate=yes"

cron模块

1.添加一个定时任务 (能不能执行跟cron模块没有关系)
[root@manager ~/ansible-project1]# ansible oldboy -m cron -a "name='Backup scripts' minute=00 hour=05 user=root job='/bin/bash /scripts/check_data.sh &>/dev/null'"

2.删除定时任务
[root@manager ~/ansible-project1]# ansible oldboy -m cron -a "name='Backup scripts' minute=00 hour=05 user=root job='/bin/bash /scripts/check_data.sh &>/dev/null' state=absent"

yum_repository模块

yum_repository模块

name: 			仓库名称,并且是文件的名称
description: 	描述--
baseurl: 		仓库的地址|很重要  http:// https:// ftp:// file://
enabled: 		是否启用该仓库yes
gpgcheck: 		不对下载的软件包进行检查
[root@manager ~/ansible-project1]# ansible oldboy -m yum_repository -a 'name=rpmforge description="RPMforge YUM Repo" baseurl="https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch/" enabled=yes gpgcheck=no'

authorized_key模块

ansible nfs -m authorized_key -a "user=root state=present key='{{ lookup('file', '/root/.ssh/id_rsa.pub') }}'" -k(询问密码,前提被管理机密码是一致的)
- hosts: all
  tasks: 
  - name: Set authorized key taken from file
    authorized_key:
      user: root
      state: present
      key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}

unarchive模块

功能:解压缩,这个模块有两种用法:
1、将ansible主机上的压缩包在本地解压缩后传到远程主机上,这种情况下,copy=yes. 本地解压缩,解压缩位置不是默认的目录,没找到或传完删了 后传到远程主机
2、将远程主机上的某个压缩包解压缩到指定路径下。这种情况下,需要设置copy=no 远程主机上面的操作,不涉及ansible服务端

参数:
copy:默认为yes,当copy=yes,那么拷贝的文件是从ansible主机复制到远程主机上的,如果设置为copy=no,那么会在远程主机上寻找src源文件
src:源路径,可以是ansible主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限

unarchive:
        src: ./kodexplorer4.40.zip
        dest: /cloud
        copy: yes
        owner: www
        group: www
        creates: "/cloud/index.php" (第一次执行剧本解压到/cloud目录,再一次执行剧本会跳过解压到/cloud目录)

notify和handlers

notify
notify这个action可用于在每个play的最后被触发,这样可以避免多次有改变发生时每次都执行指定的操作,取而代之,仅在所有的变化发生完成后一次性地执行指定操作。

在notify中列出的操作称为handler,也即notify中调用handler中定义的操作。

handlers
Handlers 也是一些 task 的列表,通过名字来引用,它们和一般的 task 并没有什么区别。
Handlers 是由通知者进行 notify, 如果没有被 notify,handlers 不会执行。
不管有多少个通知者进行了 notify,等到 play 中的所有 task 执行完成之后,handlers 也只会被执行一次。
Handlers 最佳的应用场景是用来重启服务,或者触发系统重启操作.除此以外很少用到了。

- hosts: lb01
  tasks:
    - name: Configure LB Server
      copy:
        src: ./cloud.lxx.com..j2
        dest: /etc/nginx/conf.d/proxy_cloud.lxx.com.conf
        owner: root
        group: root
        mode: '0644'
      notify: Restart Nginx Server
       
   handlers:
    - name: Restart Nginx Server
      systemd:
        name: nginx
        state: restarted

Ansible Playbook(剧本)

示例:nginx+php+redis 搭建可道云

- hosts: web
  tasks:
    - name: Create Process Gruop
      group:
        name: www
        gid: '666'

    - name: Create Process User
      user:
        name: www
        uid: '666'
        group: '666'

    - name: Configure Nginx.conf
      copy:
        src: ./nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: '0644'
      notify: Restart Nginx Server

    - name: Configure Nginx  Vhost    
      copy:
        src: ./cloud.lxx.com.conf.j2
        dest: /etc/nginx/conf.d/cloud.lxx.com.conf
        owner: root
        group: root
        mode: '0644'
      notify: Restart Nginx Server

    - name: Configure PHP.INI Server
      copy:
        src: ./php.ini.conf.j2
        dest: /etc/php.ini
        owner: root
        group: root
        mode: '0644'
      notify: Restart PHP Server

    - name: Configure PHP Server
      copy:
        src: ./php_www.conf.j2
        dest: /etc/php-fpm.d/www.conf
        owner: root
        group: root
        mode: '0644'
      notify: Restart PHP Server
     
    - name: Create WebSite Directory
      file:
        path: /cloud
        state: directory
        owner: www
        group: www
        recurse: yes

    - name: Copy Cloud Code
      unarchive:
        src: ./kodexplorer4.40.zip
        dest: /cloud
        copy: yes
        owner: www
        group: www
        creates: "/cloud/index.php"

    - name: Systemd Nginx Server
      systemd:
        name: nginx
        state: started
        enabled: yes

    - name: Systemd PHP Server
      systemd:
        name: php-fpm
        state: started
        enabled: yes

        
  handlers:
    - name: Restart PHP Server
      systemd:
        name: php-fpm
        state: restarted
    
    - name: Restart Nginx Server
      systemd:
        name: nginx
        state: restarted
   
- hosts: lb01
  tasks:
    - name: Configure LB Server
      copy:
        src: ./cloud.lxx.com..j2
        dest: /etc/nginx/conf.d/proxy_cloud.lxx.com.conf
        owner: root
        group: root
        mode: '0644'
      notify: Restart Nginx Server
  
    - name: Systemd Nginx
      systemd:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: Restart Nginx Server
      systemd:
        name: nginx
        state: restarted
        
- hosts: db01
  tasks:
    - name: Configure Redis
      copy:
        src: ./redis.conf.j2
        dest: /etc/redis.conf
      notify: Restart Redis Server

    - name: Systemd Redis
      systemd:
        name: redis
        state: started
        enabled: yes
  handlers:
    - name: Restart Redis Server
      systemd:
        name: redis
        state: restarted

Ansible 变量

vars

测试playbook中的vars设定变量

- hosts: web
  vars:
    - play_var: oldboy
  tasks:
    - name: file
      file:
        path: /tmp/{{ play_var }}
        state: touch    

vars_files

测试playbook中的vars_files设定变量

[root@manager ~/ansible_variables]# cat play_1.yml 
- hosts: web
  vars_files: ./var.yml

  tasks:
    - name: touch new files
      file:
        path: "/tmp/{{ play_var1 }}"
        state: touch

[root@manager ~/ansible_variables]# play_2.yml
- hosts: web
  vars_files: ./var.yml

  tasks:
    - name: touch new files
      file:
        path: "/tmp/{{ play_var2 }}_{{ play_var1 }}"
        state: touch

[root@manager ~/ansible_variables]# var.yml 
play_var1: play_var1_sb1
play_var2: play_var2_sb2

host_vars

inventory
host_vars

[root@lb02 /ansible_varibles]# cat play1.yml 
- hosts: web
  tasks:
    - name: file
      file:
        path: /tmp/{{ file_name }}
        state: touch    
[root@lb02 /ansible_varibles]# cat hosts 
[web]

172.16.1.7
172.16.1.8

[web:vars]
file_name=oldboy_filename

对单个主机设置变量

mkdir host_vars
vim  host_vars/172.16.1.7 (设置变量)
host_vars/(IP 或者 域名)

group_vars

mkdir group_vars/
vim web.yml (对web主机组设置变量)
vim all.yml (对所有主机组设置变量)

extra-vars执行参数赋给变量

[root@lb02 /ansible_varibles]# cat play1.yml 
- hosts: web
  tasks:
    - name: file
      file:
        path: /tmp/{{ haha }}
        state: touch  
[root@lb02 /ansible_varibles]# ansible-playbook play1.yml --extra-vars "haha=sky.lxx_filename"

注:
优先级

1.extra

2.playbook
2.1) vars_files
2.2) vars

3.inventory
3.1) host_vars
3.2) group_vars
3.3) group_all

playbook变量注册

注册变量:register 关键字可以存储指定命令的输出结果到一个自定义的变量中

- hosts: web
  tasks:
    - name:
      shell: netstat -lnp
      register: System_state

    - name: Get System_state
      debug:
        msg: "{{ System_state }}"

facts变量

除了可以引用自己定义的变量外,ansible还有很多变量是通过facts所获取的,facts可以理解为ansible所收集到的每个远程主机的一些基本信息,如IPv4、IPv6、MAC地址、磁盘分区信息等。要引用facts变量只需要在变量名两边用双花括号引用,多个变量使用逗号分隔

Example:

'{{ ansible_all_ipv4_addresses }}','{{ ansible_all_ipv6_addresses }}'

采集本地主机一些基本信息

[root@lb02 /ansible_varibles]# ansible localhost -m setup

采集远程主机一些基本信息

[root@lb02 /ansible_varibles]# ansible 172.16.1.7 -m setup

playbook循环语句

1.装软件
- name: ensure a list of packages installed
  yum:
    name: "{{ packages }}"
  vars:
    packages:
    - httpd
    - httpd-tools

2.拷贝多分配置文件  1个tasks拷贝多个文件    字典
    - name: Copy Rsync Configure
      copy:
        src: "{{ item.src }}"
        dest: "{{ item.dest }}"
        mode: "{{ item.mode }}"
      loop:
        - { src: ./rsyncd.conf.j2 , dest: /etc/rsyncd.conf , mode: '0644' }
        - { src: ./rsync.passwd.j2  , dest: /etc/rsync.passwd , mode: '0600' }
      notify: Restart Rsync Server


3.批量启动服务      1个tasks启动多个服务     列表
    - name: Systemd Httpd Server
      systemd:
        name: "{{ item }}"
        state: started
        enabled: yes
      loop:
        - httpd
        - firewalld

示例:

使用ansible的循环,批量创建多个用户
	user: test01  group: adm    groups: lp
    user: test02  group: root   groups: sys*
[root@lb02 /ansible_varibles]# cat adduser.conf.yml 
- hosts: web
  tasks:
    - name: Create User
      user:
        name: "{{ item.name  }}"
        group: "{{ item.group }}"
        groups: "{{ item.groups }}"
        state: present
      loop:
        - { name: "test01" , group: "adm" , groups: "lp" } 
        - { name: "test02" , group: "root" , groups: "sys" } 

playbook判断语句

playbook中的条件判断语句使用when

1.根据不同的操作系统,安装不同的软件	
[root@manager ~/ansible_variables]# cat play_14.yml 
- hosts: all
  tasks:
    - name: Installed Httpd Server Centos
      yum:
        name: httpd
        state: present
      when: ( ansible_distribution == "Ubuntu" ) 
		
	
[root@manager ~/ansible_variables]# cat play_14.yml 
- hosts: all
  tasks:
    - name: Installed Httpd Server Centos
      yum:
        name: httpd
        state: present
      when: ( ansible_distribution == "CentOS" ) and 
	        ( ansible_distribution_major_version == "7")	
	
    - name: Installed Httpd Server Centos
      yum:
        name: httpd2
        state: present
      when: ( ansible_distribution == "CentOS" ) and  
	        ( ansible_distribution_major_version == "6")	
	

	2.根据不同的主机名称,配置不同的源     all-->   web--->nginx_repo
[root@manager ~/ansible_variables]# cat play_15.yml 
- hosts: all
  tasks:
    - name: This is when repo
      yum_repository:
        name: oldxu
        description: oldxu
        baseurl: http://nginx.org/packages/centos/$releasever/$basearch/
        gpgcheck: no
      when: ( ansible_hostname is match ("web*") ) 

      when: ( ansible_hostname is match ('web*') ) or 
            ( ansible_hostname is match ('lb*') ) 
     # 不匹配
    - name: Disable Firewalld
      systemd:
        name: firewalld
        state: stopped
      when: ( not ansible_hostname == "lb01" ) and  ##
            ( not ansible_hostname == "lb02" )      ##

Ansible Playbook Handlers(触发器)

1.特殊Tasks
2.不会被正常的TASKS调用。
3.当有notify调用时,才会被执行。
注意: 无论Handlers被调用多少次,最终只会在正常的Tasks结束后,才执行

force_handlers

	- hosts: web
	  force_handlers: yes    <---当handlers被调起,无论中间的tasks是否错误,都会执行handlers任务

Ansible Playbook tags(标签)

tag标签 (tasks较多时,需要对指定的某个tasks进行调试)
将tasks与标签捆绑-->  后期针对指定的tags进行执行
1.支持一个tasks对应一个tags标签
2.支持一个tasks对应多个tags标签

1.执行指定的标签
ansible-playbook redis_server.yml -t install
2.除了某个tags,其余都执行
ansible-playbook redis_server.yml --skip-tags(跳过install标签都执行) install

- hosts: nfs
  tasks:
    - name: NFS Installed
      yum:
        name: nfs-utils
        state: present
      tags: install
      tags:               (标签列表,支持一个tasks对应多个tags标签)
        - install
        - install_nfs

Ansible Playbook 异常处理

ignore_errors 忽略错误

[root@manager ~/ansible_tasks]# vim task_2.yml
	- hosts: all
	  tasks:
		- name: Ignore False
		  command: /bin/false
		  ignore_errors: yes

		- name: touch new file
		  file: path=/tmp/bgx_ignore state=touch

Ansible Roles

Roles

roles
1.目录结构规划 (必须)
2.大型项目全部都是roles

yml文件,用于定义此角色用到的各handler:在handler中使用include包含的其他的handler文件也应该位于此目录中;

files目录:存放由copy或script等模块调用的文件;

templates目录:templates模块会自动在此目录中寻找Jinja2模板文件;

tasks目录:至少应该包含一个名为main.yml的文件,其定义了此角色的任务列表;此文件可以使用include包含其他的位于此                  目录中的task文件;

handlers目录:此目录中应当包含一个main;

vars目录:应当包含一个main.yml文件,用于定义此角色用到的变量;

meta目录:应当包含一个main.yml文件,用于定义此角色的特殊设定及其依赖关系;ansible 1.3及其以后的版本才支持

default目录:为当前角色设定默认变量时使用此目录;应当包含一个main.yml文件;
目录结构:
	nginx
		tasks				<--tasks任务
			main.yml
		handlers			<--handlers触发器
			main.yml
		templates			<--模板文件
			main.yml
		vars				<--变量
			main.yml
		files				<--文件 tar|zip
		meta				<--依赖间关系

注: 自定义角色骨架目录

 ansible-galaxy init  role_name(自定义)

Roles流程图

在这里插入图片描述

keepalived 配置写法

[root@manager ~/ansible_tasks]# cat task5.yml 
- hosts: web
  tasks:
    - name: Configure Keepalived
      template:
        src: keepalived.conf.j2
        dest: /tmp/keepalived.conf

[root@manager ~/ansible_tasks]# cat keepalived.conf.j2 
  global_defs {
         router_id {{ ansible_hostname }}
  }

  vrrp_instance VIP_1 {
{% if ansible_hostname == "web01" %}    ###
     state MASTER
      priority 150
{% elif ansible_hostname == "web02" %}  
     state BACKUP
      priority 100
{% endif %}                             ###
      interface eth0
      virtual_router_id 1
      advert_int 1
      authentication {
          auth_type PASS
          auth_pass 1111
      }
      virtual_ipaddress {
		10.0.0.3
      }
  }

Roles示例

nginx+php+redis搭建可道云(引入负载均衡,高可用,https)

目录结构:

[root@m01 ~/ansible_role]# pwd
/root/ansible_role
[root@m01 ~/ansible_role]# tree
.
├── ansible.cfg
├── group_vars             **(设置所有主机组变量)**
│   └── all.yml
├── hosts                  **(主机清单保存到hosts文件)**
├── keepalived
│   ├── handlers           **(触发handlers)**
│   │   └── main.yml
│   ├── tasks              **(任务)**
│   │   └── main.yml
│   └── templates          **(存放配置文件)**
│       └── keepalived.conf.j2
├── kodcloud-proxy
│   ├── files              **(存放压缩文件)**
│   │   └── ssl_key.zip
│   ├── handlers
│   │   └── main.yml
│   ├── meta               **(依赖间关系)**
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   └── templates
│       ├── nginx_proxy.conf.j2
│       └── proxy_params.j2
├── kodcloud-web
│   ├── files
│   │   └── kodexplorer4.40.zip
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   └── templates
│       └── ansable.cloud.lxx.com.conf.j2
├── nginx-web
│   ├── handlers
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   └── templates
│       └── nginx.conf.j2
├── php
│   ├── handlers
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   └── templates
│       ├── php.ini.j2
│       └── php-www.j2
├── redis
│   ├── handlers
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   └── templates
│       └── redis.j2
└── top.yml

29 directories, 29 files

top.yml

[root@m01 ~/ansible_role]# pwd
/root/ansible_role
[root@m01 ~/ansible_role]# cat top.yml 
- hosts: web
  roles:
    - role: kodcloud-web
      tags: kodcloud-web

- hosts: lb
  roles:
    - role: kodcloud-proxy
      tags: kodcloud-proxy
   
    - role: keepalived
      tags: keepalived

- hosts: db01
  roles:
    - role: redis
      tags: redis 

group_vars

[root@m01 ~/ansible_role/group_vars]# pwd
/root/ansible_role/group_vars
[root@m01 ~/ansible_role/group_vars]# cat all.yml 
# Nginx-web

running_user: www
running_group: www
redis_server_ip: 172.16.1.51
redis_server_port: 6379
cloud_code_dir: /code/cloud
cloud_server_port: 80
cloud_server_name: ansible.lxx.com
 
 # Nginx-proxy
cloud_proxy_port: 80

hosts

[root@m01 ~/ansible_role]# cat hosts 
[web]
172.16.1.7
172.16.1.8

[lb]
172.16.1.5
172.16.1.6

[db01]
172.16.1.51

[lb01]
172.16.1.5

nginx-web

[root@m01 ~/ansible_role/nginx-web]# pwd
/root/ansible_role/nginx-web
[root@m01 ~/ansible_role/nginx-web]# ls
handlers  tasks  templates
[root@m01 ~/ansible_role/nginx-web]# cat handlers/main.yml 
- name: Restart Nginx Server
  systemd:
    name: nginx
    state: restarted

[root@m01 ~/ansible_role/nginx-web]# cat tasks/main.yml 
- name: Install Nginx
  yum: 
    name: nginx 
    state: present

- name: Configure Nginx
  template:
   src: nginx.conf.j2
   dest: /etc/nginx/nginx.conf
   owner: root
   group: root
   mode: '0644'
  notify: Restart Nginx Server
  
  - name: Systemd Nginx Server
  systemd:
    name: nginx
    state: started

[root@m01 ~/ansible_role/nginx-web]# ls 
handlers  tasks  templates
[root@m01 ~/ansible_role/nginx-web]# cat templates/nginx.conf.j2 

user  {{ running_user }};

php

[root@m01 ~/ansible_role/php]# pwd
/root/ansible_role/php
[root@m01 ~/ansible_role/php]# ls
handlers  tasks  templates
[root@m01 ~/ansible_role/php]# cat handlers/main.yml 
- name: Restart PHP Server
  systemd:
    name: php-fpm
    state: restarted

[root@m01 ~/ansible_role/php]# cat tasks/main.yml 
- name: Configure PHP-RPM PHP.INI Server
  template:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    owner: root
    group: root
    mode: '0644'
  loop:
    - { src: php.ini.j2 , dest: /etc/php.ini }
    - { src: php-www.j2 , dest: /etc/php-fpm.d/www.conf }
  notify: Restart PHP Server

- name: Systemd PHP Server
  systemd:
    name: php-fpm
    state: started
    enabled: yes

[root@m01 ~/ansible_role/php]# cat templates/php.ini.j2

session.save_handler = redis
session.save_path = "tcp://{{ redis_server_ip }}:{{ redis_server_port }}?weight=1&timeout=2.5"

[root@m01 ~/ansible_role/php]# cat templates/php-www.j2 

user = {{ running_user }}
group = {{ running_group }}

;php_value[session.save_handler] = files
;php_value[session.save_path]    = /var/lib/php/session

redis

[root@m01 ~/ansible_role/redis]# pwd
/root/ansible_role/redis
[root@m01 ~/ansible_role/redis]# ls
handlers  tasks  templates
[root@m01 ~/ansible_role/redis]# cat handlers/main.yml 
- name: Restart Redis Server
  systemd:
    name: redis 
    state: restarted

[root@m01 ~/ansible_role/redis]# cat tasks/main.yml 
- name: Configure Redis
  template:
    src: redis.j2
    dest: /etc/redis.conf
  notify: Restart Redis Server    

- name: Systemd Redis Server
  systemd:
    name: redis
    state: started
    enabled: yes


[root@m01 ~/ansible_role/redis]# cat templates/redis.j2

bind 127.0.0.1  {{ ansible_eth1.ipv4.address }}

keepalived

[root@m01 ~/ansible_role/keepalived]# pwd
/root/ansible_role/keepalived
[root@m01 ~/ansible_role/keepalived]# ls
handlers  tasks  templates
[root@m01 ~/ansible_role/keepalived]# cat handlers/main.yml 
- name: Restart Keepalived
  systemd:
    name: keepalived
    state: restarted

[root@m01 ~/ansible_role/keepalived]# cat tasks/main.yml 
- name: Install Keepalived
  yum:
    name: keepalived
    state: present

- name: Configure Keepalived 
  template:
    src: keepalived.conf.j2
    dest: /etc/keepalived/keepalived.conf
    owner: root
    group: root
    mode: '0644'
  notify: Restart Keepalived

- name: Systemd Keepalived
  systemd:
    name: keepalived
    state: started
    enabled: yes

[root@m01 ~/ansible_role/keepalived]# cat templates/keepalived.conf.j2 
! Configuration File for keepalived
global_defs {
         router_id {{ ansible_hostname }}
  }

  vrrp_instance VIP_1 {
{% if ansible_hostname == "lb01" %}    
     state MASTER
      priority 150
{% elif ansible_hostname == "lb02" %}  
     state BACKUP
      priority 100
{% endif %}                             
      interface eth0
      virtual_router_id 1
      advert_int 1
      authentication {
          auth_type PASS
          auth_pass 1111
      }
      virtual_ipaddress {
		10.0.0.3
      }
  }

kodcloud-web

[root@m01 ~/ansible_role/kodcloud-web]# pwd
/root/ansible_role/kodcloud-web
[root@m01 ~/ansible_role/kodcloud-web]# ls 
files  handlers  meta  tasks  templates
[root@m01 ~/ansible_role/kodcloud-web]# cd files/
[root@m01 ~/ansible_role/kodcloud-web/files]# ls
kodexplorer4.40.zip

[root@m01 ~/ansible_role/kodcloud-web]# cat handlers/main.yml 
- name: Restart Nginx Server
  systemd:
    name: nginx
    state: restarted

[root@m01 ~/ansible_role/kodcloud-web]# cat meta/main.yml 
dependencies:
  - nginx-web
  - php

[root@m01 ~/ansible_role/kodcloud-web]# cat tasks/main.yml 
- name: Create Nginx Vhost Configure
  template:
    src: ansable.cloud.lxx.com.conf.j2
    dest: /etc/nginx/conf.d/ansible.cloud.lxx.com.conf
  notify: Restart Nginx Server

- name: Create Cloud Directory
  file:
    path: "{{ cloud_code_dir  }}"
    owner: "{{ running_user }}"
    group: "{{ running_group }}"
    state: directory
    recurse: yes

- name: Copy Cloud Code
  unarchive:
    src: kodexplorer4.40.zip
    dest: "{{ cloud_code_dir }}"
    copy: yes
    owner: "{{ running_user  }}"
    group: "{{ running_group  }}"
    creates: "{{ cloud_code_dir }}/index.php"

[root@m01 ~/ansible_role/kodcloud-web]# cat templates/ansable.cloud.lxx.com.conf.j2 
server {
	listen {{ cloud_server_port  }};
	server_name {{ cloud_server_name  }};
	root {{ cloud_code_dir  }};

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

kodcloud-proxy

[root@m01 ~/ansible_role/kodcloud-proxy]# pwd
/root/ansible_role/kodcloud-proxy
[root@m01 ~/ansible_role/kodcloud-proxy]# ls
files  handlers  meta  tasks  templates
[root@m01 ~/ansible_role/kodcloud-proxy]# cd files/
[root@m01 ~/ansible_role/kodcloud-proxy/files]# ls
ssl_key.zip

[root@m01 ~/ansible_role/kodcloud-proxy]# cat handlers/main.yml 
- name: Restart Nginx Server
  systemd:
    name: nginx
    state: restarted

[root@m01 ~/ansible_role/kodcloud-proxy]# cat meta/main.yml 
dependencies:
  - nginx-web
 
[root@m01 ~/ansible_role/kodcloud-proxy]# cat tasks/main.yml 
- name: Configure LB 
  template:
    src: "{{ item.src }}"
    dest: "{{ item.dest  }}"
  loop:
    - { src: nginx_proxy.conf.j2 , dest: /etc/nginx/conf.d/proxy_cloud.com.conf }
    - { src:  proxy_params.j2 , dest: /etc/nginx/proxy_params }
  notify: Restart Nginx Server

- name: Create SSL_KEY
  file:
    path: /etc/nginx/ssl_key
    state: directory

- name: Create SSL_KEY File
  unarchive:
        src: ssl_key.zip
        dest: /etc/nginx/ssl_key
        copy: yes
        creates: "/etc/nginx/ssl_key/server.key"

[root@m01 ~/ansible_role/kodcloud-proxy]# cat templates/nginx_proxy.conf.j2 
upstream {{ cloud_server_name  }} {
   
  {% for host in groups['web'] %}
   
	 server {{ host  }}:{{ cloud_proxy_port  }};      
    
  {%  endfor  %}

}
  server {
	listen 443 ssl;
        server_name {{ cloud_server_name }};
        ssl_certificate ssl_key/server.crt;
	ssl_certificate_key ssl_key/server.key;

   location / {
	proxy_pass http://{{ cloud_server_name  }};
        include proxy_params;
}
}

[root@m01 ~/ansible_role/kodcloud-proxy]# cat templates/proxy_params.j2 
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Connection "";

proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;

proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值