本章概要
常用自动化运维工具
ansible特性
Ansible主要组成部分
主机清单:被控制端的计算机列表,只有放到主机清单中的主机才能够被ansible管理.
经常要做的复杂任务,要编写playbook,在playbook中调用ansible的模块进行管理.
这些模块有核心模块,有定制模块,还有一些插件,提供日志、邮件等功能.
ansible通过连接插件连接到被控制的服务器,用户通过特殊工具使用ansible
Ansible安装方式
常用配置文件
主机清单inventory
ntp.magedu.com
[webservers]
www1.magedu.com:2222
www2.magedu.com
[dbservers]
db1.magedu.com
db2.magedu.com
db3.magedu.com
示例:
www[001:006].example.com
[001:006]是指001 002 003 004 005 006
db-[99:101]-node.example.com
[99:101]是指99 100 101
[websrvs]
192.168.32.128
192.168.32.130
[appsrvs]
192.168.32.13[0:1] 组合写法,是指192.168.32.130和192.168.32.131
absible配置文件
10 [defaults]
11
12 # some basic default values...
13
14 #inventory = /etc/ansible/hosts 主机清单
15 #library = /usr/share/my_modules/ 库文件存放目录
16 #module_utils = /usr/share/my_module_utils/ until工具存放目录
17 #remote_tmp = ~/.ansible/tmp 远程临时文件
18 #local_tmp = ~/.ansible/tmp 本地临时文件
#ansible执行过程:先把ansible执行的指令先生成python程序,放在本地目录中,
#然后把生成的python程序通过ssh协议复制到被管理的服务器~/.ansible/tmp目录下,
#再把这些程序执行,执行完毕以后再把复制过来的程序删除。
#如果在程序执行过程中,停止程序的执行,能在被控制服务器上找到复制过去的python脚本。
19 #plugin_filters_cfg = /etc/ansible/plugin_filters.yml 插件配置
20 #forks = 5 同时打开进程数,即并发数
21 #poll_interval = 15 时间间隔,经过多少秒查看对方的状态,根据对方的状态判断接下来怎么做
22 #sudo_user = root 默认sudo用户
23 #ask_sudo_pass = True 每次执行ansible命令是否询问ssh密码
24 #ask_pass = True
25 #transport = smart
26 #remote_port = 22 远程端口号
27 #module_lang = C
28 #module_set_locale = False
62 host_key_checking = False 第一次连接对方主机时,是否询问yes/no
#为了方便管理,推荐更改此项,即去掉行前注释符号,表示第一次连接对方主机无需询问yes/no
102 log_path = /var/log/ansible.log 日志文件,系统默认不启用
#推荐启用日志文件,即去掉注释符号
模拟实验命令示例规划:
主控端:192.168.32.129
需要两个网卡,连接互联网,使用epel源
被控端:192.168.32.128 192.168.32.130 192.168.32.131
主机清单配置:
vim /etc/ansible/hosts
[websrvs]
192.168.32.128
192.168.32.130
[appsrvs]
192.168.32.13[0:1] 组合写法,是指192.168.32.130和192.168.32.131
以下举例说明均以此规划进行,注意主机ip地址规划,防止不清楚举例的意思
注意:主机必须在主机清单中,ansible的命令才能有效
ansible
-m 后跟模块名
ping模块:探测被控制端是否可用
如:ansible -m ping 192.168.32.128
结果显示验证失败,要指定验证方式,基于用户名密码验证或者基于key验证
-k 指定用户名密码验证
默认为key验证方式,即不使用-k选项时,为key验证方式
ansible -m ping 192.168.32.128 -k
[root@centos7-1 ~]#ansible 192.168.32.128 -m ping -k
SSH password: 需要输入对方主机密码
192.168.32.128 | SUCCESS => {
"changed": false,
"ping": "pong"
}
管理多台主机:
ansible web -m ping -k
当管理多台主机时,第一次连接对方主机会有提示信息,需要输入yes/no,因此会出现错误。
解决方法:
vim /etc/ansible/ansible.cfg
62 host_key_checking = False 启用该项,即去掉行前注释符号
配置文件更改后立即生效。
另外,管理多台主机时,一次只能输入一个口令,因此管理多台主机时,口令不一致的情况下,不能使用用户名密码方式验证。
解决方法:使用基于key的验证方式
注意:基于key验证,可以手动添加key验证,也可以在装系统时使用脚本在kickstart文件中做好,也可以使用expect脚本。
ansible all -m ping 使用基于key验证测试
-u 指定远程执行用户
-b 使用sudo切换管理员身份
-K 提示输入sudo时的口令
这三个选项需要配合使用
ansible的Host-pattern
ansible命令执行过程
示例:
以wang用户执行ping存活检测
ansible all -m ping -u wang -k
以wang sudo至root执行ping存活检测
ansible all -m ping -u wang –b -k
以wang sudo至mage用户执行ping存活检测
ansible all -m ping -u wang –b -k --become-user mage
以wang sudo至root用户执行ls
ansible all -m command -u wang --become-user=root -a 'ls /root' -b –k -K
ansible常用模块
[root@centos7-1 ~]#ansible all -a 'echo centos123456|passwd --stdin test'
192.168.32.128 | SUCCESS | rc=0 >>
centos123456|passwd --stdin test
192.168.32.131 | SUCCESS | rc=0 >>
centos123456|passwd --stdin test
192.168.32.130 | SUCCESS | rc=0 >>
centos123456|passwd --stdin test
[root@centos7-1 ~]#ansible all -m shell -a 'echo centos123456|passwd --stdin test'
192.168.32.130 | SUCCESS | rc=0 >>
Changing password for user test.
passwd: all authentication tokens updated successfully.
192.168.32.128 | SUCCESS | rc=0 >>
Changing password for user test.
passwd: all authentication tokens updated successfully.
192.168.32.131 | SUCCESS | rc=0 >>
Changing password for user test.
passwd: all authentication tokens updated successfully.
由于shell模块功能更强,支持命令更多,为了方便管理,可以把shell模块更改为默认模块
vim /etc/ansible/ansible.cfg
105 #module_name = shell
ansible websrvs -m fetch -a 'src=/data/fstab2 dest=/data'
[root@centos7-1 data]#tree
.
├── 192.168.32.128
│ └── data
│ └── fstab2
└── 192.168.32.130
└── data
└── fstab2
该模块默认不能从目标主机拉取目录,如果想要拉取目录到本机,可以先对目录进行打包,然后再拉取该目录。
注意:ansible有专门的打包模块,用shell模式使用tar命令打包也可以
ansible websrvs -a 'tar cf /root/data.tar /data'
ansible websrvs -m fetch -a 'src=/root/data.tar dest=/data'
state 使用该命令指定状态
touch 创建新文件
link 创建软连接
hard 创建硬链接
absent 删除,如state=absent
path 指定文件路径,也可以用name,dest
ansible srv -m file -a “path=/root/a.sh owner=wang mode=755” 创建文件,所有者为wang,权限为755
ansible web -m file -a ‘src=/app/testfile dest=/app/testfile-link state=link’ 创建软连接
ansible web -m file -a ‘src=/app/testfile dest=/app/testfile-link state=hard’ 创建硬连接
ansible websrvs -m file -a ‘name=/data/dir1 state=directory’ 创建目录
ansible websrvs -m file -a ‘name=/data/dir1 state=absent’ 删除目录
Hostname:管理主机名
ansible node1 -m hostname -a “name=websrv”
Cron:计划任务
支持时间:minute,hour,day,month,weekday
ansible websrvs -m cron -a ‘minute=*/10 job=“ntpdata 172.20.0.1 &>/dev/null” name=synctime’ 创建计划任务
ansible websrvs -m cron -a ‘disabled=true job=“ntpdata 172.20.0.1 &>/dev/null” name=synctime’ 禁用计划任务
ansible websrvs -m cron -a ‘state=absent job=“ntpdata 172.20.0.1 &>/dev/null” name=synctime’ 删除计划任务
Yum:管理包
要确认被管理主机为linux redhat系列系统,因为只有redhat支持yum命令
ansible appsrvs -a “rpm -q httpd” 确认目标主机是否已经安装httpd软件包
ansible appsrvs -a “yum -y install httpd” 使用shell模块使用yum命令安装软件
ansible appsrvs -m yum -a “name=httpd state=absent” 使用yum模块删除软件包
ansible appsrvs -m yum -a "name=httpd " 使用yum模块安装软件包
ansible appsrvs -m yum -a "name=vsftpd,samba " 同时装多个软件包
ansible appsrvs -a "rpm -q httpd vsftpd samba " 查询是否安装软件包(查询多个包用空格隔开) 注意:查询软件包是否已经安装,多个软件包之间用空格隔开(注意不是逗号隔开);而在安装或者卸载多个软件包时,用逗号隔开
Service:管理服务
enabled=yes 安装软件并设置为开机自启动
ansible srv -m service -a ‘name=httpd state=stopped’
ansible srv -m service -a ‘name=httpd state=started’
ansible srv –m service –a ‘name=httpd state=reloaded’
ansible srv -m service -a ‘name=httpd state=restarted’
User:管理用户
ansible srv -m user -a ‘name=user1 comment=“test user” uid=2048 home=/app/user1 group=root’
ansible srv -m user -a ‘name=sysuser1 system=yes home=/app/sysuser1’
ansible srv -m user -a ‘name=user1 state=absent remove=yes’ 删除用户及家目录等数据
Group:管理组
ansible srv -m group -a “name=testgroup system=yes”
ansible srv -m group -a “name=testgroup state=absent”
ansible模块相关命令
[root@centos7-1 ~]#which ansible
/usr/bin/ansible
[root@centos7-1 ~]#ll /usr/bin/ansible
lrwxrwxrwx 1 root root 20 Sep 21 20:52 /usr/bin/ansible -> /usr/bin/ansible-2.7
vim hello.yml
#hello world yml file
- hosts: websrvs
remote_user: root
tasks:
- name: hello world
command: /usr/bin/wall hello world
root@all (2)[f:5]$ list
root@all (2)[f:5]$ cd appsrvs
root@appsrvs (2)[f:5]$ list
root@appsrvs (2)[f:5]$ yum name=httpd state=present
root@appsrvs (2)[f:5]$ service name=httpd state=started
playbook
YAML语法简介
示例:
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango
*Dictionary:字典,通常由多个key与value构成
示例:
---
# An employee record
name: Example Developer
job: Developer
skill: Elite
也可以将key:value放置于{}中进行表示,用,分隔多个key:value
示例:
---
# An employee record
{name: Example Developer, job: Developer, skill: Elite}
示例:
name: John Smith
age: 41
gender: Male
spouse:
name: Jane Smith
age: 37
gender: Female
children:
- name: Jimmy Smith
age: 17
gender: Male
- name: Jenny Smith
age 13
gender: Female
Playbook核心元素
ansible-playbook –t tagsname useradd.yml
Playbook基础组件
one.example.com
one.example.com:two.example.com
192.168.1.50
192.168.1.*
Websrvs:appsrvs 两个组的并集
Websrvs:&appsrvs 两个组的交集
webservers:!appsrvs 在websrvs组,但不在appsrvs组
示例:
- hosts: websrvs:dbsrvs
- hosts: websrvs
remote_user: root
tasks:
- name: test connection
ping:
remote_user: magedu
sudo: yes 默认sudo为root
sudo_user:wang sudo为wang
示例:
tasks:
- name: disable selinux
command: /sbin/setenforce 0
运行playbook
示例 :
ansible-playbook file.yml --check 只检测
ansible-playbook file.yml
ansible-playbook file.yml --limit websrvs
Playbook与shellscripts
#!/bin/bash
# 安装Apache
yum install --quiet -y httpd
# 复制配置文件
cp /tmp/httpd.conf /etc/httpd/conf/httpd.conf
cp/tmp/vhosts.conf /etc/httpd/conf.d/
# 启动Apache,并设置开机启动
service httpd start
chkconfig httpd on
---
- hosts: all
tasks:
- name: "安装Apache"
yum: name=httpd
- name: "复制配置文件"
copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/
- name: "复制配置文件"
copy: src=/tmp/vhosts.conf dest=/etc/httpd/conf.cd/
- name: "启动Apache,并设置开机启动"
service: name=httpd state=started enabled=yes
示例1:
vim sysuser.yml
---
- hosts: all
remote_user: root
tasks:
- name: create mysql user
user: name=mysql system=yes uid=36
- name: create a group
group: name=httpd system=yes
示例2:
vim httpd.yml
- hosts: websrvs
remote_user: root
tasks:
- name: Install httpd
yum: name=httpd state=present
- name: Install configure file
copy: src=files/httpd.conf dest=/etc/httpd/conf/
- name: start service
service: name=httpd state=started enabled=yes
实验:用playbook实现自定义安装http服务
自定义http服务
httpd.yml
先创建组,在创建用户,安装软件包,最后启动服务
先确定目标主机没有安装httpd软件包
根据自己的情况生成配置文件,把该配置文件作为模板,修改过之后,把配置文件复制到需要启用http服务的主机上
cp /etc/httpd/conf/httpd.conf /data
vim /data/httpd.conf
Listen 8080 把监听端口更改为8080(默认为80)
注意:由于centos6和centos7系统中http配置文件不兼容,因此此时做实验用两台centos7系统主机(在appsrvs组)做实验,或者把不同版本的系统做成不同的文件,此时暂不考虑
vim httpd2.yml
1 ---
2 # config httpd service
3 - hosts: appsrvs
4 remote_user: root
5
6 tasks:
7 - name: create group
8 group: name=apache gid=80 system=yes
9 - name: create user
10 user: name=apache uid=80 system=yes group=apache shell=/sbin/nologin home=/dat a/www comment="web user"
11 - name: install packaage
12 yum: name=httpd
13 - name: copy config file
14 copy: src=/data/httpd.conf dest=/etc/httpd/conf/httpd.conf
15 - name: start service
16 service: name=httpd state=started enabled=yes
注意:如果服务刚安装没有启动过,配置文件复制过去以后,started启动服务,配置文件立即生效,监听端口也会发生变化。
如果该服务已经启动过,或第二次通过httpd2.yml文件复制配置文件时,配置文件复制过去以后,需要重启该服务配置文件才能生效。
由于文件中服务模块service为started,服务并不会重启,配置文件虽然复制过去,但并不会生效,因此监听端口不会发生变化
解决方法:把配置文件中service模块,state更改为restarted。
即:- name: start service
service: name=httpd state=restarted enabled=yes
但这种写法不适用于第一次启动该服务的状态,因为服务软件包刚安装还没有启动,restarted并不生效
那么,此时就用到了触发器handlers的用法,下面介绍用法。
handlers和notify结合使用触发条件
playbook中handlers使用
- hosts: websrvs
remote_user: root
tasks:
- name: Install httpd
yum: name=httpd state=present
- name: Install configure file
copy: src=files/httpd.conf dest=/etc/httpd/conf/
notify: restart httpd
- name: ensure apache is running
service: name=httpd state=started enabled=yes
handlers:
- name: restart httpd
service: name=httpd status=restarted
- hosts: websrvs
remote_user: root
tasks:
- name: add group nginx
tags: user
user: name=nginx state=present
- name: add user nginx
user: name=nginx state=present group=nginx
- name: Install Nginx
yum: name=nginx state=present
- name: config
copy: src=/root/config.txt dest=/etc/nginx/nginx.conf
notify:
- Restart Nginx
- Check Nginx Process
handlers:
- name: Restart Nginx
service: name=nginx state=restarted enabled=yes
- name: Check Nginx process
shell: killall -0 nginx > /tmp/nginx.log
vim httpd2.yml
1 ---
2 # config httpd service
3 - hosts: appsrvs
4 remote_user: root
5
6 tasks:
7 - name: create group
8 group: name=apache gid=80 system=yes
9 - name: create user
10 user: name=apache uid=80 system=yes group=apache shell=/sbin/nologin home=/data/www comment="web user"
11 - name: install packaage
12 yum: name=httpd
13 - name: copy config file
14 copy: src=/data/httpd.conf dest=/etc/httpd/conf/httpd.conf
15 - name: cpoy other config file
16 copy: src=/data/httpd2.conf dest=/etc/httpd/conf/httpd.conf
17 notify: restart service
18
19 - name: start service
20 service: name=httpd state=started enabled=yes
21
22 handlers:
23 - name: restart service
24 service: name=httpd state=restarted
playbook中tags使用
vim httpd2.yml
1 ---
2 # config httpd service
3 - hosts: appsrvs
4 remote_user: root
5
6 tasks:
7 - name: create group
8 group: name=apache gid=80 system=yes
9 - name: create user
10 user: name=apache uid=80 system=yes group=apache shell=/sbin/nologin home=/dat a/www comment="web user"
11 - name: install packaage
12 yum: name=httpd
13 - name: copy config file
14 copy: src=/data/httpd.conf dest=/etc/httpd/conf/httpd.conf
15 notify: restart service
16 tags: conf 对复制文件加标签
17
18 - name: start service
19 service: name=httpd state=started enabled=yes
20
21 handlers:
22 - name: restart service
23 service: name=httpd state=restarted
ansible-playbook -t conf httpd2.yml
执行命令-t conf时,只对带有标签的项进行更改,即复制配置文件,其他项不做更改
vim httpd3.yml
1 ---
2 # config httpd service
3 - hosts: appsrvs
4 remote_user: root
5
6 tasks:
7 - name: create group
8 group: name=apache gid=80 system=yes
9 - name: create user
10 user: name=apache uid=80 system=yes group=apache shell=/sbin/nologin home=/dat a/www comment="web user"
11 - name: install packaage
12 yum: name=httpd
13 - name: copy config file
14 copy: src=/data/httpd.conf dest=/etc/httpd/conf/httpd.conf
15 notify: restart service
16 tags: conf
17
18 - name: copy other config file
19 copy: src=/data/httpd2.conf dest=/etc/httpd/conf/httpd.conf
20 notify: restart service
21 tags: conf2
22
23 - name: start service
24 service: name=httpd state=started enabled=yes
25
26 handlers:
27 - name: restart service
28 service: name=httpd state=restarted
ansible-playbook -t conf,conf2 httpd2.yml
playbook中变量使用
示例1:使用setup变量
使用setup模块可以查询主机的各种信息,这些信息可以作为变量使用,也即是系统内置变量。
用法:
[root@centos7-1 data]#ansible 192.168.32.128 -m setup|grep fqdn
"ansible_fqdn": "centos6.magedu.com",
以下为系统内置变量,可根据此变量查询被控端主机信息或对配置文件做相应的修改
版本号: “ansible_distribution_major_version”: “7”
主机名: “ansible_nodename”: “centos6.magedu.com”
cpu数量:“ansible_processor_vcpus”: 2
内存大小:“ansible_memtotal_mb”: 1497
查询版本号:
ansible all -m setup -a "filter=ansible_distribution_major_version"
或ansible all -m setup -a "filter=ansible_distribution_major_*" 模糊匹配
查询主机名
ansible all -m setup -a "filter=ansible_fqdn"
或ansible all -m setup -a "filter=*_fqdn" 模糊匹配
示例1:使用主机名变量创建文件
vim var.yml
- hosts: websrvs
remote_user: root
tasks:
- name: create log file
file: name=/var/log/ {{ ansible_fqdn }} state=touch
ansible-playbook var.yml
示例2:使用自定义变量安装软件
vim var.yml
- hosts: websrvs
remote_user: root
tasks:
- name: install package
yum: name={{ pkname }} state=present
ansible-playbook –e pkname=httpd var.yml
示例3:使用自定义变量创建用户和组
vim var.yml
- hosts: websrvs
remote_user: root
vars:
- username: user1
- groupname: group1
tasks:
- name: create group
group: name={{ groupname }} state=present
- name: create user
user: name={{ username }} state=present
ansible-playbook var.yml
ansible-playbook -e "username=user2 groupname=group2” var2.yml
变量
示例:
[websrvs]
www1.magedu.com http_port=80 maxRequestsPerChild=808
www2.magedu.com http_port=8080 maxRequestsPerChild=909
示例1:
[websrvs]
www1.magedu.com
www2.magedu.com
[websrvs:vars]
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com
示例2:
普通变量
[websrvs]
192.168.32.128 http_port=86
192.168.32.130 http_port=87
公共(组)变量
[websvrs:vars]
http_port=808
mark=“_”
[websrvs]
192.168.32.128 http_port=8080 hname=www1
192.168.32.130 http_port=80 hname=www2
ansible websvrs –m hostname –a ‘name={{ hname }}{{ mark }}{{ http_port }}’
命令行指定变量:
ansible websvrs –e http_port=8000 –m hostname –a
‘name={{ hname }}{{ mark }}{{ http_port }}’
使用变量文件
vim vars.yml
---
- hosts: websrvs
remote_user: root
vars:
- http_port: 8080
- pname: httpd
tasks:
- name: create log file
file: name=/data/httpd{{mark}}{{ http_port }}.log state=touch
tags: conf
- name: install package
yum: name={{pname}}
变量优先级:
-e自定义变量 > playbook中定义的变量 > 独立yml文件定义的变量 > hosts主机清单中的变量 > setup变量
vim vars2.yml
http_port: 9527
pname: memcached
vim var.yml
---
- hosts: websrvs
remote_user: root
vars_files:
- vars2.yml 调用独立的定义变量文件vars.yml
tasks:
- name: create log file
file: name=/data/httpd{{mark}}{{ http_port }}.log state=touch
tags: conf
- name: install package
yum: name={{pname}}
模板templates
templates简介
./
├── temnginx.yml
└── templates
└── nginx.conf.j2
示例:利用templates 同步nginx配置文件
在ansible管理端主机上安装Nginx软件
在ansible管理主机上生成配置文件,参考该配置文件在不同主机上生成对应的真正的配置文件
如:nginx配置文件中中work process进程数与cpu数量有关,更改配置文件中的work process进程数为主机cpu数量*2
cp /etc/nginx/nginx.conf /data/ 把nginx配置文件复制到/data目录下
vim nginx.conf
worker_processes auto; auto默认work process进程数与cpu个数一致
worker_processes {{ansible_processor_vcpus*2}} 指定work process进程数为cpu数量*2
(1)准备templates/nginx.conf.j2文件
vim test_tepm1.yml
- hosts: appsrvs
remote_user: root
tasks:
- name: install nginx
yum: name=nginx
- name: template
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf 调用模板文件
- name: start service
service: name=nginx state=started
(2)在主机清单中定义变量,在templates/nginx.conf.j2中调用该变量自动更改nginx监听端口号
vim /etc/ansible/hosts
51 [appsrvs]
52 192.168.32.130 http_port=81
53 192.168.32.131 http_port=82
vim templates/nginx.conf.j2
server {
listen {{http_port}} default_server; 更改监听端口为变量,其他不变
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
(3)调用变量,并配置文件推送到被控端主机
vim test_temp1.yml
- hosts: appsrvs
remote_user: root
tasks:
- name: install nginx
yum: name=nginx
- name: template
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: restart service 一旦复制文件就重启服务
- name: start service
service: name=nginx state=started
handlers: 触发器
- name: restart service
service: name=nginx state=restarted service
ansible-playbook test_temp1.yml
playbook中template算术运算
示例:
vim nginx.conf.j2
worker_processes {{ ansible_processor_vcpus**2 }};
worker_processes {{ ansible_processor_vcpus+2 }};
when
示例1:
tasks:
- name: "shutdown RedHat flavored systems"
command: /sbin/shutdown -h now
when: ansible_os_family == "RedHat"
示例2:
- hosts: websrvs
remote_user: root
tasks:
- name: add group nginx
tags: user
user: name=nginx state=present
- name: add user nginx
user: name=nginx state=present group=nginx
- name: Install Nginx
yum: name=nginx state=present
- name: restart Nginx
service: name=nginx state=restarted
when: ansible_distribution_major_version == "6"
示例3:
tasks:
- name: install conf file to centos7
template: src=nginx.conf.c7.j2
when: ansible_distribution_major_version == "7"
- name: install conf file to centos6
template: src=nginx.conf.c6.j2
when: ansible_distribution_major_version == "6"
实验:根据不同的版本实现不同的模板
以http服务为例:centos6和centos7的http配置文件不兼容,因此需要实现判断版本号以后,在复制配置文件到目标主机
注意:使用Nginx和http服务做实验时,要注意这两个服务端口号都是80,会产生冲突,因此使用http服务做实验时要卸载Nginx服务
cd /data
cp /etc/httpd/conf/httpd.conf /data/templates/httpd7.conf.j2
把本机centos7的http服务的配置文件复制到ansible控制端主机上作为模板文件
scp /etc/httpd/conf/httpd.conf 192.168.32.129:/data/templates/httpd6.conf.j2
把centos6的http服务的配置文件远程复制到ansible控制端主机上作为模板文件
vim httpd7.conf.j2 centos7系统http配置文件
42 Listen {{http_port}} 把默认80端口更改为http_port变量
vim httpd6.conf.j2 centos6系统http配置文件
42 Listen {{http_port}} 把默认80端口更改为http_port变量
vim /etc/ansible/hosts
45 [websrvs]
46 192.168.32.128 http_port=86 该主机为centos6版本
47 192.168.32.130 http_port=87 该主机为centos7版本
vim test_temp2.yml
1 - hosts: websrvs
2 remote_user: root
3
4 tasks:
5 - name: install nginx
6 yum: name=httpd
7 - name: template 6
8 template: src=httpd6.conf.j2 dest=/etc/httpd/conf/httpd.conf
9 notify: restart service
10 when: ansible_distribution_major_version == "6"
11
12 - name: template 7
13 template: src=httpd7.conf.j2 dest=/etc/httpd/conf/httpd.conf
14 notify: restart service
15 when: ansible_distribution_major_version == "7"
16
17 - name: start service
18 service: name=httpd state=started
19
20 handlers:
21 - name: restart service
22 service: name=httpd state=restarted
playbook调用主机清单中websrvs组中自定义变量http_port,在配置文件中生成监听86和87端口并复制到目标主机对应的配置文件目录下
迭代:with_item
示例1:
- name: add several users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2
上面语句的功能等同于下面的语句:
- name: add user testuser1
user: name=testuser1 state=present groups=wheel
- name: add user testuser2
user: name=testuser2 state=present groups=wheel
示例2:迭代:将多个文件进行copy到被控端
---
- hosts: websrv
remote_user: root
tasks:
- name: Create rsyncd config
copy: src={{ item }} dest=/etc/{{ item }}
with_items:
- rsyncd.secrets
- rsyncd.conf
示例3:迭代
- hosts: websrvs
remote_user: root
tasks:
- name: copy file
copy: src={{ item }} dest=/tmp/{{ item }}
with_items:
- file1
- file2
- file3
- name: yum install httpd
yum: name={{ item }} state=present
with_items:
- apr
- apr-util
- httpd
示例4:迭代
- hosts:websrvs
remote_user: root
tasks:
- name: install some packages
yum: name={{ item }} state=present
with_items:
- nginx
- memcached
- php-fpm
示例5:迭代嵌套子变量
- 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' }
playbook中template模板for语句、if语句
语法格式:
{% for vhost in nginx_vhosts %}
server {
listen {{ vhost.listen | default('80 default_server') }};
{% if vhost.server_name is defined %}
server_name {{ vhost.server_name }};
{% endif %}
{% if vhost.root is defined %}
root {{ vhost.root }};
{% endif %}
示例1:
yml文件:
vim temnginx.yml
---
- hosts: appsrvs
remote_user: root
vars:
nginx_vhosts:
- listen: 8080
模板template目录下j2文件:
vim templates/nginx.conf.j2
{% for vhost in nginx_vhosts %}
server {
listen {{ vhost.listen }}
}
{% endfor %}
生成的结果:
server {
listen 8080
}
示例2:
yml文件:
vim temnginx.yml
---
- hosts: appsrvs
remote_user: root
vars:
nginx_vhosts:
- web1
- web2
- web3
tasks:
- name: template config
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
模板template目录下j2文件:
vim templates/nginx.conf.j2
{% for vhost in nginx_vhosts %}
server {
listen {{ vhost }}
}
{% endfor %}
生成的结果:
server {
listen web1
}
server {
listen web2
}
server {
listen web3
}
示例3:
yml文件:
vim temnginx.yml
- hosts: appsrvs
remote_user: root
vars:
nginx_vhosts:
- web1:
listen: 8080
server_name: "web1.magedu.com"
root: "/var/www/nginx/web1/"
- web2:
listen: 8080
server_name: "web2.magedu.com"
root: "/var/www/nginx/web2/"
- web3:
listen: 8080
server_name: "web3.magedu.com"
root: "/var/www/nginx/web3/“
tasks:
- name: template config
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
模板template目录下j2文件:
vim templates/nginx.conf.j2
{% for vhost in nginx_vhosts %}
server {
listen {{ vhost.listen }}
server_name {{ vhost.server_name }}
root {{ vhost.root }}
}
{% endfor %}
生成结果:
server {
listen 8080
server_name web1.magedu.com
root /var/www/nginx/web1/
}
server {
listen 8080
server_name web2.magedu.com
root /var/www/nginx/web2/
}
server {
listen 8080
server_name web3.magedu.com
root /var/www/nginx/web3/
}
示例4:
yml文件:
vim temnginx.yml
- hosts: appsrvs
remote_user: root
vars:
nginx_vhosts:
- web1:
listen: 8080
root: "/var/www/nginx/web1/"
- web2:
listen: 8080
server_name: "web2.magedu.com"
root: "/var/www/nginx/web2/"
- web3:
listen: 8080
server_name: "web3.magedu.com"
root: "/var/www/nginx/web3/"
tasks:
- name: template config to
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
模板template目录下j2文件:
vim templates/nginx.conf.j2
{% for vhost in nginx_vhosts %}
server {
listen {{ vhost.listen }}
{% if vhost.server_name is defined %}
server_name {{ vhost.server_name }}
{% endif %}
root {{ vhost.root }}
}
{% endfor %}
生成的结果:
server {
listen 8080
root /var/www/nginx/web1/
}
server {
listen 8080
server_name web2.magedu.com
root /var/www/nginx/web2/
}
server {
listen 8080
server_name web3.magedu.com
root /var/www/nginx/web3/
}
roles
roles目录结构
roles各目录作用
创建role
针对大型项目使用roles进行编排
roles目录结构:
playbook.yml
roles/
project/
tasks/
files/
vars/
templates/
handlers/
default/ # 不经常用
meta/ # 不经常用
示例1:
vim nginx_role.yml 该文件调用nginx角色
- hosts: appsrvs
remote_user: root
roles:
- role: nginx
tree roles
roles/
└── nginx
├── files
│ └── main.yml
├── tasks
│ ├── groupadd.yml
│ ├── install.yml
│ ├── main.yml
│ ├── restart.yml
│ └── useradd.yml
└── vars
└── main.yml
playbook调用角色
- hosts: websrvs
remote_user: root
roles:
- mysql
- memcached
- nginx
- hosts:
remote_user:websrvs
roles:
- mysql
- { role: nginx, username: nginx } role用于指定角色名称,后续的k/v用于传递变量给角色
roles:
- { role: nginx, username: nginx, when: ansible_distribution_major_version == ‘7’ }
变量的最后一种方式:在role中定义变量
[root@centos7-1 data]#cat httpd_role.yml
- hosts: appsrvs
remote_user: root
roles:
- role: apache
vim /templates/nginx.conf.j2
5 user {{username}}; 模板文件中的用户名nginx用变量username代替
vim /data/nginx_role.yml
1 - hosts: appsrvs
2 remote_user: root
3
4 roles:
5 - {role: nginx,username: daemon} 自定义用户名变量
ansible-playbook nginx_role.yml
命令执行结果:目标主机中的nginx程序已daemon用户执行
完整的roles架构
vim nginx-role.yml 顶层任务调用yml文件
---
- hosts: appsrvs
remote_user: root
roles:
- role: nginx
- role: httpd 可执行多个role
vim roles/nginx/tasks/main.yml
---
- include: groupadd.yml
- include: useradd.yml
- include: install.yml
- include: restart.yml
- include: filecp.yml
vim roles/nginx/tasks/groupadd.yml
---
- name: add group nginx
user: name=nginx state=present
vim roles/nginx/tasks/filecp.yml
---
- name: file copy
copy: src=tom.conf dest=/tmp/tom.conf
以下文件格式类似:
useradd.yml,install.yml,restart.yml
ls roles/nginx/files/
tom.conf
roles playbook tags使用
vim nginx_role.yml
- hosts: appsrvs
remote_user: root
roles:
- {role: nginx,username: daemon,tags: ['nginx','web']}
- {role: apache,tags: ['apache','web']}
执行时,指定标签执行
ansible-playbook -t apache nginx_role.yml -t或–tags 选项指定运行标签为apache的服务
实验:根据内存大小灵活配置缓存大小
ansible_memtotal_mb 内存总大小
安装memcached软件包
yum -y installmemcached
cp /etc/sysconfig/memcached memcache/templates/memcached.j2
vim memcache/templates/memcached.j2
1 PORT="11211"
2 USER="memcached"
3 MAXCONN="1024"
4 CACHESIZE="{{ansible_memtotal_mb//4}}" //是指除以4,所得结果只取整数
5 OPTIONS=""
[root@centos7-1 roles]#tree roles/memcache/
memcache/
├── tasks
│ ├── main.yml
│ ├── package.yml
│ ├── service.yml
│ └── templconf.yml
└── templates
└── memcached.j2
2 directories, 5 files
[root@centos7-1 data]#vim memcached_role.yml
1 - hosts: appsrvs
2 remote_user: root
3
4 roles:
5 - role: memcached
ansible-playbook memcached_role.yml
推荐资料查询网址