一、环境配置

ansible服务器:192.168.10.217

ansible客户端:192.168.5.201

二、Ansible安装

[root@localhost tmp]# yum install epel-release -y
[root@localhost tmp]# yum install ansible -y

三、配置主机清单

[root@localhost tmp]# cd /etc/ansible/
[root@localhost ansible]# vim hosts
[server_test]
192.168.5.201 ansible_ssh_port=2256 ansible_ssh_user="opadm" ansible_ssh_pass="123"

四、使用Ansible模块

  • ping模块
    注意:第一次要进行ssh手动认证
    [root@localhost ansible]# ansible server_test -m ping 
    192.168.5.201 | SUCCESS => {
      "ansible_facts": {
          "discovered_interpreter_python": "/usr/bin/python"
      }, 
      "changed": false, 
      "ping": "pong"
    }
    
  • raw模块

    执行原始的命令,而不是通过模块子系统。在任何情况下,使用shell或命令模块是合适的。给定原始的参数直接通过配置的远程shell运行。可返回标准输出、错误输出和返回代码。此模块没有更变处理程序支持。这个模块不需要远程系统上的python,就想脚本模块一样,此模块也支持windows目标

    [root@localhost ansible]# ansible server_test -m raw -a '/usr/sbin/ifconfig'
    192.168.5.201 | CHANGED | rc=0 >>
    ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
          inet 192.168.5.201  netmask 255.255.255.0  broadcast 192.168.5.255
          ether 00:0c:29:55:9a:3b  txqueuelen 1000  (Ethernet)
          RX packets 251102  bytes 334591370 (319.0 MiB)
          RX errors 0  dropped 1215  overruns 0  frame 0
          TX packets 88410  bytes 18267042 (17.4 MiB)
          TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
    
    lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
          inet 127.0.0.1  netmask 255.0.0.0
          loop  txqueuelen 1000  (Local Loopback)
          RX packets 0  bytes 0 (0.0 B)
          RX errors 0  dropped 0  overruns 0  frame 0
          TX packets 0  bytes 0 (0.0 B)
          TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
    
    Shared connection to 192.168.5.201 closed.
    
  • yum模块

    这里要使用远程root用户进行安装,而且,而且要把/etc/ansible/hosts的远程用户关闭,ansible默认会读这个文件并且使用配置文件中的用户作为远程用户

    [root@localhost ansible]# ansible server_test -m yum -a 'name=httpd state=latest' --become
    present:默认的,表示为安装 
    lastest: 安装为最新的版本 
    absent:表示删除
    注意:ansible2.8以上版本使用--become进行提权,老版本使用-u root
    
  • copy模块

    拷贝文件至远端服务器

    src 要复制到远程主机的文件在本地的地址

    dest 必选项,要将源文件复制到的远程主机的绝对路径

    directory_mode 递归的设定目录的权限,默认为系统默认权限

    force 如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖。

    [root@localhost ansible]# ansible server_test -m copy -a 'src=/tmp/RackMultipart20191015-29451-vuidu2 dest=/tmp force=yes'
    [root@localhost ansible]# ansible server_test -m copy -a 'src=/tmp/RackMultipart20191015-29451-vuidu2 dest=/opt force=yes' --become       //后面这种做持续集成无疑是很强大的
    
  • file模块

    file模块主要用于远程主机上的文件操作

    [root@localhost ansible]# ansible server_test -m file -a 'src=/tmp/mysql-5.7.17 path=/mnt/mysql-5.7.17 force=yes state=link owner="opadm" group="opadm"' --become
    注意:当第二次执行时如果配置了其他用户也不会生效
    
  • shell模块
    [root@localhost ansible]# ansible server_test -m shell -a 'touch /tmp/abc.txt' --become
    
最后修改日期: 2020年3月19日

作者

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。