一、Ansible 基础介绍

1、概述

互联网技术的发展,机房里面机器的数量随之增加,运维的难度和复杂度也在增加,需要投入的运维人员和成本也在增加,从而催生了一系列的自动化运维工具(Ansible、SaltStack、Puppet)的产生来减少运维的成本。 

Ansible、SaltStack、Puppet都是目前比较受用户欢迎的自动化化运维工具,其中Ansible和SaltStack使用python编写,具有良好的可移植性。Puppet的使用脚本语法复杂,且可移植性比较差,目前的使用者慢慢变少。

2、Ansible是什么?

Ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。

Ansible 是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是 Ansible 所运行的模块,Ansible 只是提供一种框架。主要包括:

  1. 连接插件 connection plugins:负责和被监控端实现通信;
  2. host inventory:指定操作的主机,是一个配置文件里面定义监控的主机;
  3. 各种模块核心模块、command 模块、自定义模块;
  4. 借助于插件完成记录日志邮件等功能;
  5. playbook:剧本执行多个任务时,非必需可以让节点一次性运行多个任务。

3、为什么要选择Ansible

  1. Ansible完全基于Python开发,而DevOps在宫内已经是一种趋势,Python被逐步普及,运维人员自己开发工具的门槛逐步降低,得益于此,方便对Ansible二次开发;
  2. Ansible丰富的内置模块,甚至还有专门为商业平台开发的功能模块,近600个模块完全可以满足日常功能所需;
  3. 在Ansible去中心化概念下,一个简单的复制操作即可完成配置管理中心的迁移;
  4. Agentless(无客户端)客户端无须任何的配置,由管理端配置好后即可使用,这点非常诱人。

4、Ansible是如何工作的 

Ansible没有客户端,因此底层通信依赖于系统软件,Linux系统下基于OpenSSH通信Windows系统下基于PowerShell,管理端必须是Linux系统,使用者认证通过后再管理节点通过Ansible工具调用各应用模块,将指令推送至被管理端执行,并在执行完毕后自动删除产生的临时文件。

5、Ansible基础架构

【01】Ansible 自动化配置入门

5、相关网站 

http://www.ansible.com.cn/ 

https://www.ansible.com/

https://docs.ansible.com/

二、Ansible 模块安装

1、先安装epel源(提供最新的ansible)
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

2、使用yum安装
[[email protected] ~]# yum install ansible -y

3、查看ansible的版本
[[email protected] ~]# ansible --version

三、Ansible 配置文件

1、配置文件查找顺序

Ansible的配置文件,配置文件可以随意放,但有查找顺序,依次是:

1、$ANSIBLE_CONFIG            #系统默认变量
2、ansible.cfg                #当前目录下面查找
3、.ansible.cfg               #当前用户的家目录下查找
4、etc/ansible/ansible.cfg    #系统默认

2、默认配置文件注释

cat /etc/ansible/ansible.cfg 

#inventory      = /etc/ansible/hosts      #主机列表配置文件
#library        = /usr/share/my_modules/  #库文件存放目录
#remote_tmp     = ~/.ansible/tmp          #临时py文件存放在远程主机目录
#local_tmp      = ~/.ansible/tmp          #本机的临时执行目录
#forks          = 5                       #默认并发数
#sudo_user      = root                    #默认sudo用户
#ask_sudo_pass = True                     #每次执行是否询问sudo的ssh密码
#ask_pass      = True                     #每次执行是否询问ssh密码
#remote_port    = 22                      #远程主机端口
host_key_checking = False                 #跳过检查主机指纹
log_path = /var/log/ansible.log           #ansible日志

[privilege_escalation]   #如果是普通用户则需要配置提权
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False

四、Ansible 主机清单

Inventory

Inventory

注意:如果控制端和被控制端第一次通讯,需要先添加指纹信息,那如果机器特别多少的情况下怎么办?

#仅需开启ansible中的 host_key_checking = False

1、基于**连接,需要先创建公钥和私钥,并下发公钥至被控端
[[email protected] ~]# ssh-******
...一直回车
[[email protected] ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[[email protected] ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]

2、配置主机清单(静态写法)
[[email protected] ~]# cat hosts
[webservers]
web01 ansible_ssh_host=172.16.1.7 ansible_ssh_port=22
web02 ansible_ssh_host=172.16.1.8  
#使用别名可以展示主机名称
#默认22端口可以不写

3、基础命令
[[email protected] ~]# ansible webservers -m ping -i./hosts
#命令+主机组+执行的动作+指定inventory的位置

4、[servers]组包括两个子组lbservers,webservers
[[email protected] ~]# cat hosts
[servers:children]
lbservers
webservers

[lbservers]
lb01 ansible_ssh_host=172.16.1.5
lb02 ansible_ssh_host=172.16.1.6  

[webservers]
web01 ansible_ssh_host=172.16.1.7
web02 ansible_ssh_host=172.16.1.8 

5、列出inventory的主机清单
[[email protected] ~]# ansible servers -m ping -i ./hosts --list-hosts
[[email protected] ~]# ansible all -m ping -i ./hosts --list-hosts       #系统中默认的组all

五、Ansible Ad-Hoc

1、Ad-Hoc 模式命令

[[email protected] ~]# ansible webservers -m command -a 'df -h' -i ./hosts

【01】Ansible 自动化配置入门

Ad-Hoc 结果返回

绿色: 代表被管理端主机没有被修改

黄色: 代表被管理端主机发现变更

红色: 代表出现了故障,注意查看提示

2、Ad-Hoc 常用模块

1)ansible-doc帮助手册

#使用过程中需要先了解ansible-doc帮助手册

[[email protected] ~]# ansible-doc -l        # 查看所有模块说明
[[email protected] ~]# ansible-doc copy      # 表示指定模块方法
[[email protected] ~]# ansible-doc -s copy   # 表示指定模块参数

#常用模块

command             # 执行shell命令(不支持管道等特殊字符)
shell               # 执行shell命令
scripts             # 执行shell脚本
yum_repository      # 配置yum仓库
get_url             # 联网下载
yum                 # 安装
copy                # 配置
service,systemd     # 启动
user,group          # 创建用户与组
file                # 授权
crond               # 定时任务
mount               # 挂载
firewalld           # 防火请
selinux	            # selinux

2)执行命令模块

1、command默认执行bash命令模块,模块不支持重定向或管道
[[email protected] ~]# ansible servers  -a "hostname"   # 如果需要一些管道操作,则使用shell
-----------------------------------------------------------------------------------------

2、shell模块,如果需要一些管道操作,则使用shell
[[email protected] ~]# ansible servers -m shell -a "ifconfig|grep eth0" 
                                                                 # -f 50 #设置主机用户并发数
-----------------------------------------------------------------------------------------

3、script脚本模块
[[email protected] ~]# cat yum.sh

#!/usr/bin/bash
yum install -y iftop

#在本地运行模块,等同于在远程执行,不需要将脚本文件进行推送目标主机执行
[[email protected] ~]# ansible servers -m script -a "/server/scripts/yum.sh"

3)软件安装模块

[[email protected] ~]# ansible servers -m yum -a "name=httpd state=present"
       					
name		#指定要安装的软件包名称
file://		#指定从本地哪个目录安装rpm
http://		#指定从哪个网站安装rpm包

state       	   #指定使用yum的方法
        present    #安装软件包(installed)
        absent     #移除软件包(removed)
        latest	   #安装最新软件包             
        
list=package				       #列出当前仓库可用的软件包
disablerepo="epel,ol7_latest"	   #安装软件时,不从哪些仓库获取
download_only=true				   #仅下载软件包,不安装

4)文件管理模块

1、copy文件拷贝模块

1)拷贝文件文件至被控节点
[[email protected] ~]# ansible servers -m copy -a "src=/etc/hosts dest=/tmp/test.txt owner=root group=root" -i ./hosts

2)对远端已有文件进行备份,按照时间信息备份
[[email protected] ~]# ansible servers -m copy -a "src=/etc/hosts dest=/tmp/test.txt owner=root group=root backup=yes"  -i ./hosts

3)向被控端主机写入数据,并且会覆盖远端文件内原有数据信息
[[email protected] ~]# ansible servers -m copy -a "content='bgx' dest=/tmp/oldboy" -i ./hosts

src             #推送数据的源文件信息
dest            #推送数据的目标路径
backup          #对推送传输过去的文件,进行备份(仅当文件发生变化才备份)
content         #直接批量在被管理端文件中添加内容
group           #将本地文件推送到远端,指定文件属组信息
owner           #将本地文件推送到远端,指定文件属主信息
mode            #将本地文件推送到远端,指定文件权限信息
-----------------------------------------------------------------------------------------

2、file文件创建模块

1)直接修改被控端的权限
[[email protected] ~]# ansible web01 -m file -a "path=/opt mode=0400" -i ./hosts

2)在被控端创建目录
[[email protected] ~]# ansible oldboy -m file -a "path=/tmp/oldboy state=directory"

3)在被控端创建文件
[[email protected] ~]# ansible oldboy -m file -a "path=/tmp/test state=touch mode=555 owner=root group=root"

4)递归授权目录权限
[[email protected] ~]# ansible oldboy -m file -a "path=/data owner=bgx group=bgx recurse=yes"

path            #指定远程主机目录或文件
recurse         #递归授权
state           #状态
    directory   #在远端创建目录
    touch       #在远端创建文件
    link        #创建链接文件(秒级回退)
    absent      #表示删除文件或目录
    mode        #设置文件或目录权限
    owner       #设置文件或目录属主
    group       #设置文件或目录属组
-----------------------------------------------------------------------------------------

3、get_url文件下载模块

1)通过get_url下载文件或者软件
[[email protected] ~]# ansible servers -m get_url -a "url=http,https  dest=/opt mode=0777" -i ./hosts

2)下载一个文件前先进行md5校验,通过则下载,不通过则失败
[[email protected] ~]# ansible webservers -m get_url -a "url=http,https  dest=/opt mode=0777 checksum=md5:值" -i ./hosts

#md5sum+软件包获取md5值

url         #文件在网络上的具体位置
dest        #下载到被控端的哪个目录下
checksum    #校验(md5  sha256)

5)服务管理模块

1、ansible管理服务的启动与停止,使用service、systemd

1)启动crond服务,并加入开机自启
[[email protected] ~]# ansible servers -m service -a "name=crond state=started enabled=yes"

2)停止crond服务,并删除开机自启
[[email protected] ~]# ansible servers -m service -a "name=crond state=stopped enabled=no"

3)重启crond服务
[[email protected] ~]# ansible servers -m service -a "name=crond state=restarted"

4)重载crond服务
[[email protected] ~]# ansible servers -m service -a "name=crond state=reloaded"

name                # 定义要启动服务的名称

state               #指定服务状态
        started     #启动服务
        stopped     #停止服务
        restarted   #重启服务
        reloaded    #重载服务       
enabled             #开机自启

6)用户管理模块

1、group组模块
[[email protected] ~]# ansible servers -m group -a "name=oldgirl gid=888"
name            #指定创建的组名

gid             #指定组的gid
state
    absent      #移除远端主机的组
    present     #创建远端主机的组(默认)
-----------------------------------------------------------------------------------------

2、user模块

1)创建用户指定uid和gid,不创建家目录也不允许登陆
[[email protected] ~]# ansible servers -m user -a "name=test uid=666 uid=888 group=888 shell=/sbin/nologin create_home=no" ./hosts 

2)删除用户
[[email protected] ~]# ansible servers -m user -a "name=test state=absent" -i ./hosts 

3)给新创建的用户生成ssh**对
[[email protected] ~]# ansible servers -m user -a "name=lhl uid=6677 group=admin generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa" -i ./hosts 

4)将明文密码进行hash加密
[[email protected] ~]# ansible localhost -m debug -a "msg={{ '123456' | password_hash('sha512', 'salt') }}"
localhost | SUCCESS => {
    "msg": "$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w.igcOo1R7vBYR65JquIQ/7siC7VRpmteKvZmfSkNc69."
}

5)进行用户创建
[[email protected] ~]# ansible webservers -m user -a 'name=lhl password=$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w.igcOo1R7vBYR65JquIQ/7siC7VRpmteKvZmfSkNc69. create_home=yes shell=/bin/bash' -i ./hosts 

#一定要用单引号,双引号会解析特殊字符!

uid             #指定用户的uid
group           #指定用户组名称
groups          #指定附加组名称
password        #给用户添加密码(记得加单引号)
shell           #指定用户登录shell(/bin/bash)
create_home     #是否创建家目录(true flase)

7)定时任务模块

1、crond定时任务模块

1)正常使用crond服务
[[email protected] ~]# crontab -l
* * * * *  /bin/sh /server/scripts/test.sh

2)使用ansible添加一条定时任务
[[email protected] ~]# ansible servers -m cron -a "minute=* hour=* day=* month=* weekday=* job='/bin/sh /server/scripts/test.sh &>dev/null'"

*****可省略不写(默认没写的时间都算*表示)
[[email protected] ~]# ansible servers -m cron -a " job='/bin/sh /server/scripts/test.sh &>dev/null'"

3)设置定时任务注释信息,防止重复,name设定
[[email protected] ~]# ansible webservers -m cron -a "name='cron01' job='/bin/sh /server/scripts/test.sh'"

4)删除相应定时任务
[[email protected] ~]# ansible servers -m cron -a "name='ansible cron02' minute=0 hour=0 job='/bin/sh test.sh' state=absent"

5)注释相应定时任务,使定时任务失效
[[email protected] ~]# ansible servers -m cron -a "name='ansible cron01' minute=0 hour=0 job='/bin/sh /server/scripts/test.sh' disabled=yes"

8)磁盘挂载模块

1、mount挂载模块

web01:nfs  

1)web01安装nfs
[[email protected] ~]# ansible web01 -m yum -a 'name=nfs-utils state=present' -i ./hosts

2)在nfs上创建共享的目录
[[email protected] ~]# ansible web01 -m file -a 'path=/data state=directory' -i ./hosts

3)配置nfs
[[email protected] ~]# ansible web01 -m copy -a 'content="/data 172.16.1.0/24(rw,sync,no_all_squash)" dest=/etc/exports' -i ./hosts 

4)启动nfs
[[email protected] ~]# ansible web01 -m systemd -a "name=nfs state=started enabled=yes" -i ./hosts

#控制端创建配置文件通过copy模块推送至nfs服务端
-----------------------------------------------------------------------------------------

web02:客户端挂载

1)开机挂载,仅将挂载配置写入/etc/fstab
[[email protected] ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=present"

2)挂载设备,并将配置写入/etc/fstab
[[email protected] ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=mounted"

3)卸载设备,不会清除/etc/fstab写入的配置
[[email protected] ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=unmounted"

4)卸载设备,会清理/etc/fstab写入的配置
[[email protected] ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=absent"

present     # 开机挂载,仅将挂载配置写入/etc/fstab
unmounted   # 卸载设备,不会清除/etc/fstab写入的配置
absent      # 卸载设备,会清理/etc/fstab写入的配置
mounted     # 挂载设备,并将配置写入/etc/fstab

9)安全管理模块

1、Selinux模块
[[email protected] ~]# ansible servers -m selinux -a "state=disabled" -i ./hosts

2、firewalld模块

1)开启防火墙
[[email protected] ~]# ansible servers -m systemd -a "name=firewalld state=started" -i ./hosts 

2)永久开启http服务
[[email protected] ~]# ansible servers -m firewalld -a "service=http immediate=yes permanent=yes state=enabled" -i ./hosts 

3)永久开启放行8080至8090端口
[[email protected] ~]# ansible servers -m firewalld -a "port=8080-8090/tcp immediate=yes permanent=yes state=enabled" -i ./hosts 

service			#指定开放或关闭的服务名称
port			#指定开放或关闭的端口
masquerade		#开启地址伪装
immediate		#临时生效
permanent		#是否添加永久生效
state			#开启或是关闭

zone			#指定配置某个区域
rich_rule		#配置富规则
source			#指定来源IP

 

相关文章: