关于Ansible 是什么这里不做过多描述,感兴趣的朋友可以去官网或者网上进行搜索,这里主要是记录Ansible的执行及使用,废话不多说,开始正题

一,ansible 任务执行模式

Ansible 系统由控制主机对被管节点的操作方式可分为两类,即adhoc和playbook:

ad-hoc模式(点对点模式):

使用单个模块,支持批量执行单条命令。ad-hoc 命令是一种可以快速输入的命令,而且不需要保存起来的命令。就相当于bash中的一句话shell。

playbook模式(剧本模式)

是Ansible主要管理方式,也是Ansible功能强大的关键所在。playbook通过多个task集合完成一类功能,如Web服务的安装部署、数据库服务器的批量备份等。可以简单地把playbook理解为通过组合多条ad-hoc操作的配置文件。

二,ansible 任务执行过程

  1. 加载自己的配置文件,默认/etc/ansible/ansible.cfg;
  2. 查找对应的主机配置文件,找到要执行的主机或者组;
  3. 加载自己对应的模块文件,如 command;
  4. 通过ansible将模块或命令生成对应的临时py文件(python脚本), 并将该文件传输至远程服务器;
  5. 对应执行用户的家目录的.ansible/tmp/XXX/XXX.PY文件;
  6. 给文件 +x 执行权限;
  7. 执行并返回结果;
  8. 删除临时py文件,sleep 0退出;

三,ansible安装:

ansible 安装有两种办法

1,首先,我们需要安装一个python-pip包,安装完成以后,则直接使用pip命令来安装我们的包,具体操作过程如下:

1 yum install python-pip
2 pip install ansible

2,yum 安装是我们很熟悉的安装方式了。我们需要先安装一个epel-release包,然后再安装我们的 ansible 即可。

1 yum install epel-release -y
2 yum install ansible –y

ansible安装目录结构:

安装目录如下(yum安装):

  1.   配置文件目录:/etc/ansible/
  2.   执行文件目录:/usr/bin/
  3.   Lib库依赖目录:/usr/lib/pythonX.X/site-packages/ansible/
  4.   Help文档目录:/usr/share/doc/ansible-X.X.X/
  5.   Man文档目录:/usr/share/man/man1/

四,ansible与我们其他的服务在这一点上有很大不同,这里的配置文件查找是从多个地方找的,顺序如下:

  1. 检查环境变量ANSIBLE_CONFIG指向的路径文件(export ANSIBLE_CONFIG=/etc/ansible.cfg);
  2. ~/.ansible.cfg,检查当前目录下的ansible.cfg配置文件;
  3. /etc/ansible.cfg检查etc目录的配置文件。

1,ansible 的配置文件为/etc/ansible/ansible.cfg,ansible 有许多参数,下面我们列出一些常见的参数:

inventory = /etc/ansible/hosts        #这个参数表示资源清单inventory文件的位置
library = /usr/share/ansible        #指向存放Ansible模块的目录,支持多个目录方式,只要用冒号(:)隔开就可以
forks = 5        #并发连接数,默认为5
sudo_user = root        #设置默认执行命令的用户
remote_port = 22        #指定连接被管节点的管理端口,默认为22端口,建议修改,能够更加安全
host_key_checking = False        #设置是否检查SSH主机的密钥,值为True/False。关闭后第一次连接不会提示配置实例
timeout = 60        #设置SSH连接的超时时间,单位为秒
log_path = /var/log/ansible.log        #指定一个存储ansible日志的文件(默认不记录日志)

2,ansible 主机清单:

在配置文件中,我们提到了资源清单,这个清单就是我们的主机清单,里面保存的是一些 ansible 需要连接管理的主机列表。我们可以来看看他的定义方式:

1、 直接指明主机地址或主机名:
    ## green.example.com#
    # blue.example.com#
    # 192.168.100.1
    # 192.168.100.10
2、 定义一个主机组[组名]把地址或主机名加进去
    [mysql_test]
    192.168.253.159
    192.168.253.160
    192.168.253.153

需要注意的是,这里的组成员可以使用通配符来匹配,这样对于一些标准化的管理来说就很轻松方便了。
我们可以根据实际情况来配置我们的主机列表,具体操作如下:

 

 

 看看我的web组里加了两个主机

五,ansible 常用命令

1 /usr/bin/ansible  Ansibe AD-Hoc 临时命令执行工具,常用于临时命令的执行
2 /usr/bin/ansible-doc   Ansible 模块功能查看工具
3 /usr/bin/ansible-galaxy  下载/上传优秀代码或Roles模块 的官网平台,基于网络的
4 /usr/bin/ansible-playbook  Ansible 定制自动化的任务集编排工具
5 /usr/bin/ansible-pull  Ansible远程执行命令的工具,拉取配置而非推送配置(使用较少,海量机器时使用,对运维的架构能力要求较高)
6 /usr/bin/ansible-vault  Ansible 文件加密工具
7 /usr/bin/ansible-console  Ansible基于Linux Consoble界面可与用户交互的命令执行工具

其中,我们比较常用的是/usr/bin/ansible和/usr/bin/ansible-playbook。

这里我们先从常用的这两个命令开始讲解其使用方式,后面我们再来了解其他命令的使用方式

在开始试验前,我们先来做些准备工作

配置控制主机到被管节点的免密登录

通过下面的命令完成:

1 ssh-keygen
2 ssh-copy-id root@192.168.56.117
3 ssh-copy-id root@192.168.56.118

完成后可以验证,通过ssh登录被管节点,是否还要输入密码

1,/usr/bin/ansible 命令的使用:

ansible命令格式:

ansible <host-pattern> [-f forks] [-m module_name] [-a args]

ansible命令参数详解:

-a MODULE_ARGS   #模块的参数,如果执行默认COMMAND的模块,即是命令参数,如: “date”,“pwd”等等
-k,--ask-pass #ask for SSH password。登录密码,提示输入SSH密码而不是假设基于密钥的验证
--ask-su-pass #ask for su password。su切换密码
-K,--ask-sudo-pass #ask for sudo password。提示密码使用sudo,sudo表示提权操作
--ask-vault-pass #ask for vault password。假设我们设定了加密的密码,则用该选项进行访问
-B SECONDS #后台运行超时时间
-C #模拟运行环境并进行预运行,可以进行查错测试
-c CONNECTION #连接类型使用
-f FORKS #并行任务数,默认为5
-i INVENTORY #指定主机清单的路径,默认为/etc/ansible/hosts
--list-hosts #查看有哪些主机组
-m MODULE_NAME #执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
-o #压缩输出,尝试将所有结果在一行输出,一般针对收集工具使用
-S #用 su 命令
-R SU_USER #指定 su 的用户,默认为 root 用户
-s #用 sudo 命令
-U SUDO_USER #指定 sudo 到哪个用户,默认为 root 用户
-T TIMEOUT #指定 ssh 默认超时时间,默认为10s,也可在配置文件中修改
-u REMOTE_USER #远程用户,默认为 root 用户
-v #查看详细信息,同时支持-vvv,-vvvv可查看更详细信息

ansible 命令常用模块:

1,主机连通性测试:

我们使用ansible web -m ping命令来进行主机连通性测试,效果如下:

[root@localhost ~]# ansible web -m ping
192.168.56.117 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.56.118 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

2,command 模块:

这个模块可以直接在远程主机上执行命令,并将结果返回本主机。

[root@localhost ~]# ansible web -m command -a "netstat -tnlp"
192.168.56.117 | CHANGED | rc=0 >>
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      880/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1108/master         
tcp6       0      0 :::22                   :::*                    LISTEN      880/sshd            
tcp6       0      0 ::1:25                  :::*                    LISTEN      1108/master         
192.168.56.118 | CHANGED | rc=0 >>
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      880/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1106/master         
tcp6       0      0 :::22                   :::*                    LISTEN      880/sshd            
tcp6       0      0 ::1:25                  :::*                    LISTEN      1106/master         
[root@localhost ~]# 

命令模块接受命令名称,后面是空格分隔的列表参数。给定的命令将在所有选定的节点上执行。它不会通过shell进行处理,比如$HOME和操作如"<",">","|",";","&" 工作(需要使用(shell)模块实现这些功能)。注意,该命令不支持| 管道命令。

下面来看一看该模块下常用的几个命令:

chdir       # 在执行命令之前,先切换到该目录

executable             # 切换shell来执行命令,需要使用命令的绝对路径

free_form            # 要执行的Linux指令,一般使用Ansible的-a参数代替。

creates                # 一个文件名,当这个文件存在,则该命令不执行,可以用来做判断

removes                # 一个文件名,这个文件不存在,则该命令不执行

 

chdir 命令:

[root@localhost ~]# ansible web -m command -a "chdir=/opt/ ls" #先切换到/opt/ 目录,再执行“ls”命令
192.168.56.118 | CHANGED | rc=0 >>
containerd
192.168.56.117 | CHANGED | rc=0 >>
containerd
[root@localhost ~]# 

creates 命令:

[root@localhost ansibletest]# ansible web -m command -a "creates=/ansibletest/hello.txt ls"  #如果/ansibletest/hello.txt文件存在,则不执行ls命令
192.168.56.118 | SUCCESS | rc=0 >>
skipped, since /ansibletest/hello.txt exists
192.168.56.117 | SUCCESS | rc=0 >>
skipped, since /ansibletest/hello.txt exists

removes  命令:

[root@localhost ansibletest]# ansible web -m command -a "removes=/ansibletest/hello.txt ls"  #如果/ansibletest/hello.txt文件存在,则执行ls命令
192.168.56.118 | CHANGED | rc=0 >>
anaconda-ks.cfg
192.168.56.117 | CHANGED | rc=0 >>
anaconda-ks.cfg

3,shell模块:

shell模块可以在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等。

[root@localhost ansibletest]# ansible web -m shell -a "ps aux | grep ssh"
192.168.56.118 | CHANGED | rc=0 >>
root       880  0.0  0.2 106000  4116 ?        Ss   13:19   0:00 /usr/sbin/sshd -D
root      6633  0.0  0.2 145704  5204 ?        Ss   15:03   0:00 sshd: root@pts/0
root     10497 31.0  0.3 146020  5656 ?        Ss   16:09   0:00 sshd: root@pts/1
root     10557  0.0  0.0 113128  1216 pts/1    S+   16:09   0:00 /bin/sh -c ps aux | grep ssh
root     10559  0.0  0.0 112680   960 pts/1    S+   16:09   0:00 grep ssh
192.168.56.117 | CHANGED | rc=0 >>
root       880  0.0  0.2 106000  4116 ?        Ss   13:19   0:00 /usr/sbin/sshd -D
root      2009  0.0  0.2 145704  5200 ?        Ss   13:49   0:00 sshd: root@pts/0
root      6564  0.0  0.2 145704  5200 ?        Ss   15:02   0:00 sshd: root@pts/1
root     10478 26.0  0.2 146020  5640 ?        Ss   16:09   0:00 sshd: root@pts/2
root     10538  0.0  0.0 113128  1216 pts/2    S+   16:09   0:00 /bin/sh -c ps aux | grep ssh
root     10540  0.0  0.0 112680   964 pts/2    S+   16:09   0:00 grep ssh

只要是我们的shell命令,都可以通过这个模块在远程主机上运行,这里就不一一举例了。

4,copy模块:

这个模块用于将文件复制到远程主机,同时支持给定内容生成文件和修改权限等。

其相关选项如下:

src         #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"

content   #用于替换"src",可以直接指定文件的值

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

backup   #当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息

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

force    #当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制。默认为"yes"

 

others    #所有的 file 模块中的选项可以在这里使用

案例1:

 

[root@localhost ansibletest]# ansible web -m copy -a "src=./copytest.txt dest=/ansibletest/" #将控制主机下的copytest.txt文件复制到被管主机的/ansibletest/目录下
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/ansibletest/copytest.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608539090.3-3424-145099408001148/source", 
    "state": "file", 
    "uid": 0
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/ansibletest/copytest.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608539090.34-3426-242077499013630/source", 
    "state": "file", 
    "uid": 0
}

 

查看结果:

[root@localhost ansibletest]# ansible web -m shell -a "ls /ansibletest/"
192.168.56.117 | CHANGED | rc=0 >>
ansibletest
copytest.txt
hello.txt
192.168.56.118 | CHANGED | rc=0 >>
ansibletest
copytest.txt
hello.txt

案例2:

[root@localhost ansibletest]# ansible web -m copy -a "content='i am a content test' dest=/ansibletest/content mode=666"  #将content中的内容插入到被管主机的/ansibletest/content文件中,并将文件的权限改成666
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "d81983bbe1ec6669c23fe3172ad45495a4c8e3c5", 
    "dest": "/ansibletest/content", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "9459a71ba8b522d2343de1e34e3b8c6b", 
    "mode": "0666", 
    "owner": "root", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 19, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608539544.38-3573-196692038423912/source", 
    "state": "file", 
    "uid": 0
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "d81983bbe1ec6669c23fe3172ad45495a4c8e3c5", 
    "dest": "/ansibletest/content", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "9459a71ba8b522d2343de1e34e3b8c6b", 
    "mode": "0666", 
    "owner": "root", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 19, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608539544.46-3575-139684389964663/source", 
    "state": "file", 
    "uid": 0
}

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "ls -l /ansibletest/"
192.168.56.117 | CHANGED | rc=0 >>
总用量 8
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt
192.168.56.118 | CHANGED | rc=0 >>
总用量 8
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt
[root@localhost ansibletest]# ansible web -m shell -a "cat /ansibletest/content"
192.168.56.117 | CHANGED | rc=0 >>
i am a content test
192.168.56.118 | CHANGED | rc=0 >>
i am a content test

案例3:

[root@localhost ansibletest]# ansible web -m copy -a "content='i am modified content' backup=yes dest=/ansibletest/content mode=655" #将新的内容写入content的文件并备份老的文件,并修改文件权限为655
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/ansibletest/content.12632.2020-12-21@16:36:55~", 
    "changed": true, 
    "checksum": "192de556c778efbde958d0ca5dc9a2548fd7b6aa", 
    "dest": "/ansibletest/content", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4023705d063abc087548ec95dd9102fa", 
    "mode": "0655", 
    "owner": "root", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 21, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608539968.18-3775-172506208719962/source", 
    "state": "file", 
    "uid": 0
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/ansibletest/content.12632.2020-12-21@16:37:04~", 
    "changed": true, 
    "checksum": "192de556c778efbde958d0ca5dc9a2548fd7b6aa", 
    "dest": "/ansibletest/content", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4023705d063abc087548ec95dd9102fa", 
    "mode": "0655", 
    "owner": "root", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 21, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608539968.2-3777-255021848406356/source", 
    "state": "file", 
    "uid": 0
}

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "cat /ansibletest/content"
192.168.56.117 | CHANGED | rc=0 >>
i am modified content
192.168.56.118 | CHANGED | rc=0 >>
i am modified content
[root@localhost ansibletest]# ansible web -m shell -a "ls -l /ansibletest/"
192.168.56.117 | CHANGED | rc=0 >>
总用量 12
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-r-xr-x. 1 root root 21 12月 21 16:36 content
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content.12632.2020-12-21@16:36:55~
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt
192.168.56.118 | CHANGED | rc=0 >>
总用量 12
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-r-xr-x. 1 root root 21 12月 21 16:37 content
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content.12632.2020-12-21@16:37:04~
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt

5,file 模块:

该模块主要用于设置文件的属性,比如创建文件、创建链接文件、删除文件等。

下面是一些常见的命令:

 

force  #需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group  #定义文件/目录的属组。后面可以加上mode:定义文件/目录的权限
owner  #定义文件/目录的属主。后面必须跟上path:定义文件/目录的路径
recurse  #递归设置文件的属性,只对目录有效,后面跟上src:被链接的源文件路径,只应用于state=link的情况
dest  #被链接到的路径,只应用于state=link的情况
state  #状态,有以下选项:

      directory:如果目录不存在,就创建目录
      file:即使文件不存在,也不会被创建
      link:创建软链接
      hard:创建硬链接
      touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
      absent:删除目录、文件或者取消链接文件

案例1:

[root@localhost ansibletest]# ansible web -m file -a "path=/ansibletest/dirtest state=directory"  #按照path给定的路径创建目录
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/ansibletest/dirtest", 
    "secontext": "unconfined_u:object_r:default_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/ansibletest/dirtest", 
    "secontext": "unconfined_u:object_r:default_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "ls -l /ansibletest/"
192.168.56.117 | CHANGED | rc=0 >>
总用量 12
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-r-xr-x. 1 root root 21 12月 21 16:36 content
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content.12632.2020-12-21@16:36:55~
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
drwxr-xr-x. 2 root root  6 12月 21 17:04 dirtest
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt
192.168.56.118 | CHANGED | rc=0 >>
总用量 12
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-r-xr-x. 1 root root 21 12月 21 16:37 content
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content.12632.2020-12-21@16:37:04~
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
drwxr-xr-x. 2 root root  6 12月 21 17:04 dirtest
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt

案例2:

[root@localhost ansibletest]# ansible web -m file -a "path=/ansibletest/hellolink.txt src=/ansibletest/hello.txt state=link" #创建hello.txt的软连接文件hellolink.txt
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/ansibletest/hellolink.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:default_t:s0", 
    "size": 22, 
    "src": "/ansibletest/hello.txt", 
    "state": "link", 
    "uid": 0
}
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/ansibletest/hellolink.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:default_t:s0", 
    "size": 22, 
    "src": "/ansibletest/hello.txt", 
    "state": "link", 
    "uid": 0
}

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "ls -l /ansibletest/"
192.168.56.117 | CHANGED | rc=0 >>
总用量 12
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-r-xr-x. 1 root root 21 12月 21 16:36 content
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content.12632.2020-12-21@16:36:55~
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
drwxr-xr-x. 2 root root  6 12月 21 17:04 dirtest
lrwxrwxrwx. 1 root root 22 12月 21 17:10 hellolink.txt -> /ansibletest/hello.txt
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt
192.168.56.118 | CHANGED | rc=0 >>
总用量 12
drwxr-xr-x. 2 root root 23 12月 21 13:48 ansibletest
-rw-r-xr-x. 1 root root 21 12月 21 16:37 content
-rw-rw-rw-. 1 root root 19 12月 21 16:29 content.12632.2020-12-21@16:37:04~
-rw-r--r--. 1 root root  0 12月 21 16:22 copytest.txt
drwxr-xr-x. 2 root root  6 12月 21 17:04 dirtest
lrwxrwxrwx. 1 root root 22 12月 21 17:10 hellolink.txt -> /ansibletest/hello.txt
-rw-r--r--. 1 root root 10 12月 21 13:57 hello.txt

案例3:

[root@localhost ansibletest]# ansible web -m file -a "path=/ansibletest/dirtest state=absent"  #删除文件/目录 删除给定path的文件/目录
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/ansibletest/dirtest", 
    "state": "absent"
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/ansibletest/dirtest", 
    "state": "absent"
}

6,fetch模块:

该模块用于从远程某主机获取(复制)文件到本地。

dest:用来存放文件的目录
src:在远程拉取的文件,并且必须是一个file,不能是目录

案例1:

[root@localhost ansibletest]# ansible web -m fetch -a "src=/ansibletest/content dest=/ansibletest/"
192.168.56.117 | CHANGED => {
    "changed": true, 
    "checksum": "192de556c778efbde958d0ca5dc9a2548fd7b6aa", 
    "dest": "/ansibletest/192.168.56.117/ansibletest/content", 
    "md5sum": "4023705d063abc087548ec95dd9102fa", 
    "remote_checksum": "192de556c778efbde958d0ca5dc9a2548fd7b6aa", 
    "remote_md5sum": null
}
192.168.56.118 | CHANGED => {
    "changed": true, 
    "checksum": "192de556c778efbde958d0ca5dc9a2548fd7b6aa", 
    "dest": "/ansibletest/192.168.56.118/ansibletest/content", 
    "md5sum": "4023705d063abc087548ec95dd9102fa", 
    "remote_checksum": "192de556c778efbde958d0ca5dc9a2548fd7b6aa", 
    "remote_md5sum": null
}
[root@localhost ansibletest]# ll
总用量 0
drwxr-xr-x. 3 root root 25 12月 21 17:23 192.168.56.117
drwxr-xr-x. 3 root root 25 12月 21 17:23 192.168.56.118
-rw-r--r--. 1 root root  0 12月 21 16:23 copytest.txt
-rw-r--r--. 1 root root  0 12月 21 13:47 hello.txt
[root@localhost ansibletest]# tree
.
├── 192.168.56.117
│   └── ansibletest
│       └── content
├── 192.168.56.118
│   └── ansibletest
│       └── content
├── copytest.txt
└── hello.txt

4 directories, 4 files
[root@localhost ansibletest]# 

7,cron模块:

该模块适用于管理cron计划任务的。
其使用的语法跟我们的crontab文件中的语法一致,同时,可以指定以下选项:

day= #日应该运行的工作( 1-31, *, */2, )
hour= # 小时 ( 0-23, *, */2, )
minute= #分钟( 0-59, *, */2, )
month= # 月( 1-12, *, /2, )
weekday= # 周 ( 0-6 for Sunday-Saturday,, )
job= #指明运行的命令是什么
name= #定时任务描述
reboot # 任务在重启时运行,不建议使用,建议使用special_time
special_time #特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
state #指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务
user # 以哪个用户的身份执行

案例1:

[root@localhost ansibletest]# ansible web -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 172.17.0.1 &> /dev/null"' #每五分钟同步一下系统时间
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntp update every 5 min"
    ]
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntp update every 5 min"
    ]
}

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "crontab -l"
192.168.56.117 | CHANGED | rc=0 >>
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 172.17.0.1 &> /dev/null
192.168.56.118 | CHANGED | rc=0 >>
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 172.17.0.1 &> /dev/null

案例2:

刚才我们添加了一个定时任务,如果这是我们发现定时任务有问题我们想将它删除应该怎么操作呢

[root@localhost ansibletest]# ansible web -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 172.17.0.1 &> /dev/null" state=absent'  #删除定时任务比添加多了一个参数state=absent
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[root@localhost ansibletest]# ansible web -m shell -a "crontab -l"
192.168.56.117 | CHANGED | rc=0 >>

192.168.56.118 | CHANGED | rc=0 >>

8,yum模块:

顾名思义,该模块主要用于软件的安装。
其选项如下:

name=  #所安装的包的名称
state=  #present--->安装, latest--->安装最新的, absent---> 卸载软件。
update_cache  #强制更新yum的缓存
conf_file  #指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
disable_pgp_check  #是否禁止GPG checking,只用于presentor latest。
disablerepo  #临时禁止使用yum库。 只用于安装或更新时。
enablerepo  #临时使用的yum库。只用于安装或更新时。

案例1:

[root@localhost ansibletest]# ansible web -m yum -a "name=htop"  #安装htop软件包,
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "htop"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.tuna.tsinghua.edu.cn\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package htop.x86_64 0:2.2.0-3.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n htop            x86_64            2.2.0-3.el7            epel            103 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 103 k\nInstalled size: 218 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : htop-2.2.0-3.el7.x86_64                                      1/1 \n  Verifying  : htop-2.2.0-3.el7.x86_64                                      1/1 \n\nInstalled:\n  htop.x86_64 0:2.2.0-3.el7                                                     \n\nComplete!\n"
    ]
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "htop"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: ftp.iij.ad.jp\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package htop.x86_64 0:2.2.0-3.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n htop            x86_64            2.2.0-3.el7            epel            103 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 103 k\nInstalled size: 218 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : htop-2.2.0-3.el7.x86_64                                      1/1 \n  Verifying  : htop-2.2.0-3.el7.x86_64                                      1/1 \n\nInstalled:\n  htop.x86_64 0:2.2.0-3.el7                                                     \n\nComplete!\n"
    ]
}

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "yum list installed | grep htop"
[WARNING]: Consider using the yum module rather than running 'yum'.  If you need to use command because yum is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.56.117 | CHANGED | rc=0 >>
htop.x86_64                        2.2.0-3.el7                    @epel         
192.168.56.118 | CHANGED | rc=0 >>
htop.x86_64                        2.2.0-3.el7                    @epel

9,service模块

该模块用于服务程序的管理。
其主要选项如下:

arguments #命令行提供额外的参数
enabled #设置开机启动。
name= #服务名称
runlevel #开机启动的级别,一般不用指定。
sleep #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。)
state #有四种状态,分别为:started--->启动服务, stopped--->停止服务, restarted--->重启服务, reloaded--->重载配置

案例1:

ansible web -m service -a "name=httpd state=started enabled=true" #启动httpd服务,并将其设为开机自启,关闭服务的话可以将state=stopped

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "systemctl status httpd"
192.168.56.118 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since 一 2020-12-21 17:54:11 CST; 1min 18s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 18045 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─18045 /usr/sbin/httpd -DFOREGROUND
           ├─18046 /usr/sbin/httpd -DFOREGROUND
           ├─18047 /usr/sbin/httpd -DFOREGROUND
           ├─18048 /usr/sbin/httpd -DFOREGROUND
           ├─18049 /usr/sbin/httpd -DFOREGROUND
           └─18050 /usr/sbin/httpd -DFOREGROUND

12月 21 17:54:11 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
12月 21 17:54:11 localhost.localdomain httpd[18045]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain. Set the 'ServerName' directive globally to suppress this message
12月 21 17:54:11 localhost.localdomain systemd[1]: Started The Apache HTTP Server.
192.168.56.117 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since 一 2020-12-21 17:54:02 CST; 1min 18s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 18074 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─18074 /usr/sbin/httpd -DFOREGROUND
           ├─18075 /usr/sbin/httpd -DFOREGROUND
           ├─18076 /usr/sbin/httpd -DFOREGROUND
           ├─18077 /usr/sbin/httpd -DFOREGROUND
           ├─18078 /usr/sbin/httpd -DFOREGROUND
           └─18079 /usr/sbin/httpd -DFOREGROUND

12月 21 17:54:02 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
12月 21 17:54:02 localhost.localdomain httpd[18074]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain. Set the 'ServerName' directive globally to suppress this message
12月 21 17:54:02 localhost.localdomain systemd[1]: Started The Apache HTTP Server.
[root@localhost ansibletest]# ansible web -m shell -a "systemctl list-unit-files | grep httpd"
192.168.56.117 | CHANGED | rc=0 >>
httpd.service                                 enabled 
192.168.56.118 | CHANGED | rc=0 >>
httpd.service                                 enabled 

10,user模块:

该模块主要是用来管理用户账号。
其主要选项如下:

comment  # 用户的描述信息
createhome  # 是否创建家目录
force  # 在使用state=absent时, 行为与userdel –force一致.
group  # 指定基本组
groups  # 指定附加组,如果指定为(groups=)表示删除所有组
home  # 指定用户家目录
move_home  # 如果设置为home=时, 试图将用户主目录移动到指定的目录
name  # 指定用户名
non_unique  # 该选项允许改变非唯一的用户ID值
password  # 指定用户密码
remove  # 在使用state=absent时, 行为是与userdel –remove一致
shell  # 指定默认shell
state  # 设置帐号状态,不指定为创建,指定值为absent表示删除
system  # 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
uid  # 指定用户的uid

案例1:添加一个用户并制定UID

[root@localhost ansibletest]# ansible web -m user -a 'name=keer uid=11111' #添加keer用户并指定其UID,删除的话加state=absent
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 11111, 
    "home": "/home/keer", 
    "name": "keer", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 11111
}
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 11111, 
    "home": "/home/keer", 
    "name": "keer", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 11111
}

运行结果:

[root@localhost ansibletest]# ansible web -m shell -a "cat /etc/passwd | grep keer"
192.168.56.118 | CHANGED | rc=0 >>
keer:x:11111:11111::/home/keer:/bin/bash
192.168.56.117 | CHANGED | rc=0 >>
keer:x:11111:11111::/home/keer:/bin/bash

11,group模块:

该模块主要用于添加或删除组。
常用的选项如下:

gid=  #设置组的GID号
name=  #指定组的名称
state=  #指定组的状态,默认为创建,设置值为absent为删除
system=  #设置值为yes,表示创建为系统组

案例1,添加组

[root@localhost ansibletest]# ansible web -m group -a 'name=sanguo gid=12222' 添加组并指定其gid 删除的话加参数state=absent
192.168.56.117 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 12222, 
    "name": "sanguo", 
    "state": "present", 
    "system": false
}
192.168.56.118 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 12222, 
    "name": "sanguo", 
    "state": "present", 
    "system": false
}

12,script模块:

该模块用于将本机的脚本在被管理端的机器上运行。
该模块直接指定脚本的路径即可,我们通过例子来看一看到底如何使用的:
首先,我们写一个脚本,并给其加上执行权限:

案例1,在被管节点执行管理主机的脚本

在管理主机编写脚本test.sh

[root@localhost ansibletest]# cat test.sh 
#!/bin/bash

echo "hello world"

运行命令在被管主机执行该脚本:

[root@localhost ansibletest]# ansible web -m script -a "./test.sh"
192.168.56.117 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.56.117 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.56.117 closed."
    ], 
    "stdout": "hello world\r\n", 
    "stdout_lines": [
        "hello world"
    ]
}
192.168.56.118 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.56.118 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.56.118 closed."
    ], 
    "stdout": "hello world\r\n", 
    "stdout_lines": [
        "hello world"
    ]
}

13,setup模块

该模块主要用于收集信息,是通过调用facts组件来实现的。
facts组件是Ansible用于采集被管机器设备信息的一个功能,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。整个facts信息被包装在一个JSON格式的数据结构中,ansible_facts是最上层的值。
facts就是变量,内建变量 。每个主机的各种信息,cpu颗数、内存大小等。会存在facts中的某个变量中。调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不同的操作。如redhat系列用yum安装,而debian系列用apt来安装软件。

案例1,查看被管节点内存信息

[root@localhost ansibletest]# ansible web -m setup -a 'filter="*mem*"'
192.168.56.117 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1298, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1584, 
                "used": 255
            }, 
            "real": {
                "free": 1298, 
                "total": 1839, 
                "used": 541
            }, 
            "swap": {
                "cached": 0, 
                "free": 1906, 
                "total": 1906, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1839, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
192.168.56.118 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1285, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1579, 
                "used": 260
            }, 
            "real": {
                "free": 1285, 
                "total": 1839, 
                "used": 554
            }, 
            "swap": {
                "cached": 0, 
                "free": 1906, 
                "total": 1906, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1839, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

来通过命令校验一下获取的信息是否正确:

[root@localhost ansibletest]# ansible web -m shell -a "free -m"
192.168.56.117 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           1839         170        1301           8         367        1476
Swap:          1906           0        1906
192.168.56.118 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           1839         175        1288           8         376        1470
Swap:          1906           0        1906

 

案例2,保存查询到的信息

我们的setup模块还有一个很好用的功能就是可以保存我们所筛选的信息至我们的主机上,同时,文件名为我们被管制的主机的IP,这样方便我们知道是哪台机器出的问题。

[root@localhost ansibletest]# ansible web -m setup -a 'filter="*mem*"' --tree ./facts
192.168.56.117 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1298, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1585, 
                "used": 254
            }, 
            "real": {
                "free": 1298, 
                "total": 1839, 
                "used": 541
            }, 
            "swap": {
                "cached": 0, 
                "free": 1906, 
                "total": 1906, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1839, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
192.168.56.118 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1285, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1579, 
                "used": 260
            }, 
            "real": {
                "free": 1285, 
                "total": 1839, 
                "used": 554
            }, 
            "swap": {
                "cached": 0, 
                "free": 1906, 
                "total": 1906, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1839, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

 

[root@localhost facts]# ll
总用量 8
-rw-r--r--. 1 root root 324 12月 21 18:29 192.168.56.117
-rw-r--r--. 1 root root 324 12月 21 18:29 192.168.56.118
[root@localhost facts]# pwd
/ansibletest/facts
[root@localhost facts]# cat 192.168.56.118
{"ansible_facts": {"ansible_memfree_mb": 1285, "ansible_memory_mb": {"nocache": {"free": 1579, "used": 260}, "real": {"free": 1285, "total": 1839, "used": 554}, "swap": {"cached": 0, "free": 1906, "total": 1906, "used": 0}}, "ansible_memtotal_mb": 1839, "discovered_interpreter_python": "/usr/bin/python"}, "changed": false}

 

以上就是ansible ad-hoc模式的所有内容,下篇文章我们会注重讲解 ansible playbook相关知识

 

posted on 2020-12-24 13:21  EZgod  阅读(831)  评论(0编辑  收藏  举报