自动化运维之ansible

目录

前言

1. 环境准备

1.1 系统资源获取

1.2 安装ansible软件

2. ansible的介绍

 2.1 语法

 2.2 配置文件

3. ansible 的常用模块

3.1 系统命令

3.2 文件管理

3.3 用户管理

3.4 软件管理

4. 总结


前言

        ansible 是一种轻量级的自动化运维工具,基于Python的paramiko 开发,主要在进行批量的管理资源上有得天独厚的作用,能大大的提高运维的效率,基于ssh 协议架构,所以在被控节点上不需要安装ansible ,只需要开启ssh服务,和python环境;模块化,丰富多彩,部署简单,容易上手。

1. 环境准备

本次测试的环境为开源欧拉系统(openEuler 22.03-sp3),资源获取如下:

1.1 系统资源获取

1.1.1 下载资源

注:该资源为已经制作好的虚拟机基础镜像,直接下载;解压之后使用VMware Workstation 打开虚拟机即可。用户名root 秘密:1
链接: https://pan.baidu.com/s/1dorVPyfD5lN9UzDDtnoabA?pwd=2024 提取码: 2024

虚拟机镜像(openEuler)

1.1.2 克隆虚拟机

注:获取的虚拟机只是一个基础的镜像,本次测试需要用到2台虚拟机,需要在进行克隆一台,配置参考如下

主机名用途IP地址网卡模式网关
control控制节点192.168.8.202NAT192.168.8.254
node1被空节点192.168.8.203NAT192.168.8.254

配置的信息可以根据现场实际情况而定,不管是什么模式但记得虚拟机要能联网哟。

注:下面的操作都是在控制节点(control)执行

修改主机名 ,IP地址,域名解析的命令参考如下

# 修改主机名,并立即生效
[root@control ~]# hostnamectl set-hostname control ;bash

# 配置网卡的ip地址
  # 查看网卡信息
[root@control ~]# nmcli c s 
NAME    UUID                                  TYPE      DEVICE 
ens160  a855aa64-bf7f-419c-add0-dd9f1ddc5e78  ethernet  ens160
  # 给网卡 ens160 添加ip地址
[root@control ~]# nmcli c modify ens160 ipv4.method manual ipv4.addresses 192.168.8.203/24 ipv4.gateway 192.168.8.254 connection.autoconnect yes
  # 激活ens160网卡
[root@control ~]# nmcli c up ens160
  # 验证ens160网卡是否配置成功
[root@control ~]# ip a s | grep 203
inet 192.168.8.203/24 brd 192.168.8.255 scope global noprefixroute ens160
# 要能上网域名解析服务的配置可少不了
[root@control ~]# cat /etc/resolv.conf 
# 这里使用的是网关 192.168.8.254
nameserver 192.168.8.254

那么,这样一台虚拟机就可以上网了,ping www.baidu.com  测试一下吧

1.2 安装ansible软件

步骤1:建立主机之间的ssh互信

修改主机映射

# 
[root@control ~]# cat /etc/hosts
192.168.8.202 control
192.168.8.203 node1
# 拷贝一份到被空节点
[root@control ~] # scp /etc/hosts  root@node1:/etc/hosts 

ssh互信

#这里使用rsa加密模式,非交互式生成密钥对
[root@control ~] # ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ''
# 拷贝公钥到被空节点,第一次记得输入node1 节点的秘密哟
[root@control ~] # ssh-copy-id node1
# 验证看是否需要秘密,不需要秘密怎么设置成功
[root@control ~] # ssh node1 date 
Authorized users only. All activities may be monitored and reported.
Wed Sep  4 03:27:10 PM CST 2024

步骤2:安装ansible 软件

前置要求:要求控制节点python>2.6

场景一, 在线安装;因为控制节点已经联网就直接安装吧

# 开始安装,这里是在连接网络的情况下哟
[root@control ~]# yum -y install ansbile

# 安装成功之后,查看版本
[root@control ~]# ansible --version
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.9/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.9.9 (main, Dec 28 2023, 13:48:32) [GCC 10.3.1]

场景二,离线安装 (找一台能联网的主机,将ansible 需要的包下载下来,在打包大离线主机上即可)(本次测试不涉及,不需要执行该步骤

参考文献:ansible离线安装-CSDN博客


2. ansible的介绍

 2.1 语法

ansible 主机清单  选项   模块

主机清单:一般指 ansble 配置文件下的hosts 清单信息

选项:常用的选项 -m :代表模块

模块:第三节 有介绍常用的模块(ping ,copy,shell 等)

 2.2 配置文件

        ansible 的配置文件分为全局和局部的配置文件,推荐使用的局部的配置文件来进行自动化运维,因为ansible,遵循的理念是通过用户自建配置信息,进行管理,这样做的目的是,管理的人多了之后,通过用户来进行区分自己的配置或者需要管理的信息,便于高效管理并且不会响应他人的配置或者混乱。一般全局的配置文件都不用去动它。

全局配置文件(主配置文件)

[root@control ~]# ls /etc/ansible
-rw-r--r--. 1 root root 19980 Oct 11  2019 ansible.cfg       #主配置文件
-rw-r--r--. 1 root root  1016 Oct 11  2019 hosts             #存放主机的清单文件
drwxr-xr-x. 2 root root     6 Oct 11  2019 roles             #角色目录信息

局部配置文件(自定义配置文件)

        需要自己创建,我们可以参考主配置文件来进行创建,具体场景到哪里,没有任何的要求,自己创建个目录存放方便管理即可。这里(/root/ansible/ 目录为例)

 创建一个ansible 运行的家目录,(所有的ansible 的执行都在这个家目录下执行)

mkdir -p /root/ansible/

创建配置文件,给配置文件添加内容

[root@control ansible] # vim ansible.cfg
[defaults]
inventory = ~/ansible/hosts         #指定主机清单的路径
[root@control ansible] vim hosts    # 存放清单信息
[test]   # 定义一个test的组
node1    # 组内的成员,这里指被控节点的主机名

测试配置文件的可用性

[root@control ansible]# ansible all --list-hosts  # 这里看出 主机清单的信息
  hosts (1):
    node1

配置文件的查找顺序:

在ansible 执行过程中其实配置文件是至关重要的, 他会去查找配置文件的信息,那么查找的顺序怎么样的呢?

1.检查变量ANSIBLE_CONFIG 定义的配置文件

2.检查当前目录下./ansible.cfg 文件   (常用)

3.当前家目录下的~/ansible.cfg 文件

4.检查全局的配置文件/etc/ansible/ansible.cfg

可以看出查找的范围是逐步加大的,使用为什么执行ansible 操作时都需要在和配置文件所在的目录下执行。

      


3. ansible 的常用模块

        查看模块文档

ansible-doc 模块名称

3.1 系统命令

  • ping 模块

        测试网络的联通性

[root@control ansible]# ansible node1 -m ping 
node1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
  • shell和command 模块

        远程执行shell 命令,command远程控制不启动shell,不支持bash特性,如管道,重定向等

shell 模块远程shell,支持bash特性,但不能进行交互式(shell模块常用)

#command模块
[root@control ansible] # ansible test -m command -a "ps aux|wc -l"  #失败
[root@control ansible] # ansible test -m command -a "sleep &" #失败
[root@control ansible] # ansible test -m command -a "ps aux >a.txt" #失败
#shell模块
[root@control ansible] # ansible test -m shell -a "ps aux >a.txt" #成功
node1 | CHANGED | rc=0 >>
[root@control ansible] # ansible test -m shell -a "cat /root/a.txt"  #查看该信息
node1 | CHANGED | rc=0 >>
    PID TTY          TIME CMD
 169233 pts/2    00:00:00 sh
 169248 pts/2    00:00:00 platform-python
 169249 pts/2    00:00:00 sh
 169250 pts/2    00:00:00 ps
 #这里没有下模块代表使用的是默认的模块,由于我在配置文件ansible.cfg中module_name=shell 指定了默认的模块为shell了所以可以不用写
[root@control ansible]# ansible test -a "ps aux |wc -l"
node1 | CHANGED | rc=0 >>
205
#############  shell模块高级特性 creates 和removes 参数   ###########
creates     #当文件存在就跳过动作不执行
removes     #当文件不存在就跳过动作不执行
[root@control ansible]# ansible test -a "ps aux >/tmp/ps.txt creates='/tmp/ps.txt'" #如果文件/tmp/ps.txt在test主机上存在就不执行命令
#如果nginx.pid存在就停止nginx的访问。
[root@control ansible]# ansible test -a "/usr/local/nginx/sbin/nginx -s stop removes='/usr/local/nginx/logs/nginx.pid'"
  • script 模块

        脚本分发到被控节点单独执行(经常常用

[root@control ansible]# cat test.sh
hostname

[root@control ansible]# ansible test -m script -a "test.sh"
node1 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to node1 closed.\r\n",
    "stderr_lines": [
        "Shared connection to node1 closed."
    ],
    "stdout": "node1\r\n",
    "stdout_lines": [
        "node1"                 # 这里就是执行后的结果
    ]
}

3.2 文件管理

  • file 模块

        该模块用于文件的管理,比如文件的创建,修改,删除,权限等。

[root@control ansible]# ansible-doc file   #查看一下帮助文档
=path       #目标路径必选
- owner     #所有者
- group     #所属组
- mode      #权限数值
- state     #文档类型,touch(文件),directory(目录),link(软连接),hard (硬链接),absent(删除)
....
#创建一个文件nedu1.txt
[root@control ansible]# ansible test -m file -a "path='/root/nedu1.txt' state=touch"
#创建一个目录testdir
[root@control ansible]# ansible test -m file -a "path='/root/testdir' state=directory"
#创建一个软连接,src 代表软连接的源
[root@control ansible]# ansible test -m file -a "src='/etc/hosts' path='/root/hosts.txt' state=link"
#删除一个文件
[root@control ansible]# ansible test -m file -a "path=/root/nedu1.txt state=absent"
#删除目录
[root@control ansible]# ansible test -m file -a "path=/root/testdir state=absent"

#修改文件的权限0代表特殊权限位置,0是没有特殊权限。
[root@control ansible]# ansible test -m file -a "path=root/a.txt owner=oracle group=orinstall mode=0777"
  • copy 模块

        做分发,将控制节点内容,文件等分发到被控节点

#查看帮助文档
[root@control ansible]#  ansible-doc copy
= dest     #(被控节点)目标路径
- src      #源路径(控制节点的路径)
- content   #指定文件内容
...
#将本地控制节点的/etc/hostname 分发到test主机的opt目录下并重命名为hostnams.txt
[root@control ansible]# ansible test -m copy -a "src=/etc/hostname dest=/opt/hostname.txt"
#目标路径有同名的文件的则自动备份一个,主要是保证安全性
[root@control ansible]# ansible test -m copy -a "src=/etc/issue dest=/opt/hostname.txt backup=yes"
#按文件内容分发 content
[root@control ansible]# ansible test -m copy -a "content='welcome to test' dest=/opt/str.txt "
说明:分发如果执行是多次并且内容相同和执行一次是一样的效果,只就是幂等性
  • fetch 模块

        fetch 收集的意思,刚好和copy相反;收集被控节点的信息。

#查看帮助文档
[root@control ansible]# ansible-doc fetch
=dest   #目标路径,收集到的信息存放到哪里,指控制节点的路径
=src    #被控节点,源路径
#搜集一下被控节点的/etc/hosts 的信息
[root@control ansible]# ansible node1,node2 -m fetch -a "src=/etc/hosts dest=/opt"
[root@control ansible]# tree /opt      #查看收集的结果
/opt
|-- node1
|   `-- etc
|       `-- hosts
`-- node2
    `-- etc
        `-- hosts
  • lineinfile模块

        文件中行内的内容替换(替换整行),支持正则表达式。

#查看帮助文档
[root@control ansible]# ansible-doc lineinfile
= path   #要替换的路径文件
- regexp  #正则表达式
- line  #要替换的内容
- backup  #是否备份 yes
#将node1节点的/etc/selinux/config 文件内容中的SELINUX模式修改为disabled
[root@control ansible]# ansible node1 -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=disabled'"
#如果是没有指定替换那一行,则会在末尾新增一行
[root@control ansible]# ansible node1 -m lineinfile -a "path=/root/a.txt line='welcome to node1'"
[root@control ansible]# ansible node1 -a "cat /root/a.txt"  #查看效果
node1 | CHANGED | rc=0 >>
abc=xxx
abc=ssbbbb
welcome to node1
#行前写入整行 insertbefore=''
#在匹配含有a的关键字的行前插入一行
[root@control ansible]# ansible node2 -m lineinfile -a "path=/root/a.txt line='welcome' insertbefore='a'"
#行后写入整行 insertafter=''
[root@control ansible]# ansible node2 -m lineinfile -a "path=/root/a.txt line='welcome' insertafter='a'"
#删除一行
[root@control ansible]# ansible node2 -m lineinfile -a "path=/root/a.txt regexp='^abc' state=absent"
说明:如果替换时正则匹配的多行,那么实际以最后匹配的那一行为准,而当删除文本时,如果有多行文本都能被匹配,这些行都会被删除
  • replace 模块

        关键字的替换,支持正则表达式。

#查看帮助文档
[root@control ansible]#ansible-doc replace
= path
= regexp  #
- replace #替换regexp参数匹配到的字符串
- backup  #是否备份 yes
...
#/etc/selinux/config 文件内容中的SELINUX=enforcing模式修改为disabled
[root@control ansible]# ansible node2 -m replace -a "path=/etc/selinux/config regexp='enforcing' replace='disabled'"
# 给a.txt 文件的内容加#注释 \1表示保留()括号里的信息
[root@control ansible]# ansible node1 -m replace -a "path=/root/a.txt regexp='^(.*)' replace='#\1'"
#取消注释
[root@control ansible]# ansible node1 -m replace -a "path=/root/a.txt regexp='^#' replace=''"

注意:替换关键字是满足条件的会全部替换掉

3.3 用户管理

  • user 模块

        用于用户的创建,修改 ;常用的参数有

=name   # 指定需要创建的用户名(必填)

-state    # present 创建 ,absent删除

-home # 指定家目录

-password # 修改秘密

-groups         #指定附加组

-group        #指定脚本组

#查看帮助文档
[root@control ansible]# ansible-doc user
#创建一个oracle用户秘密为123
#这里password={{'秘密' | password_hash('sha512')}} 是固定格式,password_hash()是一个指定加密算法的函数,默认就是sha512算法
[root@control ansible]# ansible test -m user -a "name=oracle password={{'123' | password_hash('sha512'))}} state=present"
#修改用户家目录
[root@control ansible]# ansible test -m user -a "name=oracle home=/opt/oracle"
#指定附加组
[root@control ansible]# ansible test -m user -a "name=oracle groups=dba,oinstall"
#删除用户
[root@control ansible]# ansible test -m user -a "name=oracle state=absent"
  • group 模块

        创建,删除用户组

        =name   # y用户组名称

        -state    # 操作类型

#创建一个supper组
[root@control ansible]# ansible test -m group -a "name=supper state=present"
#删除supper组
[root@control ansible]# ansible test -m group -a "name=supper state=absent"

3.4 软件管理

  • yum_repository 模块

        创建,修改yum仓库文件 *.repo

-name         #名称id 类似[名称]

-description         #描述信息-->name

-baseurl         #仓库路径

-enabled         #是否启用 true , false

-gpgcheck         #是否开启校验,no | yes

#创建一个本地的yum仓库文件
[root@control ansible]# ansible test -m yum_repository -a  \
"name=my_yum description='this is local yums' enabled=true gpgcheck=no baseurl='file:///mnt/iso' "
#删除yum文件
[root@control ansible]# ansible test -m yum_repository -a  "name=my_yum state=absent"
#修改只是将对应的值进行修改就可以了,创建成功会会在/etc/yum.repos.d/下生成一个于name定义名称一样的名称.repo文件

  • yum 模块

        软件安装,卸载,升级

-name        # 软件名,如果是包组,需要在包组名称前夹@ 

-state         #present(安装),absent(卸载) ,latest(升级)

#安装httpd软件
[root@control ansible]# ansible test -m yum -a "name=httpd state=present"
#安装图形工具包
[root@control ansible]# ansible test -m yum -a "name=@'server with gui' state=present"
#升级vsftp
[root@control ansible]# ansible test -m yum -a "name=vsftp state=latest"
  • service 模块 

        用户管理linux 服务的,这里被systemd 管理的服务

=name   # 服务名称

-enabled        # 是否开机自启; true ,false

-state         # started,restarted ,stopped

#启动httpd服务
[root@control ansible]# ansible test -m service -a "name=httpd state=started"
#停止http服务
[root@control ansible]# ansible test -m service -a "name=httpd state=stopped"
#设置开启自启http服务
[root@control ansible]# ansible test -m service -a "name=httpd enabled=true"

4. 总结

        模块非常多,就不做一一的介绍了,要到是时候记得会使用查看帮助文档,ansible-doc 模块名,赶紧动动小手练习一下吧。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值