1.Ansible介绍
- 不需要安装客户端,通过sshd去通信
- 基于模块工作,模块可以由任何语言开发 不仅支持命令行使用模块,也支持编写yaml格式的playbook,易于编写和阅读
- 安装十分简单,centos上可直接yum安装
- 有提供UI(浏览器图形化)www.ansible.com/tower,收费的 官方文档 http://docs.ansible.com/ansible/latest/index.html ansible已经被redhat公司收购,它在github上是一个非常受欢迎的开源软件,github地址https://github.com/ansible/ansible
ansible基于python开发,集合了众多运维工具的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是基于模块工作的,本身没有批量部署的能力。
真正具有批量部署的是ansible运行的模块,ansible只是一个框架
(1) 连接插件connection plugins: 负责和被监控端实现通信;
(2) host inventory: 指定操作的主机,是一个配置文件里面定义监控的主机
(3) 各种模块核心模块、command模块、自定义模块;
(4) 借助于插件完成记录日志邮件等功能;
(5) playbook: 剧本执行多个任务时,非必须可以让节点一次性运行多个任务。
Ansible 特点:
- >> 部署简单,只需在主控端部署 Ansible 环境,被控端无需做任何操作。
- >> 默认使用 SSH(Secure Shell)协议对设备进行管理。
- >> 主从集中化管理。
- >> 配置简单、功能强大、扩展性强。
- >> 支持 API 及自定义模块,可通过 Python 轻松扩展。
- >> 通过 Playbooks 来定制强大的配置、状态管理。
- >> 对云计算平台、大数据都有很好的支持。
- >> 提供一个功能强大、操作性强的 Web 管理界面和 REST API 接口 ---- AWX 平台。
Ansible 与 SaltStack
- >> 最大的区别是 Ansible 无需在被监控主机部署任何客户端代理,默认通过 SSH 通道进行远程命令执行或下发配置。
- >> 相同点是都具备功能强大、灵活的系统管理、状态配置,都使用 YAML 格式来描述配置,两者都提供丰富的模板及 API,对云计算平台、大数据都有很好的支持。
1.1 ansible架构图
2.Ansible安装
1.在服务器端安装ansible
[root@knightlai01 ~]# yum install ansible
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirror.vpshosting.com.hk
* epel: mirrors.aliyun.com
* extras: mirror.vpshosting.com.hk
* updates: mirror.vpshosting.com.hk
Resolving Dependencies
--> Running transaction check
---> Package ansible.noarch 0:2.7.2-1.el7 will be installed
--> Processing Dependency: sshpass for package: ansible-2.7.2-1.el7.noarch
--> Processing Dependency: python2-jmespath for package: ansible-2.7.2-1.el7.noarch
.....................................................................................
//编辑hosts文件增加以下二行
[root@knightlai01 ~]# vi /etc/ansible/hosts
[testhost]
127.0.0.1
192.168.139.138
说明: testhost为主机组名字,自定义的。 下面两个ip为组内的机器ip。
2.Ansible远程执行命令
ansible默认使用 SSH(Secure Shell)协议对设备进行管理,.所以首先我们要配置ssh的密钥认证,才能远程操作执行命令等。
基于commadn模块
[root@knightlai01 ~]# ansible 192.168.139.140 -m command -a 'w'
192.168.139.140 | CHANGED | rc=0 >>
20:46:54 up 38 min, 2 users, load average: 0.03, 0.34, 0.26
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 knight-pc.airdre 20:08 14.00s 0.05s 0.05s -bash
root pts/1 192.168.139.135 20:46 0.00s 0.05s 0.00s w
//这样就可以批量执行命令了。这里的testhost 为主机组名,-m后边是模块名字,-a后面是命令。当然我们也可以直接写一个ip,针对某一台机器来执行命令。
基于shell
[root@knightlai01 ~]# ansible 192.168.139.140 -m shell -a 'w'
192.168.139.140 | CHANGED | rc=0 >>
20:49:02 up 40 min, 2 users, load average: 0.00, 0.22, 0.22
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 knight-pc.airdre 20:08 2:22 0.05s 0.05s -bash
root pts/1 192.168.139.135 20:49 0.00s 0.04s 0.00s w
3.Ansible拷贝文件或者目录
[root@knightlai01 ~]# ansible 192.168.139.140 -m copy -a "src=/etc/ansible dest=/tmp/ansibletest owner=root group=root mode=0755"
192.168.139.140 | CHANGED => {
"changed": true,
"dest": "/tmp/ansibletest/",
"src": "/etc/ansible"
}
注意:源目录会放到目标目录下面去,如果目标指定的目录不存在,它会自动创建。如果拷贝的是文件,dest指定的名字和源如果不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果desc是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下面。
在客户端机器上面查看文件拷贝是否成功
[root@knightlai02 ~]# ls /tmp/ansibletest/
ansible
[root@knightlai02 ~]# ls /tmp/ansibletest/ansible/
ansible.cfg hosts roles
[root@knightlai01 ~]# ansible 192.168.139.140 -m copy -a "src=/etc/passwd dest=/tmp/123"
192.168.139.140 | SUCCESS => {
"changed": false,
"checksum": "923abdac4c78b2287e5e2bcaa32878765edd12cc",
"dest": "/tmp/123",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"path": "/tmp/123",
"size": 884,
"state": "file",
"uid": 0
}
注意:这里的/tmp/123和源机器上的/etc/passwd是一致的,但如果目标机器上已经有/tmp/123目录,则会再/tmp/123目录下面建立passwd文件
[root@knightlai02 ~]# ls -lt /tmp/123
-rw-r--r-- 1 root root 884 Nov 27 20:56 /tmp/123
4.Ansible远程执行脚本
首先在服务端新建一个脚本:
[root@knightlai01 ~]# vim /tmp/1.sh
[root@knightlai01 ~]# chmod u+x /tmp/1.sh
[root@knightlai01 ~]# sh /tmp/1.sh
20181127
将脚本分发到客户端
[root@knightlai01 ~]# ansible 192.168.139.140 -m copy -a "src=/tmp/1.sh dest=/tmp/1.sh mode=0755"
192.168.139.140 | CHANGED => {
"changed": true,
"checksum": "0f703dc9b05c5d6242875ae5a90e58a99223897f",
"dest": "/tmp/1.sh",
"gid": 0,
"group": "root",
"md5sum": "69cc0c8eb04122067c515caa76019078",
"mode": "0755",
"owner": "root",
"size": 39,
"src": "/root/.ansible/tmp/ansible-tmp-1543328289.1-25342647888339/source",
"state": "file",
"uid": 0
}
远程执行脚本:shell模块,还支持远程执行命令并且带管道
ansible testhost -m shell -a "cat /etc/passwd|wc -l "
[root@knightlai01 ~]# ansible 192.168.139.140 -m shell -a "/tmp/1.sh"
192.168.139.140 | CHANGED | rc=0 >>
20181127
[root@knightlai01 ~]# ansible 192.168.139.140 -m shell -a "cat /etc/passwd|wc -l "
192.168.139.140 | CHANGED | rc=0 >>
20
5.Ansible管理任务计划
远程执行任务计划:
[root@knightlai01 ~]# ansible 192.168.139.140 -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' weekday=6"
192.168.139.140 | CHANGED => {
"changed": true,
"envs": [],
"jobs": [
"test cron"
]
}
//其他的时间表示:分钟 minute 小时 hour 日期 day 月份 month
//若要删除该cron 只需要加一个字段 state=absent
ansible testhost -m cron -a "name='test cron' state=absent"
在客户端上查看任务计划
[root@knightlai02 ~]# crontab -l
#Ansible: test cron
* * * * 6 /bin/touch /tmp/1212.txt
6.Ansible安装rpm包/管理服务
[root@knightlai01 ~]# ansible 192.168.139.140 -m yum -a "name=httpd"
192.168.139.140 | CHANGED => {
"ansible_facts": {
"pkg_mgr": "yum"
},
"changed": true,
"msg": "",
"rc": 0,
"results": [
............................................................................
在name后面还可以加上state=installed/removed
ansible testhost -m service -a "name=httpd state=started enabled=yes"
这里的name是centos系统里的服务名,可以通过chkconfig --list查到。
远程开启httpd服务:ansible testhost -m service -a "name=httpd state=started enabled=yes"
root@knightlai01 ~]# ansible 192.168.139.140 -m service -a "name=httpd state=started enabled=yes"
192.168.139.140 | CHANGED => {
"changed": true,
"enabled": true,
"name": "httpd",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "tmp.mount basic.target systemd-journald.socket system.slice nss-lookup.target -.mount remote-fs.target network.target",
..................................................................................
在客户端上查看httpd服务,已经开启了
[root@knightlai02 ~]# ps aux |grep httpd
root 2543 3.1 0.5 230376 5168 ? Ss 22:35 0:00 /usr/sbin/httpd -DFOREGROUND
apache 2544 0.0 0.3 230376 3016 ? S 22:35 0:00 /usr/sbin/httpd -DFOREGROUND
apache 2545 0.0 0.3 230376 3016 ? S 22:35 0:00 /usr/sbin/httpd -DFOREGROUND
apache 2547 0.0 0.3 230376 3016 ? S 22:35 0:00 /usr/sbin/httpd -DFOREGROUND
apache 2548 0.0 0.3 230376 3016 ? S 22:35 0:00 /usr/sbin/httpd -DFOREGROUND
apache 2549 0.0 0.3 230376 3016 ? S 22:35 0:00 /usr/sbin/httpd -DFOREGROUND
root 2558 0.0 0.0 112704 960 pts/0 R+ 22:35 0:00 grep --color=auto httpd
Ansible文档的使用
- ansible-doc -l 列出所有的模块
- ansible-doc cron 查看指定模块的文档
7.Ansible playbook的使用
//把模块写入到配置文件里面
[root@knightlai01 ~]# vim /etc/ansible/test.yml
---
- hosts: 192.168.139.140
remote_user: root
tasks:
- name: test_playbook
shell: touch /tmp/123.txt
说明: 第一行需要有三个杠,hosts参数指定了对哪些主机进行参作,如果是多台机器可以用逗号作为分隔,也可以使用主机组,在/etc/ansible/hosts里定义; user参数指定了使用什么用户登录远程主机操作; tasks指定了一个任务,其下面的name参数同样是对任务的描述,在执行过程中会打印出来,shell是ansible模块名字.
7.1 ansible playbook执行过程
[root@knightlai01 ~]# ansible-playbook /etc/ansible/test.yml
PLAY [192.168.139.140] *************************************************************************
TASK [Gathering Facts] *************************************************************************
ok: [192.168.139.140]
TASK [test_playbook] ***************************************************************************
[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.139.140]
PLAY RECAP *************************************************************************************
192.168.139.140 : ok=2 changed=1 unreachable=0 failed=0
在客户端上验证是否成功
[root@knightlai02 ~]# ls -lt /tmp/123.txt
-rw-r--r-- 1 root root 0 Nov 27 22:44 /tmp/123.txt
[root@knightlai02 ~]# date
Tue Nov 27 22:45:27 CST 2018
7.2 Ansible playbook第两个例子
创建一个新用户
[root@knightlai01 ~]# vim /etc/ansible/create_user.yml
---
- name: create_user
hosts: 192.168.139.140
user: root
gather_facts: false
vars:
- user: "test"
tasks:
- name: create user
user: name="{{ user }}"
说明:name参数对该playbook实现的功能做一个概述,后面执行过程中,会打印 name变量的值 ,可以省略;gather_facts参数指定了在以下任务部分执行前,是否先执行setup模块获取主机相关信息,这在后面的task会使用到setup获取的信息时用到;vars参数,指定了变量,这里指字一个user变量,其值为test ,需要注意的是,变量值一定要用引号引住;user提定了调用user模块,name是user模块里的一个参数,而增加的用户名字调用了上面user变量的值。
执行过程:
[root@knightlai01 ~]# ansible-playbook /etc/ansible/create_user.yml
PLAY [create_user] *****************************************************************************
TASK [create user] *****************************************************************************
changed: [192.168.139.140]
PLAY RECAP *************************************************************************************
192.168.139.140 : ok=1 changed=1 unreachable=0 failed=0
在客户端上查看执行结果:这里test用户创建成功。
[root@knightlai02 ~]# tail /etc/passwd
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
mysql:x:1000:1000::/home/mysql:/bin/bash
php-fpm:x:1001:1001::/home/php-fpm:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
test:x:1002:1002::/home/test:/bin/bash
8.Ansible playbook中的循环
例:批量修改文件的权限
[root@knightlai01 ~]# vi /etc/ansible/while.yml
---
- hosts: 192.168.139.140
user: root
tasks:
- name: change mode for files
file: path=/tmp/{{ item }} mode=600
with_items:
- 1.txt
- 2.txt
- 3.txt
执行过程:
[root@knightlai01 ~]# ansible-playbook /etc/ansible/while.yml
PLAY [192.168.139.140] *************************************************************************
TASK [Gathering Facts] *************************************************************************
ok: [192.168.139.140]
TASK [change mode for files] *******************************************************************
changed: [192.168.139.140] => (item=1.txt)
changed: [192.168.139.140] => (item=2.txt)
changed: [192.168.139.140] => (item=3.txt)
PLAY RECAP *************************************************************************************
192.168.139.140 : ok=2 changed=1 unreachable=0 failed=0
在客户端上查看执行结果:发现我们修改的1.txt 2.txt 3.txt 全部权限变成600
[root@knightlai02 ~]# ls -ll /tmp
total 8
-rw-r--r-- 1 root root 884 Nov 27 20:56 123
-rw-r--r-- 1 root root 0 Nov 27 22:44 123.txt
-rwxr-xr-x 1 root root 39 Nov 27 22:23 1.sh
drw------- 2 root root 6 Nov 27 22:54 1.txt
drw------- 2 root root 6 Nov 27 22:54 2.txt
drw------- 2 root root 6 Nov 27 22:54 3.txt
drwxr-xr-x 3 root root 21 Nov 27 20:54 ansibletest
9.Ansible playbook中的条件判断
例:判断如果我们远程ip地址192.168.139.140则在tmp目录下面创建when.txt文件
[root@knightlai01 ~]# vi /etc/ansible/when.yml
---
- hosts: 192.168.139.140
user: root
gather_facts: True
tasks:
- name: use when
shell: touch /tmp/when.txt
when: ansible_ens33.ipv4.address == "192.168.139.140“
说明:ansible aming-02 -m setup 可以查看到所有的facter信息
10.Ansible playbook中的handlers
执行task之后,服务器发生变化之后要执行的一些操作,比如我们修改了配置文件后,需要重启一下服务:
例:只有当copy模块执行成功才会执行下面这一条命令将“111111”写入到aaa.txt中
[root@knightlai01 ~]# vi /etc/ansible/handlers.yml
---
- name: handlers test
hosts: 192.168.139.140
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相关的操作。也就是说如果1.txt和2.txt内容是一样的,并不会去执行handlers里面的shell相关命令。 这种比较适合配置文件发生更改后,重启服务的操作。
执行过程:
[root@knightlai01 ~]# ansible-playbook /etc/ansible/handlers.yml
PLAY [handlers test] ***************************************************************************
TASK [Gathering Facts] *************************************************************************
ok: [192.168.139.140]
TASK [copy file] *******************************************************************************
changed: [192.168.139.140]
RUNNING HANDLER [test handlers] ****************************************************************
changed: [192.168.139.140]
PLAY RECAP *************************************************************************************
192.168.139.140 : ok=3 changed=2 unreachable=0 failed=0
在客户端上查看结果:
[root@knightlai02 ~]# ls /tmp/aaa.txt
/tmp/aaa.txt
[root@knightlai02 ~]# ls -lt /tmp/aaa.txt
-rw-r--r-- 1 root root 891 Nov 27 23:15 /tmp/aaa.txt
[root@knightlai02 ~]# cat /tmp/aaa.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
mysql:x:1000:1000::/home/mysql:/bin/bash
php-fpm:x:1001:1001::/home/php-fpm:/bin/bash
111111
11.playbook实战-nginx安装
思路:先在一台机器上编译安装好nginx、打包,然后再用ansible去下发
11.1 创建相关目录文件
- 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下为定义的变量
11.2 安装需要的依赖包
需要事先准备好安装用到的文件,具体如下:
- 在一台机器上事先编译安装好nginx,配置好启动脚本,配置好配置文件 安装好后,
- 我们需要把nginx目录打包,并放到/etc/ansible/nginx_install/roles/install/files/下面,名字为nginx.tar.gz
- 启动脚本、配置文件都要放到/etc/ansible/nginx_install/roles/install/templates下面
[root@knightlai01 roles]# vim ./common/tasks/main.yml
- name: Install initializtion require software
yum: name={{ item }} state=installed
with_items:
- zlib-devel
- pcre-devel
11.3 定义变量
[root@knightlai01 roles]# vim /etc/ansible/nginx_install/roles/install/vars/main.yml
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx
把所有用到的文档拷贝到目标机器
[root@knightlai01 roles]# 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
11.4接下来会建立用户,启动服务,删除压缩包
[root@knightlai01 roles]# 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
11.5再创建main.yml并且把copy和install调用
[root@knightlai01 roles]# vim /etc/ansible/nginx_install/roles/install/tasks/main.yml
- include: copy.yml
- include: install.yml
到此两个roles:common和install就定义完成了,接下来要定义一个入口配置文件
[root@knightlai01 roles]# vim /etc/ansible/nginx_install/install.yml
---
- hosts: testhost
remote_user: root
gather_facts: True
roles:
- common
- install
11.5 开始执行程序验证结果
[root@knightlai01 roles]# ansible-playbook /etc/ansible/nginx_install/install.yml
12.管理配置文件
生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。
下面我们来写个管理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: testhost
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