ansible 基本使用

安装ansible

yum install ansble

ansible用ssh管理主机,可以用密钥登陆,也可以用密码登录

密码免输入登录(sshpass需要有这个服务)

添加主机,端口,账号,密码  /etc/ansible/hosts

[cs]
192.168.43.201 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=wangwei
192.168.43.202 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=wangwei

在/etc/ansible/ansible.cfg配置文件中删除 host_key_checking = False 前面的#,因为ansible登录节点主机时会获取key,然后造成报错。

管理节点的命令

ansible -i /etc/ansible/hosts web -m ping     #/etc/ansible/hosts节点管理路径, web组

[root@centos01 ~]# vim /etc/ansible/hosts
............   <!--此处省略部分内容-->
[web]
192.168.100.20
192.168.100.30
[test]
www.benet.com:222                         <!--通过222端口管理设备-->
[mail]
yj1.kgc.cn
yj[2:5].kgc.cn
<!--[2:5]表示2~5之间的所有数字,即表示yj2.kgc.cn、yj3.kgc.cn……的所有主机-->

ansible web -m command -a "systemctl status httpd" --limit "192.168.100.20"  #发送命令给web组192.168.100.20节点主机

ansible web -m command -a "systemctl status httpd" #发送命令给web组的所有主机

 批量复制文件到节点主机用yml,然后用

ansible-playbook copy.yml执行

---

- name: copy file

  hosts: 192.168.43.201 192.168.43.202

  tasks:

  - name: copy ifcfg

    copy:

      src: /etc/docker/daemon.json

      dest: /root

 command不支持管道,这里用shell

ansible cs -m shell -a "ps -ef|grep httpd"

用copy传文件到节点主机

ansible ziji -m copy -a "src=/root/1.txt dest=/tmp owner=hailin group=hailin mode=0755" (src源文件 dest目标位置 owner文件用户 group文件组 mode文件权限)

用stat查看节点主机某文件信息

ansible ziji -m stat -a "path=/tmp/1.txt"

lineinfile用这个模块对文件内容进行操作

ansible centos7 -m lineinfile -a "dest=/etc/selinux/config regexp='SELINUX=enforcing' line='SELINUX=disabled'"  #把SELINUX=enforcing替换成SELINUX=disabled

yum模块

ansible centos7 -m yum -a "name=ntp state=latest" #安装ntp

 file模块

ansible centos7 -m file -a "src=/usr/share/zoneinfo/Asia/Shanghai dest=/etc/localtime state=link"  #创建软链接

非root权限执行

sudo ansible 2 -m copy -a "src=/etc/apt/sources.list dest=/etc/apt/ owner=devteam group=devteam mode=655" -u devteam --sudo

切换其他用户执行命令

sz2 ansible_ssh_user=devteam ansible_become_pass="123456"

原文地址:https://www.cnblogs.com/yunweiweb/p/12812233.html