第二十四章 ansible自动化运维工具 (3)Playbook进阶使用-roles

148 阅读5分钟

@[TOC](第二十四章 ansible自动化运维工具 (3)Playbook进阶使用-roles)


示例:迭代嵌套子变量

ansible主机

[root@ansible playbook]# pwd
/data/playbook

[root@ansible playbook]# vim items2.yml 	#创建三个组、在和三个用户组合起来

---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: add some groups
      group: name={{ item }} state=present
      with_items:
        - group1
        - group2
        - group3
    - name: add some users
      user: name={{ item.name }} group={{ item.group }} state=present
      with_items:
        - { name: 'user1', group: 'group1' }
        - { name: 'user2', group: 'group2' }
        - { name: 'user3', group: 'group3' }

[root@ansible playbook]# ansible-playbook -C items2.yml
[root@ansible playbook]# ansible-playbook items2.yml

6/18

#查看用户创建情况[user1.user2.user3]
[root@centos6 ~]$ getent passwd
...
user1:x:501:501::/home/user1:/bin/bash
user2:x:502:502::/home/user2:/bin/bash
user3:x:503:503::/home/user3:/bin/bash

#查看用户是否有对应的组、如:'user1'用户'group1'组
[root@centos6 ~]$ id user1
uid=501(user1) gid=501(group1) groups=501(group1)
[root@centos6 ~]$ id user2
uid=502(user2) gid=502(group2) groups=502(group2)
[root@centos6 ~]$ id user3
uid=503(user3) gid=503(group3) groups=503(group3)
#查看用户创建情况[user1.user2.user3]
[root@centos7-1 ~]# getent passwd
...
user1:x:1001:1001::/home/user1:/bin/bash
user2:x:1002:1002::/home/user2:/bin/bash
user3:x:1003:1003::/home/user3:/bin/bash

#查看用户是否有对应的组、如:'user1'用户'group1'组
[root@centos7-1 ~]# id user1
uid=1001(user1) gid=1001(group1) groups=1001(group1)
[root@centos7-1 ~]# id user2
uid=1002(user2) gid=1002(group2) groups=1002(group2)
[root@centos7-1 ~]# id user3
uid=1003(user3) gid=1003(group3) groups=1003(group3)

Playbook中template for if(for循环)

  • 示例1

ansible主机

[root@ansible playbook]# vim for1.yml
---
- hosts: appsrvs		<--针对哪些主机
  remote_user: root
  vars:					<--变量值
    ports:			<--变量值由'ports'生成,由来:因为此处定义为'ports'。
      - 81			<--变量中存的元素	
      - 82
      - 83
  tasks:
    - name: config
      template: src=server.conf.j2 dest=/data/server.conf 

下图中的'ports'由来

*[ports]: 是从上图中定义的。

[root@ansible playbook]# vim templates/server.conf.j2
{% for port in ports %}	 <--for循环定义变量值为'ports'、是从上面文件定义的'ports'中取值
server {
  listen {{ port }}
}
{% endfor %}

[root@ansible playbook]# ansible-playbook -C for1.yml
[root@ansible playbook]# ansible-playbook for1.yml

18/28主机

#显示结果18/28一致、此处以18为例
[root@centos7-1 ~]# cat /data/server.conf 
server {
  listen 81
}
server {
  listen 82
}
server {
  listen 83
}
  • 示例2:变量赋值

ansible主机

[root@ansible playbook]# cp for1.yml for2.yml
[root@ansible playbook]# vim for2.yml
---
- hosts: appsrvs
  remote_user: root
  vars:
    ports:
      - listen_port: 81		<--变量赋值:如'listen_port'表示变量、'81'表示值
      - listen_port: 82
      - listen_port: 83
  tasks:
    - name: config
      template: src=server2.conf.j2 dest=/data/server2.conf


[root@ansible playbook]# cp templates/server.conf.j2 templates/server2.conf.j2
[root@ansible playbook]# vim templates/server2.conf.j2
{% for port in ports %}
server {
  listen {{ port.listen_port }}
}
{% endfor %}


[root@ansible playbook]# ansible-playbook for2.yml

18/28主机

#显示结果
[root@centos7-1 ~]# cat /data/server2.conf 
server {
  listen 81
}
server {
  listen 82
}
server {
  listen 83
}
  • 示例3:字典

ansible主机

[root@ansible playbook]# cp for2.yml for3.yml 
[root@ansible playbook]# vim for3.yml	#嵌入字典、如:'web1'字典内我们定义了3个值。
---
- hosts: appsrvs
  remote_user: root
  vars:
    ports:
      - web1:								<--字典
        listen_port: 81						<--值
        name: web1.mgdu.com					<--值
        dir: /data/web1						<--值
      - web2:
        listen_port: 82
        name: web2.mgdu.com
        dir: /data/web2
      - web3:
        listen_port: 83
        name: web3.mgdu.com
        dir: /data/web3
  tasks:
    - name: config
      template: src=server3.conf.j2 dest=/data/server3.conf


[root@ansible playbook]# cp templates/server2.conf.j2 templates/server3.conf.j2 
[root@ansible playbook]# vim templates/server3.conf.j2 
{% for port in ports %}
server {
  listen {{ port.listen_port }}		<--对应上面文件的'listen_port'
  server_name {{ port.name }}		<--对应上面文件的'name'
  root {{ port.dir }}				<--对应上面文件的'dir'
}
{% endfor %}


[root@ansible playbook]# ansible-playbook -C for3.yml
[root@ansible playbook]# ansible-playbook for3.yml

18/28主机

#显示结果
[root@centos7-1 ~]# cat /data/server3.conf 
server {
  listen 81
  server_name web1.mgdu.com
  root /data/web1
}
server {
  listen 82
  server_name web2.mgdu.com
  root /data/web2
}
server {
  listen 83
  server_name web3.mgdu.com
  root /data/web3
}
  • 示例4:条件判断
[root@ansible playbook]# cp for3.yml for4.yml 
[root@ansible playbook]# vim for4.yml 	#条件判断、没有name条件就不生成
---
- hosts: appsrvs
  remote_user: root
  vars:
    ports:
      - web1:
        listen_port: 81
        #name: web1.mgdu.com			<--注释掉此行
        dir: /data/web1
      - web2:
        listen_port: 82
        name: web2.mgdu.com
        dir: /data/web2
      - web3:
        listen_port: 83
        #name: web3.mgdu.com			<--注释掉此行
        dir: /data/web3
  tasks:
    - name: config
      template: src=server4.conf.j2 dest=/data/server4.conf


[root@ansible playbook]# cp templates/server3.conf.j2 templates/server4.conf.j2  
[root@ansible playbook]# vim templates/server4.conf.j2 
{% for port in ports %}
server {
  listen {{ port.listen_port }}
{% if port.name is defined %}		<--if条件判断
  server_name {{ port.name }}		<--判断'port.name'是否存在、不存在就不生成
{% endif %}			<--判断结束
  root {{ port.dir }}
}
{% endfor %}


[root@ansible playbook]# ansible-playbook for4.yml -C
[root@ansible playbook]# ansible-playbook for4.yml

18/28主机

#显示结果、发现刚刚注释掉的两行内容没有生成
[root@centos7-1 ~]# cat /data/server4.conf 
server {
  listen 81
  root /data/web1
}
server {
  listen 82
  server_name web2.mgdu.com
  root /data/web2
}
server {
  listen 83
  root /data/web3
}

roles(角色)模块

roles

  • ansible自1.2版本引入的新特性,用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲,roles就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中,并可以便捷地include它们的一种机制。角色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中

复杂场景:建议使用roles,代码复用度高

  • 变更指定主机或主机组
  • 如命名不规范维护和传承成本大
  • 某些功能需多个Playbook,通过includes即可实现

roles目录结构、官方推荐目录 /etc/ansible/roles

  • 每个角色,以特定的层级目录结构进行组织
  • roles目录结构: (playbook.yml和roles/平级目录)
playbook.yml 
roles/		
├── project/
├── tasks/
├── files/
├── vars
├── templates/
├── handlers/
├── default/
└──meta/

ansible主机

#创建目录
[root@ansible playbook]# mkdir -pv /data/playbook/roles/{mysql,nginx}/{tasks,files}

#查看目录结构
[root@ansible playbook]# tree /data/playbook/roles/
/data/playbook/roles/
├── mysql
│   ├── files
│   └── tasks
└── nginx
    ├── files
    └── tasks

6 directories, 0 files

1. roles(角色)模块:nginx搭建

  1. 创建账户
[root@ansible playbook]# cd roles/nginx/tasks/
[root@ansible tasks]# pwd
/data/playbook/roles/nginx/tasks
[root@ansible tasks]# touch user.yml install.yml config.yml service.yml

#第一步:创建账户和组
[root@ansible tasks]# vim user.yml
- name: create user
  user: name=nginx shell=/sbin/nologin system=yes create_home=no	#创建用户nginx、shell类型、系统账号、不创建家目录	
  1. 安装软件包
[root@ansible tasks]# vim install.yml 
- name: install
  yum: name=nginx
  1. 写配置文件
[root@ansible tasks]# cd ../files/
[root@ansible files]# pwd
/data/playbook/roles/nginx/files

#把配置文件拷贝到当前目录
[root@ansible files]# cp /etc/nginx/nginx.conf .

#修改配置文件
[root@ansible files]# vim nginx.conf
...
    server {
        listen       9527;		<--ipv4端口号
        listen       [::]:9527;		<--ipv6端口号
...
[root@ansible files]# cd ../tasks/
[root@ansible tasks]# pwd
/data/playbook/roles/nginx/tasks

#配置文件
[root@ansible tasks]# vim config.yml
- name: config
  copy: src=nginx.conf dest=/etc/nginx/
  1. 启动服务
#启动服务
[root@ansible tasks]# vim service.yml 
- name: service
  service: name=nginx state=started enabled=yes
[root@ansible tasks]# vim main.yml		#执行次序
- include: user.yml			<--1. 创建账户
- include: install.yml		<--2. 安装软件包
- include: config.yml		<--3. 配置文件
- include: service.yml		<--4. 启动服务
[root@ansible tasks]# cd ..
[root@ansible nginx]# pwd
/data/playbook/roles/nginx

#查看一下nginx目录结构、可以看到刚刚写过、改过的文件
[root@ansible nginx]# tree
.
├── files
│   └── nginx.conf
└── tasks
    ├── config.yml
    ├── install.yml
    ├── main.yml
    ├── service.yml
    └── user.yml

2 directories, 6 files
#进到与roles同级的目录里
[root@ansible nginx]# cd ../..
[root@ansible playbook]# pwd
/data/playbook				#与roles同级的目录里
[root@ansible playbook]# ll		#查看一下是否同级
...
drwxr-xr-x  4 root root        32 Jun 27 00:30 roles		<--
drwxr-xr-x  2 root root       183 Jun 26 23:56 templates
...

#调用nginx角色
[root@ansible playbook]# vim nginx_role.yml
- hosts: appsrvs			#那些主机【appsrvs】、调用‘nginx’角色

  roles:						#角色
    - role: nginx				#nginx

18/28主机 快照(初始化)

连接外网: 方法1: 虚拟机设置-->添加NAT网卡-->systemctl restart network-->ping 1.1.1.1 方法2: 网卡配置文件中-->添加'GATEWAY=192.168.37.2,DNS1=114.114.114.114'-->systemctl restart network-->ping 1.1.1.1

[root@centos7-1 ~]# rpm -q nginx
package nginx is not installed		#未安装nginx

#添加epel源
[root@centos7-1 ~]# vim /etc/yum.repos.d/base.repo
[base]
name=cdrom base
baseurl=file:///misc/cd
gpgcheck=0

[epel]
name=aliyun epel
#baseurl=https://mirrors.aliyun.com/epel/$releasever/$basearch/
baseurl=https://mirrors.aliyun.com/epel/$releasever/$basearch/
gpgcheck=0
enabled=1

ansible主机

#ansible key验证(18/28主机初始化后需要重新做key验证)
[root@ansible playbook]# ssh-copy-id 192.168.37.18
[root@ansible playbook]# ssh-copy-id 192.168.37.28
[root@ansible playbook]# ansible-playbook nginx_role.yml

18/28主机

#发现nginx的ipv4和ipv6端口号都为'9527'、
[root@centos7-1 ~]# ss -ntlp|grep 9527
LISTEN     0      128          *:9527                     *:*                   users:(("nginx",pid=20511,fd=6),("nginx",pid=20510,fd=6),("nginx",pid=20509,fd=6),("nginx",pid=20508,fd=6),("nginx",pid=20507,fd=6))
LISTEN     0      128         :::9527                    :::*                   users:(("nginx",pid=20511,fd=7),("nginx",pid=20510,fd=7),("nginx",pid=20509,fd=7),("nginx",pid=20508,fd=7),("nginx",pid=20507,fd=7))

#如果需要更改端口、怎么办? ansible主机

#更改nginx端口号
[root@ansible playbook]# vim roles/nginx/files/nginx.conf 
...
    server {
        listen       80;	<--
        listen       [::]:80;	<--
...
[root@ansible playbook]# cd roles/nginx/
[root@ansible nginx]# pwd
/data/playbook/roles/nginx


[root@ansible nginx]# mkdir handlers
[root@ansible nginx]# vim handlers/main.yml		#触发重启服务
- name: restart service			<--名称要一致
  service: name=nginx state=restarted


[root@ansible nginx]# cd tasks/
[root@ansible tasks]# vim config.yml
- name: config
  copy: src=nginx.conf dest=/etc/nginx/
  notify: restart service		<--触发重启、名称要和上面一致

#目录结构
[root@ansible nginx]# tree
.
├── files
│   └── nginx.conf
├── handlers
│   └── main.yml
└── tasks
    ├── config.yml
    ├── install.yml
    ├── main.yml
    ├── service.yml
    └── user.yml

3 directories, 7 files

[root@ansible tasks]# cd /data/playbook/		#回到与roles/文件同级目录中
[root@ansible playbook]# ansible-playbook -C nginx_role.yml
[root@ansible playbook]# ansible-playbook nginx_role.yml

18/28主机

#nginx端口号为80
[root@centos7-1 ~]# ss -ntlp|grep 80
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=21745,fd=6),("nginx",pid=21744,fd=6),("nginx",pid=21743,fd=6),("nginx",pid=21742,fd=6),("nginx",pid=21741,fd=6))
LISTEN     0      128         :::80                      :::*                   users:(("nginx",pid=21745,fd=7),("nginx",pid=21744,fd=7),("nginx",pid=21743,fd=7),("nginx",pid=21742,fd=7),("nginx",pid=21741,fd=7))

浏览器打开"192.168.37.18"、默认端口为80 在这里插入图片描述

#nginx页面文件
[root@centos7-1 ~]# cd /usr/share/nginx/html/
#备份页面文件
[root@centos7-1 html]# cp index.html{,.bak}
#修改页面文件内容
[root@centos7-1 html]# vim index.html
<h1>hello world</h1>

页面内容发生变化 在这里插入图片描述ansible主机

#nginx测试页面写到nginx角色files的index.html中
[root@ansible playbook]# cd roles/nginx/files/
[root@ansible files]# vim index.html
<h1>hello world!</h1>

#进到nginx角色目录
[root@ansible files]# pwd
/data/playbook/roles/nginx/files
[root@ansible files]# cd ..
[root@ansible nginx]# ls
files  handlers  tasks

#准备网页文件
[root@ansible nginx]# vim tasks/data.yml
- name: data file
  copy: src=index.html dest=/usr/share/nginx/html/

[root@ansible nginx]# vim tasks/main.yml 	#执行次序
- include: user.yml
- include: install.yml
- include: config.yml
- include: data.yml		<--html网页文件
- include: service.yml
#回到roles同级目录中
[root@ansible nginx]# cd ../../
[root@ansible playbook]# ansible-playbook -C nginx_role.yml
[root@ansible playbook]# ansible-playbook nginx_role.yml

18/28主机:浏览器页面发生变化

在这里插入图片描述

2. roles(角色)模块:apache搭建

  1. 安装apache
[root@ansible playbook]# pwd
/data/playbook
[root@ansible playbook]# mkdir -pv roles/httpd/{tasks,files,templates,var}
[root@ansible playbook]# cd roles/httpd/tasks/
[root@ansible tasks]# touch install.yml config.yml data.yml service.yml
[root@ansible tasks]# ls > main.yml  #把刚刚创建4个文件、生成到main.yml里

#安装apache
[root@ansible tasks]# vim install.yml 
- name: install.yml
  yum: name=httpd

[root@ansible tasks]# vim config.yml
- name: config file
  template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  1. 配置文件
[root@ansible tasks]# pwd
/data/playbook/roles/httpd/tasks
[root@ansible tasks]# cd ..
#拷贝文件
[root@ansible httpd]# cp /etc/httpd/conf/httpd.conf templates/httpd.conf.j2
#修改配置文件内容
[root@ansible httpd]# vim templates/httpd.conf.j2
...
Listen {{ httpd_port }}	<--监听端口
User {{ username }}	<--用户账号
Group {{ groupname }}	<--用户组
...
#vars/变量文件夹、专门放变量
[root@ansible httpd]# vim vars/main.yml
username: daemon
groupname: daemon
  1. 数据文件
#数据文件
[root@ansible httpd]# cd tasks/
[root@ansible tasks]# vim data.yml
- name: data file
  copy: src=roles/nginx/files/index.html dest=/var/www/html	#此处'roles/nginx/files/index.html'为相对路径、从roles开始描述。调用nginx的网页文件。
  1. 启动服务
#启动服务
[root@ansible tasks]# vim service.yml
- name: service
  service: name=httpd state=started enabled=yes
[root@ansible tasks]# vim main.yml	#启动次序
- include: install.yml		<--安装软件包
- include: config.yml		<--配置文件
- include: data.yml			<--数据文件
- include: service.yml		<--启动服务
[root@ansible tasks]# cd ..

#查看apache目录结构
[root@ansible httpd]# tree
.
├── files
├── tasks
│   ├── config.yml
│   ├── data.yml
│   ├── install.yml
│   ├── main.yml
│   └── service.yml
├── templates
│   └── httpd.conf.j2			<--模板文件、写了用户的变量名
└── vars
    └── main.yml				<--专门放变量

4 directories, 7 files
#回到roles平级目录
[root@ansible httpd]# cd ../../
[root@ansible playbook]# vim httpd_role.yml
- hosts: appsrvs		<--针对主机

  roles:		<--角色
    - httpd		<--什么角色?如'httpd'角色
#注意:如果配置文件中、下面还有针对[appsrvs]组中主机的端口变量、此处将被下面端口变量覆盖
[root@ansible playbook]# vim /etc/ansible/hosts
...
[appsrvs]
192.168.37.18 httpd_port=8018		<--端口变量'8018'
192.168.37.28 httpd_port=8028		<--端口变量'8028'
...

[root@ansible playbook]# ansible-playbook -C httpd_role.yml
[root@ansible playbook]# ansible-playbook httpd_role.yml

18/28主机:查看httpd端口情况

[root@centos7-1 ~]# ss -ntlp|grep 8018	#18主机:端口情况8018
LISTEN     0      128         :::8018                    :::*                   users:(("httpd",pid=75083,fd=4),("httpd",pid=75082,fd=4),("httpd",pid=75081,fd=4),("httpd",pid=75080,fd=4),("httpd",pid=75079,fd=4),("httpd",pid=75076,fd=4))

[root@centos7-2 ~]# ss -ntlp|grep 8028	#28主机:端口情况8028
LISTEN     0      128         :::8028                    :::*                   users:(("httpd",pid=24193,fd=4),("httpd",pid=24192,fd=4),("httpd",pid=24190,fd=4),("httpd",pid=24189,fd=4),("httpd",pid=24188,fd=4),("httpd",pid=24185,fd=4))

浏览器测试 在这里插入图片描述在这里插入图片描述

3. roles(角色)模块:mariadb搭建

#可参考、之前的mariadb模板文件、内容如下
[root@ansible playbook]# cat install_mariadb.yml
---
- hosts: 192.168.37.6
  remote_user: root

  tasks:
    - name: user 
      user: name=mysql system=yes home=/data/mysql create_home=no shell=/sbin/nologin
    - name: unarchive 
      unarchive: src=/data/playbook/mariadb-10.2.25-linux-x86_64.tar.gz dest=/usr/local/ owner=root group=root
    - name: mysql link
      file: src=/usr/local/mariadb-10.2.25-linux-x86_64 dest=/usr/local/mysql state=link
    - name: mysql datadir
      file: path=/data/mysql state=directory
    - name: mysql datadir owner group
      file: path=/data/mysql state=directory owner=mysql group=mysql 
    - name: mysql database
      shell: chdir=/usr/local/mysql/ scripts/mysql_install_db --datadir=/data/mysql --user=mysql
    - name: path var
      copy: content='PATH=/usr/local/mysql/bin:$PATH' dest=/etc/profile.d/mysql.sh
    - name: config
      copy: src=/data/playbook/my-huge.cnf dest=/etc/my.cnf
    - name: service file
      shell: cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
    - name: start service
      shell: /etc/init.d/mysqld start 
[root@ansible playbook]# cd roles/mysql/tasks/

#创建文件(用户账号、解压缩、软连接、文件夹、数据库、变量、配置文件、脚本、服务)
[root@ansible tasks]# touch user.yml unarchive.yml link.yml datadir.yml database.yml var.yml config.yml script.yml service.yml
#创建用户账号
[root@ansible tasks]# cat > user.yml
- name: user 
  user: name=mysql system=yes home=/data/mysql create_home=no shell=/sbin/nologin
^C
#解压缩
[root@ansible tasks]# vim unarchive.yml 
- name: unarchive
  unarchive: src=mariadb-10.2.25-linux-x86_64.tar.gz dest=/usr/local/ owner=root group=root
^C
#软连接
[root@ansible tasks]# cat > link.yml 
- name: mysql link
  file: src=/usr/local/mariadb-10.2.25-linux-x86_64 dest=/usr/local/mysql state=link
^C
#文件夹
[root@ansible tasks]# cat > datadir.yml 
- name: mysql datadir owner group
  file: path=/data/mysql state=directory owner=mysql group=mysql
^C
#数据库
[root@ansible tasks]# cat > database.yml 
- name: mysql database
  shell: chdir=/usr/local/mysql/ scripts/mysql_install_db --datadir=/data/mysql --user=mysql
^C
#变量
[root@ansible tasks]# cat > var.yml 
- name: path var
  copy: content='PATH=/usr/local/mysql/bin:$PATH' dest=/etc/profile.d/mysql.sh
^C
#配置文件
[root@ansible tasks]# cat > config.yml 
- name: config
  shell: cp /usr/local/mysql/support-files/my-huge.cnf /etc/my.cnf
^C
#配置文件2、修改mysql配置文件、指定路径
[root@ansible tasks]# vim config2.yml
- name: config file2
  shell: sed -i '/\[mysqld\]/a datadir=/data/mysql' /etc/my.cnf
#脚本
[root@ansible tasks]# cat > script.yml 
- name: service file
  shell: cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
^C
#服务
[root@ansible tasks]# cat > service.yml 
- name: start service 
  shell: /etc/init.d/mysqld start
^C
[root@ansible tasks]# for file in *;do echo "- include: $file" >> main.yml;done
[root@ansible tasks]# vim main.yml 	#调顺序
- include: user.yml
- include: unarchive.yml
- include: link.yml
- include: datadir.yml
- include: database.yml
- include: var.yml
- include: config.yml
- include: config2.yml
- include: script.yml
- include: service.yml

mariadb-10.2.25下载

[root@ansible tasks]# cd ../files/
[root@ansible files]# rz -E		#上传文件
[root@ansible files]# ls
mariadb-10.2.25-linux-x86_64.tar.gz
[root@ansible files]# cd ../../../
[root@ansible playbook]# pwd
/data/playbook

#查看目录结构
[root@ansible playbook]# tree roles/mysql/
roles/mysql/
├── files
│   └── mariadb-10.2.25-linux-x86_64.tar.gz
└── tasks
    ├── config2.yml
    ├── config.yml
    ├── database.yml
    ├── datadir.yml
    ├── link.yml
    ├── main.yml
    ├── script.yml
    ├── service.yml
    ├── unarchive.yml
    ├── user.yml
    └── var.yml

2 directories, 12 files


[root@ansible playbook]# vim mysql_role.yml
- hosts: appsrvs

  roles:
    - mysql


[root@ansible playbook]# ansible-playbook mysql_role.yml

18/28主机

#可以端口发现、mysql端口号'3306'开启
[root@centos7-1 ~]# ss -ntlp |grep mysql
LISTEN     0      80          :::3306                    :::*                   users:(("mysqld",pid=28243,fd=21))
[root@centos7-1 ~]# mysql
bash: mysql: command not found...
[root@centos7-1~]# . /etc/profile.d/mysql.sh	#运行完此步骤、使变量生效或退出此主机(37.18)远程窗口重新登录、即可进入mysql
[root@centos7-1 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 11
Server version: 10.2.25-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

针对不同版本应用不同角色:CentOS6装httpd、CentOS7装nginx

前提

ansible主机

#卸载ansible所有主机httpd、nginx服务。(工作中慎用、此处为实验需要)
[root@ansible ~]# ansible all -m yum -a 'name=httpd,nginx state=absent'

6/18/28主机

#查看是否nginx和httpd卸载
[root@centos6 ~]$ rpm -q nginx httpd
package nginx is not installed		<--未安装软件包 nginx 
package httpd is not installed		<--未安装软件包 httpd

[root@centos7-1 ~]# rpm -q nginx httpd
package nginx is not installed
package httpd is not installed

[root@centos7-2 ~]# rpm -q nginx httpd
package nginx is not installed
package httpd is not installed

实验开始 ansible主机

[root@ansible ~]# cd /data/playbook/
[root@ansible playbook]# vim httpd_nginx_role.yml	#判断脚本
- hosts: all	<--针对所有主机

  roles:
    - { role: httpd, when: ansible_distribution_major_version=="6" }	<--版本6、运行httpd
    - { role: nginx, when: ansible_distribution_major_version=="7" }	<--版本7、运行nginx

6主机[需要用centos6的httpd模板、拷贝到37.7主机中] 方法1:

[root@centos6 ~]$ yum install -y httpd

#把httpd.conf配置文件传过去
[root@centos6 ~]$ scp /etc/httpd/conf/httpd.conf 192.168.37.7:/data/playbook/roles/httpd/templates/httpd.conf.j2

方法2: 点此下载:CentOS6版本的httpd.conf模板文件 保存到:192.168.37.7主机‘/data/playbook/roles/httpd/templates/’目录下、改名’httpd.conf.j2‘

ansible主机

[root@ansible playbook]# ansible-playbook httpd_nginx_role.yml

6主机

#6版本、有httpd端口80
[root@centos6 ~]$ ss -ntlp|grep httpd
LISTEN     0      128                      :::80                      :::*      users:(("httpd",8411,5),("httpd",8415,5),("httpd",8416,5),("httpd",8417,5),("httpd",8418,5),("httpd",8419,5),("httpd",8420,5),("httpd",8421,5),("httpd",8422,5))

18/28主机

#7版本、有nginx端口80
[root@centos7-1 ~]# ss -tnlp |grep nginx
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=33578,fd=6),("nginx",pid=33577,fd=6),("nginx",pid=33576,fd=6),("nginx",pid=33575,fd=6),("nginx",pid=33574,fd=6))
LISTEN     0      128         :::80                      :::*                   users:(("nginx",pid=33578,fd=7),("nginx",pid=33577,fd=7),("nginx",pid=33576,fd=7),("nginx",pid=33575,fd=7),("nginx",pid=33574,fd=7))

角色里面还可以用变量

ansible主机

#修改6版本httpd配置文件
[root@ansible playbook]# vim roles/httpd/templates/httpd.conf.j2 
...
Listen {{ httpd_port }}		<--端口号改为变量
...

[root@ansible playbook]# vim httpd_nginx_role.yml 

- hosts: all

  roles:
    - {role: httpd, httpd_port: 1234, when: ansible_distribution_major_version=="6"}		<--添加变量httpd_port: 1234
    - {role: nginx, when: ansible_distribution_major_version=="7"}
[root@ansible playbook]# cd roles/httpd/tasks/
[root@ansible tasks]# vim config.yml

- name: config file
  template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  notify: restart		<--触发重启服务
  
[root@ansible tasks]# cd ..
[root@ansible httpd]# mkdir handlers
[root@ansible httpd]# vim handlers/main.yml
- name: restart		<--触发重启服务
  service: name=httpd state=restarted

[root@ansible httpd]# cd ../../
[root@ansible playbook]# ansible-playbook httpd_nginx_role.yml

6主机

#httpd服务重启了、并且端口变成了1234
[root@centos6 ~]$ ss -ntlp|grep httpd
LISTEN     0      128                      :::1234                    :::*      users:(("httpd",9780,6),("httpd",9783,6),("httpd",9784,6),("httpd",9785,6),("httpd",9786,6),("httpd",9787,6),("httpd",9788,6),("httpd",9789,6),("httpd",9790,6))

roles playbook tags标签使用[定义角色时候加标签]

#添加标签
[root@ansible playbook]# vim httpd_nginx_role.yml 

- hosts: all

  roles:
    - {role: httpd, httpd_port: 1234, when: ansible_distribution_major_version=="6"}
    - {role: nginx, when: ansible_distribution_major_version=="7", tags: web}	<---标签tags: web、以后这个7版本的nginx就有标签了


#以后就可以挑着标签执行、而不是全部执行
[root@ansible playbook]# ansible-playbook -t web httpd_nginx_role.yml 


#也可添加多个标签
[root@ansible playbook]# vim httpd_nginx_role.yml

- hosts: all

  roles:
    - {role: httpd, httpd_port: 1234, when: ansible_distribution_major_version=="6"}
    - {role: nginx, when: ansible_distribution_major_version=="7", tags: ["web","nginx"]}<---以后这个7版本的nginx就有2个标签了


[root@ansible playbook]# ansible-playbook -t nginx httpd_nginx_role.yml 

memcached提供缓存服务

[root@ansible playbook]# pwd
/data/playbook
[root@ansible playbook]# cd roles/
[root@ansible roles]# mkdir -pv memcached/{tasks,files,templates}
[root@ansible roles]# yum install -y memcached
[root@ansible roles]# cat /etc/sysconfig/memcached 
PORT="11211"			#Memcached用来运行的端口
USER="memcached"		#Memcached服务的启动守护程序。
MAXCONN="1024"			#用于将最大同时连接数设置为1024的值。对于繁忙的Web服务器,您可以根据需要增加任何数量。
CACHESIZE="64"			#缓存大小
OPTIONS=""				#选项:设置服务器的IP地址,以便Apache或Nginx Web服务器可以连接到它。
[root@ansible roles]# cd memcached/
[root@ansible memcached]# cp /etc/sysconfig/memcached templates/memcached.j2
[root@ansible memcached]# vim templates/memcached.j2

PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="{{ ansible_memtotal_mb//4 }}"		<--内存总大小除4、取整数
OPTIONS=""
[root@ansible memcached]# cd tasks/
[root@ansible tasks]# touch {install,config,service}.yml

[root@ansible tasks]# vim install.yml 	#安装包
- name: install
  yum: name=memcached


[root@ansible tasks]# vim config.yml 	#配置文件
- name: config
  template: src=memcached.j2 dest=/etc/sysconfig/memcached


[root@ansible tasks]# vim service.yml 	#启动服务
- name: service
  service: name=memcached state=started enabled=yes                                               

[root@ansible tasks]# for file in * ;do echo "- include: $file" >> main.yml ;done

[root@ansible tasks]# vim main.yml 	#启动顺序
- include: install.yml
- include: config.yml
- include: service.yml


[root@ansible memcached]# cd ../..
[root@ansible playbook]# vim memcached_role.yml

- hosts: appsrvs

  roles:
    - memcached

18/28主机:把内存大小调一下【18:2G、28:4G】看内存大小

[root@centos7-1 ~]# free -h
              total        used        free      shared  buff/cache   available
Mem:           1.8G        351M        1.1G         12M        387M        1.2G
Swap:          4.0G          0B        4.0G


[root@centos7-2 ~]# free -h
              total        used        free      shared  buff/cache   available
Mem:           3.7G        360M        2.9G         14M        452M        3.1G
Swap:          4.0G          0B        4.0G

ansible主机

[root@ansible playbook]# ansible-playbook -C memcached_role.yml
[root@ansible playbook]# ansible-playbook memcached_role.yml

18/28主机:缓存大小发生变化

[root@centos7-1 ~]# cat /etc/sysconfig/memcached 
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="454"		<--
OPTIONS=""

[root@centos7-2 ~]# cat /etc/sysconfig/memcached 
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="942"		<--
OPTIONS=""

查看memcached端口、端口号'11211'

[root@centos7-1 ~]# ss -ntlp
...
LISTEN     0      128                       *:11211                                 *:*                   users:(("memcached",pid=9454,fd=26))
LISTEN     0      128                      :::11211                                :::*                   users:(("memcached",pid=9454,fd=27))
...

[root@centos7-2 ~]# ss -ntlp |grep memcached
LISTEN     0      128          *:11211                    *:*                   users:(("memcached",pid=20594,fd=26))
LISTEN     0      128         :::11211                   :::*                   users:(("memcached",pid=20594,fd=27))

推荐资料

galaxy.ansible.com/ galaxy.ansible.com/not-found github.com/ ansible.com.cn/ 中文 github.com/ansible/ans… github.com/ansible/ans…