yum install python39 -y
pip3.9 install ansible
# 查看版本
ansible --version
mkdir /etc/ansible
# 此处根据安装的 ansible 版本进行修改
# wget -O /etc/ansible.cfg https://raw.githubusercontent.com/ansible/ansible/stable-2.14/examples/ansible.cfg
touch /etc/ansible.cfg
vim /etc/ansible/hosts
[test]
test-node1
test-node2
# 方式一
[test]
192.168.133.111 ansible_ssh_user=root ansible_ssh_pass=123456
192.168.133.112 ansible_ssh_user=root ansible_ssh_pass=123456
192.168.133.123 ansible_ssh_user=root ansible_ssh_pass=123456
# 方式二
[test]
192.168.133.111
192.168.133.112
192.168.133.123
[test:vars]
ansible_ssh_user=root
ansible_ssh_pass=123456
# 方式三
[test]
192.168.133.111
192.168.133.112
192.168.133.123
# 在/etc/ansible目录下创建目录group_vars,然后再创建文件test.yml,以组名命名的yml文件
vim /etc/ansible/group_vars/test.yml
# 内容如下
ansible_ssh_user: root
ansible_ssh_pass: 123456
# 生成秘钥
ssh-keygen -t rsa
# 配置秘钥
ssh-copy-id -i ~/.ssh/id_rsa.pub root@test-node1
ssh-copy-id -i ~/.ssh/id_rsa.pub root@test-node2
ansible test -m ping
# 查看cron帮助
ansible-doc cron
ansible 官方存在大量的模块,我们使用 ansible 主要使用的也是因为它有大量的模块和插件,虽然模块很多,但是我们常用的模块就那么几种,下面介绍以下常用模块:
模块名 | 说明 |
---|---|
command(默认) | 不支持管道过滤 grep |
shell | 支持管道过滤 grep |
script | 不用把脚本复制到远程主机就可以在远程主机执行脚本 |
yum | 安装软件 |
yum_repository | 配置 yum 源 |
copy | 拷贝文件到远程主机 |
file | 在远程主机创建目录或者文件 |
service | 启动或停止服务 |
mount | 挂载设备 |
cron | 执行定时任务 |
firewalld | 防火墙设置 |
get_url | 下载软件或访问网页 |
git | 执行 git 命令 |
参数 | 选项 | 含义 |
---|---|---|
src | 源目录或文件 | |
dest | 目标目录或文件 | |
remote_src | True、False | src 是远程主机上还是在当前主机上,仅在 mode=preserve 有效 |
owner | 所属用户 | |
group | 所属组 | |
mode | 0655、u=rw、u+rw | 设置文件权限 |
backup | yes、no | 是否备份目标文件 |
content | 写入目标文件的内容 |
示例:
# 拷贝apache配置文件到目标机器
ansible test -m copy -a "src=httpd.conf dest=/etc/httpd/conf/httpd.conf owner=root group=root mode=644"
# 拷贝apache配置文件到目标机器,并备份目标文件
ansible test -m copy -a "src=httpd.conf dest=/etc/httpd/conf/httpd.conf owner=root group=root mode=644 backup=yes"
# 在远程主机创建一个文件并写入内容
ansible test -m copy -a "content=HelloWorld dest=/home/index.html"
参数 | 含义 |
---|---|
url | 地址 |
dest | 目标文件 |
mode | 文件权限 |
# 下载文件到本地
ansible test -m get_url -a "url=http://xx.xx.xx/ssss.txt dest=/home/xx.txt mode=655"
# 创建文件
ansible test -m file -a "path=/home/aaa.txt state=touch"
# 创建目录
ansible test -m file -a "path=/home/test state=directory"
# 递归修改目录权限
ansible test -m file -a "path=/home owner=nginx group=nginx mode=766 recurse=yes"
ansible test -m shell -a "df -h"
如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。
本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。