ansible 超详细讲解[值得收藏]
时间:2023-01-09 17:51:17.634 +0800 CST 浏览:209

ansible安装

yum install python39 -y
pip3.9 install ansible
# 查看版本
ansible --version

ansible配置

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

ansible主机

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

# 生成秘钥
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

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 命令

copy命令

参数选项含义
src 源目录或文件
dest 目标目录或文件
remote_srcTrue、Falsesrc 是远程主机上还是在当前主机上,仅在 mode=preserve 有效
owner 所属用户
group 所属组
mode0655、u=rw、u+rw设置文件权限
backupyes、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"

get_url命令

参数含义
url地址
dest目标文件
mode文件权限
# 下载文件到本地
ansible test -m get_url -a "url=http://xx.xx.xx/ssss.txt dest=/home/xx.txt mode=655"

file命令

# 创建文件
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"

shell命令

ansible test -m shell -a "df -h"


如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。

本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。


来说两句吧