Ansible安装及使用
该案例使用的操作系统为:RockyLinux-8.8 (该操作系统为CentOS的替代产品)
下载软件包
可以在阿里云镜像仓库下载:https://developer.aliyun.com/mirror/
安装
将下载好的软件包使用工具(例如MobaXterm)复制到linux系统里面
[root@localhost ~]# ls
anaconda-ks.cfg ansible-core-2.15.3-1.el8.x86_64.rpm
[root@localhost ~]# yum -y localinstall ansible-core-2.15.3-1.el8.x86_64.rpm
localinstall
是yum的一个子命令,用于安装本地的软件包,而不是从yum仓库安装
配置
创建一个工作目录,之后的操作都将在工作目录里面进行
[root@localhost ~]# mkdir project
[root@localhost ~]# cd project
[root@localhost project]# 之后所有的操作都在这个目录内
创建配置文件
默认的配置文件是/etc/ansible/ansible.cfg,但是一般不使用它,而是在工作目录下创建自己的配置文件
[root@localhost project]# vim ansible.cfg # 文件名必须是ansible.cfg
[defaults]
host_key_checking = false # 不检查主机密钥,=号两边空格可有可无。
inventory = inventory # 定义主机清单文件为inventory
创建主机清单文件
写在[]里的是组名,[]下面的是组内的主机名
[root@localhost project]# vim inventory
# 服务器名称 ansible_host=服务器IP地址
[mysql]
mysql01 ansible_host=192.168.0.31
mysql02 ansible_host=192.168.0.32
mysql03 ansible_host=192.168.0.33
[all:vars] # all是ansible自带的组,表示全部主机
ansible_ssh_user=root
ansible_ssh_pass=root
测试
[root@localhost project]# ansible all -m ping
mysql02 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
mysql03 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
mysql01 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
和上面效果相似,或者显示为绿是,就说明配置没问题
学习模块的使用
[root@localhost project]# ansible-doc -l # 列出全部可用模块,按空格键向下翻页,按q退出
[root@localhost project]# ansible-doc -l | wc -l # 列出模块数量
[root@localhost project]# ansible-doc -l | grep yum # 查看包含yum的模块名
[root@localhost project]# ansible-doc yum # 查看yum模块的帮助文档,按空格键向下翻页,按q退出
使用,编写Playbook
语法格式为yaml
yaml文件的文件名,一般以yml或yaml作为扩展名
- 文件一般以
---
作为第一行,不是必须的,但是常用 - 键值对使用冒号
:
表示,冒号后面必须有空格。 - 数组使用
-
表示,-
后面必须有空格。 - 相同的层级必须有相同的缩进。如果缩进不对,则有语法错误。每一级缩进,建议2个空格。
- 全文不能使用tab,必须使用空格
配置vim适应yaml语法
# 文件位置和名字是固定的,用于设置vim的格式
[root@localhost ~]# vim ~/.vimrc
set ai # 设置自动缩进
set ts=2 # 设置按tab键,缩进2个空格
set et # 将tab转换成相应个数的空格
安装软件
使用yum模块
[root@localhost project]# vim install.yml
---
- name: 安装软件
hosts: mysql
tasks:
- name: 安装vim和bash-completion
yum:
name: vim,bash-completion
state: present
安装多个软件包,还可以写为:
---
- name: 安装软件
hosts: mysql
tasks:
- name: 安装vim和bash-completion
yum:
name:
- vim
- bash-completion
state: present
安装软件,并启动
---
- name: Install and configure Nginx
hosts: your_target_hosts # 替换为你的目标主机或主机组
become: yes # 使用sudo权限
tasks:
- name: Install Nginx
yum:
name: nginx
state: present
- name: Ensure Nginx is running and enabled at boot
systemd:
name: nginx
state: started
enabled: yes
Ansible还有许多模块,这个文档我应该还会更新,但作为初学者,我更推荐直接使用AI工具搜索,因为你可能不清楚,它有什么模块,但是你知道,你要做什么,比如,我上面的例子,就是通过文心一言搜索的,为搜索词条是:“使用ansible安装nginx,并且启动”
我经常使用的AI工具是:文心一言(就普通版本,没有充值会员),平常工作日,如果人多,提示服务器忙不过来,我就用,通义千问。智谱清言也不错,但它老是用英文回答。