Linux系统安装ansible

发布于:2024-04-18 ⋅ 阅读:(29) ⋅ 点赞:(0)

安装ansible

yum install epel-release -y
yum install ansible -y

#检查是否安装成功
ansible --version

检测ansible是否与其他机器连通

#需要先在/etc/ansible/hosts文件中进行配置
#并且需要配置免密登录

#检测自己本机是否正常
ansible localhost -m ping 
#检测与主机host1是否连通
ansible host1 -m ping
#检测与主机host2是否连通,并使用-o简介输出
ansible host2 -m ping -o
#没有配置免密登录可以使用这种方式,手动输入密码
ansible host1 -m ping -o -u root -k

在ansible配置文件/etc/ansible/hosts中配置组(可以配置多个组)

#下面配置表示主机host1和主机host2在同一个组testserver中
[testserver]
host1
host2
[webserver]
host3
#尝试是否连通
ansible testserver -m ping
#如果没有配置免密登录,需要在/etc/ansible/hosts中配置ssh登录的用户和密码
host1 ansible_ssh_user='root' ansible_ssh_pass='123456'
#也可以添加端口
host1 ansible_ssh_user='root' ansible_ssh_pass='123456' ansible_ssh_port='2222'
#使用正则代表host1-host4一共四台主机
host[1:4] ansible_ssh_user='root' ansible_ssh_pass='123456'

#组变量
#在/etc/ansible/hosts文件中定义组
[webserver]
host1
host2
host3
#定义组变量,组变量需要以组名跟上:vars定义   定义的变量对组内所有主机都生效
[webserver:vars]
ansible_ssh_user='root'
ansible_ssh_pass='123456'

使用指定的hosts主机文件

#使用hostlist文件作为ansible主机文件
ansible -i hostlist -m ping 

copy模块

#下面这条模块的作用是将/root/test.txt文件拷贝到testserver组中所有主机的/tmp路径下文件名为123.txt,所有者为root,所属组为root  权限为777
ansible testserver -m copy -a 'src=/root/test.txt dest=/tmp/123.txt owner=root group=root mode=777'
#backup=yes的作用,目标主机上若已存在该文件,且文件内容没有改变,则不会执行拷贝。若文件发生变化,则会将目标主机上的文件进行备份后执行拷贝模块
ansible testserver -m copy -a 'src=/root/test.txt dest=/tmp/123.txt owner=root group=root mode=777 backup=yes'

yum模块

#下面这条模块的作用是为testserver组中所有的主机安装telnet模块
ansible testserver -m yum -a 'name="telnet" state=latest'

service模块

#启动testserver组中所有主机上的httpd服务,并设置为开机启动
ansible testserver -m service -a 'name=httpd state=started enable=yes'
#state还可以设置为stopped restarted   enable还可以设置为no

file模块

#在testserver组中所有主机上的/tmp目录下创建文件test.txt
ansible testserver -m file -a 'path=/tmp/test.txt mode=777 state=touch'
#在testserver组中所有主机上的/tmp目录下创建目录aaa
ansible testserver -m file -a 'path=/tmp/aaa mode=777 state=directory'
#删除文件和目录使用absent
ansible testserver -m file -a 'path=/tmp/aaa mode=777 state=absent'

setup模块

#使用setup可以收集其他主机上的信息
#查看host1主机上的所有信息
ansible host1 -m setup
#查看host1主机上的IP地址,使用filter对信息进行过滤
ansible host1 -m setup -a 'filter=ansible_all_ipv4_addresses'

fetch模块

#从远程主机获取文件到本地
#将host1主机上的/tmp/fetch.txt文件,保存到本地的/root/host1/tmp/fetch.txt路径下
ansible host1 -m fetch -a 'src=/tmp/fetch.txt dest=/root'

cron模块

#给远程主机设置定时任务
#每隔一分钟执行一次/root/check.sh脚本,将执行结果输出到/dev/null
ansible host1 -m cron -a 'name="check environment" minute="*/1" job="/bin/bash /root/check.sh &> /dev/null"'

script模块

#到远程主机上执行脚本
#将ansible机器上当前目录下的script.sh,到testserver组中所有的机器上去执行
ansible testserver -m script -a './script.sh'

shell模块

#到远程主机上执行命令
#查看远程主机的时间
ansible testserver -m shell -a "date"