一、认识ansible
Ansible是一款开源自动化运维工具。它有如下特点:
1、不需要安装客户端,通过sshd去通信,比较轻量化;
2、基于模块工作,模块可以由任何语言开发,比较自由和开放;
3、不仅支持命令行使用模块,也支持编写yaml格式的playbook,易于编写和阅读;
4、安装十分简单,RHEL/Rocky上可直接yum安装;
5、有提供UI(浏览器图形化)http://www.ansible.com/tower,但是收费的;
6、目前Ansible已经被RedHat公司收购,它在Github上是一个非常受欢迎的开源软件
二、安装ansible
1.机器准备(用的redhat 9)
主机名 | 作用 |
---|---|
control(192.168.85.133) | 控制端 |
manged (192.168.85.129) | 被控制端 |
2.控制端安装ansible
dnf install ansible-core 自带的版本较低
使用pipx进行网络安装
python3 -m pip install --user pipx
【root@192 】pip install ansible
3.主机改名
[root@localhost ~]# hostnamectl set-hostname control
[root@localhost ~]# hostnamectl set-hostname manged
4.设置密钥认证,ssh无密码登录
ssh-keygen生成一对密钥(公钥和密钥);ssh-copy-id把本地主机的公钥复制到目标主机上,会在/root/。ssh下生成,id_rsa为私钥,rsa.pub为公钥,它会被发送到远程主机的.ssh目录。
[root@control ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:ix4x2B2W0UYMEo3mXTRdjBk80akGaw4HcR95hpnvKGk root@control
The key's randomart image is:
+---[RSA 3072]----+
| o++B=o+&.. |
| o.o+*o@.* |
| o .++ o.* |
| o.oo.+ o . |
| . + S= o o |
| + .E . . |
| o .. . |
| . . |
| . |
+----[SHA256]-----+
[root@control ~]# ssh-copy-id 192.168.85.129
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.85.129 (192.168.85.129)' can't be established.
ED25519 key fingerprint is SHA256:pZV20K/MGiBcrjDwuiY8PCjvlRuVtMNZ2xsE4ahgJbg.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.85.129's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '192.168.85.129'"
and check to make sure that only the key(s) you wanted were added.
ssh远程连接就不需要密码了。
4.通过tree查看ansible的主要文件
root@localhost ~] tree /etc/ansible/
/etc/ansible/
├── ansible.cfg #主配置文件
├── hosts #主机清单文件 必须写
└── roles #公共角色文件
[root@localhost ~] vim /etc/ansible/hosts
[liang] #组中两个被管理机的IP以及组名(相当于组长),组名名字可以随便取
192.168.16.135
192.168.16.136
没有组的主机要在有组的前面
查看主机清单的主机结构
[root@control ansible]# ansible-inventory --graph
@all:
|--@ungrouped:
|--@webserver:
| |--manged
如果写的域名还需在/etc/hosts写配置
5.测试
[root@localhost ~] ansible all -m ping
#解释:用于测试远程主机是否在线,回复pong表示在线
#ping模块用于检查指定节点机器(被管理主机)是否还能连通,
#用法简单,不涉及参数,主机如果在线,则回复pong
6.学习ansible的管理配置文件
一、使用 /etc/ansible/ansible.cfg 。该文件为默认的 Ansible 配置文件,如果找不到其他的配置文件,
则使用该配置文件。
二、使用 ~/.ansible.cfg 。在用户家目录中的 .ansible.cfg 配置文件,如果存在此配置文件并且当前工作
目录也没有 ansible.cfg 配置文件,则使用此配置文件替代 /etc/ansible/ansible.cfg 配置文件。
三、使用 ./ansible.cfg 。如果执行命令的目录中存在该文件,则使用该文件来替代其他所有的配置文
件。这样可以创建一种目录结构,将不同的环境或项目存储在单独的目录中,并且每一个目录包含
为独特的一组设置而定义的配置文件。这是通常的做法。
四、也可以使用 ANSIBLE_CONFIG 环境变量来动态指定配置文件,如果定义了该变量,则 Ansible 不使用上
面任何的配置文件。
ansible的配置文件会随着运行ansible命令的位置而改变使用的配置文件,并且每个文件都是独立的,可通过 ansible --version查看
Ansible 配置文件主要有两个部分组成:
[defaults] 部分设置 Ansible 操作的默认值
[privilege_escalation] 配置 Ansible 如何在受管主机上执行特权升级
[defaults]
inventory = ./inventory 指定清单文件的路径
remote_user = user 要在受管主机上登陆的用户名
ask_pass = false 是否提示输入 SSH 密码,如果使用证书登陆,则可以是 false
[privilege_escalation]
become = true 是否提示输入 SSH 密码,如果使用证书登陆,则可以是 false
become_method = sudo 切换方法,通常为 sudo
become_user = root 切换到的用户,通常是 root
become_ask_pass = true 是否需要为 become_method 提示输入密码
如果远程用户为非特权用户,需要知道是否应尝试将特权用户升级为 root 以及如何进行升级。
是否提示输入 SSH 密码或 sudo 密码以进行登陆或者获取特权
二、ansible常用模块
[root@control ansible]# ansible-doc yum 查看模块用法
[root@localhost ~]# ansible-doc -l 查看ansibe中已有的模块
ansible调用格式:
ansible [节点] -m [模块] -a [参数]
1.setup模块
[root@localhost ~]# ansible all -m setup 查看某个节点的信息
2.copy模块
该模块可实现从管理机向节点复制静态文件,并设置合理的权限
参数 选项 含义
dest --- 文件复制的目的地
src --- 复制的源文件
backup yes/no 是否备份原始文件
validate - 复制前是否检验需要复制目的路径
mode --- 给文件加权限
使用:ansible all -m copy -a ‘src= ~ /xixi.txt dest=~/ mode=777’
3.command模块和shell模块
默认是command模块,command模块是不支持管道,》,《等使用的,但是shell脚本可以。
使用:ansible all -m shell -a “ls -l /”
ansible all -m shell -a “ps -ef | httpd”
4.script模块
cript模块用于将管理机的shell脚本发送到节点上执行。在实际的工作中,经常会发送脚本控制远程主机执行指定任务,所有该模块使用会频繁使用。
写一个脚本
[root@control ~]# vim xi.sh
[root@control ~]# cat xi.sh
!#/bin/bash
echo "hello ansible"
`touch hell.txt`
[root@control ~]# ansible all -m script -a "~/xi.sh"
在目标主机执行后出现该文件
5、yum模块
yum模块能够从指定的服务器自动下载安装RPM包,并且可以自动处理依赖性关系。
参数 选项 含义
name --- 包名
state present 安装(默认)
latest 更新
absent 卸载
使用: ansible all -m yum -a “name=vsftpd state=present”
6.serice模块
service模块用来管理节点上的服务,可开启,关闭,重启服务,如httpd,sshd,nfs,named等服务。
参数 选项 含义
enabled yes/no 是否开机自启动
name --- 服务名称
pattern --- 若服务没响应,则ps查看是否已经启动
start 启动
state stoped 关闭
restarted 重启
reloaded 重新下载
使用:ansible all -m shell -a “systemctl stop httpd”
7.blockinfile模块
path 路径
insertafter=EOF 文件末尾添加
block=“的亟待解决的” 添加的内容
8.lineinfile模块
9.unarchive解包解压缩模块
三、编写Playbook
命令是在节点上执行任务的,使用起来复杂,且重复,为避免重复,ansible提供playbook脚本,一个可以被ansible执行的YAML文件叫做playbook。
playbook 均具有幂等性。这意味着,可以在相同主机上多次安全地运行一个playbook。当的系统处于正确状态时,playbook在运行时不会进行任何更改。
模块总结:
模块类别 | 模块 |
---|---|
文件模块 | copy/file/lineinfile |
软件包模块 | package/yum/dnf/pip |
系统模块 | firewalld/reboot/service/user/group |
网络模块 | get_url/nmcli/uri |
但是这么多模块,想记住如何使用来写playbook是很难的,可以通过ansible-doc yum命令查看最后的示例,在说明最后会写。
格式
yaml 格式通常使用 yml 来作为后缀保存,playbook 使用空格缩进来表示其数据结构,YAML 对于缩进的空格数量没有严格的要求,但是有两个最基本的规则:
1、处于层级结构中同一层级的数据元素,必须具有相同的缩进量
2.如果项目属于其他项目的子项,其缩进量必须大于父项
注意: 只能使用空格字符可用于缩进,不能使用制表符。
如果使用的是vim工具,则可以使用以下指令来改善编辑环境:
[root@kittod ansible]# cat ~/.vimrc
autocmd FileType yaml setlocal ai ts=2 sw=2 et
Playbook示例 安装httpd服务
示例:httpd.yml
- name: first play
- hosts: websrvs
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
示例2:
使用playbook安装数据库并启动,修改密码
- hosts: dbserver
tasks:
- name: mv file
copy: src=~/mysql_install dest=~/
- name: yum mysql
shell: yum install ~/mysql_install/* -y
- name: 启动mysql
service: name=mysqld state=started enabled=yes
- name: 获取mysql临时密码
shell: grep password /var/log/mysqld.log | awk '{print $13}'
register: mysql_password
- name: 修改mysql的密码
shell: mysqladmin -uroot -p'{{mysql_password.stdout}}' password "Lygredhat@123"
``
批量安装zabbix-agent2的客户端:
[root@server ~]# cat zabbix.agent.yml
---
- name: 安装zabbix-agent2的客户端
hosts: all
tasks:
- name: download zabbix rpm release
get_url:
url: https://repo.zabbix.com/zabbix/6.0/rhel/7/x86_64/zabbix-release-6.0-4.el7.noarch.rpm
dest: /tmp/
- name: install zabbix
yum:
name: /tmp/zabbix-release-6.0-4.el7.noarch.rpm
state: present
- name: download zabbix-agent
yum:
name: zabbix-agent2
state: present
- name: enable zabbix-agent
systemd:
name: zabbix-agent2
enabled: yes
state: started
测试:
[root@ctrol ~]# ansible-playbook mysql.yaml --syntax-check #语法检测
[root@ctrol ~]# ansible-playbook mysql.yaml --list-tasks #列出任务
[root@ctrol ~]# ansible-playbook mysql.yaml --list-hosts #列出主机
[root@ctrol ~]# ansible-playbook mysql.yaml #执行
四、编写playbook时vim可以修改的配置
[root@server ~]# cat ~/.vimrc
set nu ai et paste ts=4
#autocmd FileType yaml setlocal ai et ts=2 sw=2
set cursorline
set cursorcolumn
[root@manager ~]# 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