Ansible常见模块

ansible中常用的模块详解:

file模块

ansible内置的可以查看模块用法的命令如下:

[root@ansible ~]# ansible-doc -s file
- name: Manage files and file properties
  file:
      access_time:           # This parameter indicates the time the file's access time should be set to. Should be `preserve' when no
                               modification is required, `YYYYMMDDHHMM.SS' when using default time format, or
                               `now'. Default is `None' meaning that `preserve' is the default for
                               `state=[file,directory,link,hard]' and `now' is default for `state=touch'.
      access_time_format:    # When used with `access_time', indicates the time format that must be used. Based on default Python format (see
                               time.strftime doc).
      attributes:            # The attributes the resulting file or directory should have. To get supported flags look at the man page for
                               `chattr' on the target system. This string should contain the attributes in the same
                               order as the one displayed by `lsattr'. The `=' operator is assumed as default,
                               otherwise `+' or `-' operators need to be included in the string.
      follow:                # This flag indicates that filesystem links, if they exist, should be followed. Previous to Ansible 2.5, this was
                               `no' by default.
      force:                 # Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the
                               destination exists and is a file (so, we need to unlink the `path' file and create
                               symlink to the `src' file in place of it).
      group:                 # Name of the group that should own the file/directory, as would be fed to `chown'.
      mode:                  # The permissions the resulting file or directory should have. For those used to `/usr/bin/chmod' remember that modes
                               are actually octal numbers. You must either add a leading zero so that Ansible's
                               YAML parser knows it is an octal number (like `0644' or `01777') or quote it (like
                               `'644'' or `'1777'') so Ansible receives a string and can do its own conversion from
                               string into number. Giving Ansible a number without following one of these rules
                               will end up with a decimal number which will have unexpected results. As of Ansible
                               1.8, the mode may be specified as a symbolic mode (for example, `u+rwx' or
                               `u=rw,g=r,o=r'). As of Ansible 2.6, the mode may also be the special string
                               `preserve'. When set to `preserve' the file will be given the same permissions as
                               the source file.
      modification_time:     # This parameter indicates the time the file's modification time should be set to. Should be `preserve' when no
                               modification is required, `YYYYMMDDHHMM.SS' when using default time format, or
                               `now'. Default is None meaning that `preserve' is the default for
                               `state=[file,directory,link,hard]' and `now' is default for `state=touch'.
      modification_time_format:   # When used with `modification_time', indicates the time format that must be used. Based on default Python format
                               (see time.strftime doc).
      owner:                 # Name of the user that should own the file/directory, as would be fed to `chown'.
      path:                  # (required) Path to the file being managed.
      recurse:               # Recursively set the specified file attributes on directory contents. This applies only when `state' is set to
                               `directory'.
      selevel:               # The level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. When set
                               to `_default', it will use the `level' portion of the policy if available.
      serole:                # The role part of the SELinux file context. When set to `_default', it will use the `role' portion of the policy if
                               available.
      setype:                # The type part of the SELinux file context. When set to `_default', it will use the `type' portion of the policy if
                               available.
      seuser:                # The user part of the SELinux file context. By default it uses the `system' policy, where applicable. When set to
                               `_default', it will use the `user' portion of the policy if available.
      src:                   # Path of the file to link to. This applies only to `state=link' and `state=hard'. For `state=link', this will also
                               accept a non-existing path. Relative paths are relative to the file being created
                               (`path') which is how the Unix command `ln -s SRC DEST' treats relative paths.
      state:                 # If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a
                               directory, if `diff' is declared, you will see the files and folders deleted listed
                               under `path_contents'. Note that `absent' will not cause `file' to fail if the
                               `path' does not exist as the state did not change. If `directory', all intermediate
                               subdirectories will be created if they do not exist. Since Ansible 1.7 they will be
                               created with the supplied permissions. If `file', without any other options this
                               works mostly as a 'stat' and will return the current state of `path'. Even with
                               other options (i.e `mode'), the file will be modified but will NOT be created if it
                               does not exist; see the `touch' value or the [copy] or [template] module if you want
                               that behavior. If `hard', the hard link will be created or changed. If `link', the
                               symbolic link will be created or changed. If `touch' (new in 1.4), an empty file
                               will be created if the `path' does not exist, while an existing file or directory
                               will receive updated file access and modification times (similar to the way `touch'
                               works from the command line).
      unsafe_writes:         # Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file. By
                               default this module uses atomic operations to prevent data corruption or
                               inconsistent reads from the target files, but sometimes systems are configured or
                               just broken in ways that prevent this. One example is docker mounted files, which
                               cannot be updated atomically from inside the container and can only be written in an
                               unsafe manner. This option allows Ansible to fall back to unsafe methods of updating
                               files when atomic operations fail (however, it doesn't force Ansible to perform
                               unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead
                               to data corruption.

file模块用来设置文件属性,并且创建或者删除目录,创建连接。

相关选项如下:
force:需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group:定义文件/目录的属组
mode:定义文件/目录的权限
owner:定义文件/目录的属主
path:必选项,定义文件/目录的路径
recurse:递归设置文件的属性,只对目录有效
src:被链接的源文件路径,只应用于state=link的情况
dest:被链接到的路径,只应用于state=link的情况
state:
       directory:如果目录不存在,就创建目录
       file:即使文件不存在,也不会被创建
       link:创建软链接
       hard:创建硬链接
       touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
       absent:删除目录、文件或者取消链接文件

利用file模块创建一个文件:

[root@ansible ~]#  ansible k8sservers -m file -a "path=/tmp/test state=touch owner=root group=root"
192.168.1.114 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/tmp/test",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}
192.168.1.111 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/tmp/test",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}
192.168.1.113 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/tmp/test",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}
[root@ansible ~]#

image-20200730094916369

copy模块

主要的作用是复制文件到远程主机:

相关选项如下:
backup:在覆盖之前,将源文件备份,备份文件包含时间信息。有两个选项:yes|no
content:用于替代“src”,可以直接设定指定文件的值
dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
directory_mode:递归设定目录的权限,默认为系统默认权限
force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
others:所有的file模块里的选项都可以在这里使用
src:被复制到远程主机的本地文件,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用“/”来结尾,则只复制目录里的内容,如果没有使用“/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync

示例如下:

[root@ansible ~]# ansible test -m copy -a "src=/etc/sysconfig dest=/test owner=root mode=600"
192.168.1.106 | CHANGED => {
    "changed": true,
    "dest": "/test/",
    "src": "/etc/sysconfig"
}
[root@ansible ~]# ansible test -a "ls -l /test/"
192.168.1.106 | CHANGED | rc=0 >>
总用量 4
drwxr-xr-x. 5 root root 4096 7月  29 22:09 sysconfig
[root@ansible ~]#
[root@ansible ~]# ansible k8sservers -m copy -a "content='test1\ntest2' dest=/tmp/test.txt"                                                        192.168.1.111 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "efc492233d97a1898c8f797904442e6b26758276",
    "dest": "/tmp/test.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "5bdd30886cf6f00a7286ac6e7322a46e",
    "mode": "0644",
    "owner": "root",
    "size": 11,
    "src": "/root/.ansible/tmp/ansible-tmp-1596074441.523403-76201-249571230429455/source",
    "state": "file",
    "uid": 0
}
192.168.1.114 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "efc492233d97a1898c8f797904442e6b26758276",
    "dest": "/tmp/test.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "5bdd30886cf6f00a7286ac6e7322a46e",
    "mode": "0644",
    "owner": "root",
    "size": 11,
    "src": "/root/.ansible/tmp/ansible-tmp-1596074441.5974753-76197-200420129308227/source",
    "state": "file",
    "uid": 0
}
192.168.1.113 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "efc492233d97a1898c8f797904442e6b26758276",
    "dest": "/tmp/test.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "5bdd30886cf6f00a7286ac6e7322a46e",
    "mode": "0644",
    "owner": "root",
    "size": 11,
    "src": "/root/.ansible/tmp/ansible-tmp-1596074441.5863822-76199-175841689491626/source",
    "state": "file",
    "uid": 0
}
[root@ansible ~]#

fetch模块

文档示例:

[root@ansible os]# ansible-doc -s fetch
- name: Fetch files from remote nodes
  fetch:
      dest:                  # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named
                               `/etc/profile' on host `host.example.com', would be saved into
                               `/backup/host.example.com/etc/profile'. The host name is based on the inventory
                               name.
      fail_on_missing:       # When set to `yes', the task will fail if the remote file cannot be read for any reason. Prior to Ansible 2.5,
                               setting this would only fail if the source file was missing. The default was changed
                               to `yes' in Ansible 2.5.
      flat:                  # Allows you to override the default behavior of appending hostname/path/to/file to the destination. If `dest' ends
                               with '/', it will use the basename of the source file, similar to the copy module.
                               This can be useful if working with a single host, or if retrieving files that are
                               uniquely named per host. If using multiple hosts with the same filename, the file
                               will be overwritten for each host.
      src:                   # (required) The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may
                               be supported in a later release.
      validate_checksum:     # Verify that the source and destination checksums match after the files are fetched.
[root@ansible os]#

示例如下:

[root@ansible ~]# ansible k8sservers -m fetch -a 'src=/tmp/test dest=/tmp/os'
192.168.1.114 | CHANGED => {
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/tmp/os/192.168.1.114/tmp/test",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "remote_md5sum": null
}
192.168.1.111 | CHANGED => {
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/tmp/os/192.168.1.111/tmp/test",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "remote_md5sum": null
}
192.168.1.113 | CHANGED => {
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/tmp/os/192.168.1.113/tmp/test",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "remote_md5sum": null
}
[root@ansible ~]#

image-20200730102359538

cron模块

我们知道crontab的主要作用就是制定定时计划任务,cron模块的主要作用和crontab命令是一样的。

我们知道在linux中添加一个计划任务需要指定计划任务执行的时间,执行的命令。而cron模块也是这样。

[root@ansible ~]#  ansible test -m cron -a 'name="custom job" minute=30 hour=2 day=* month=* weekday=1-5 job="sh tesh.sh"'
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "custom job"
    ]
}
[root@ansible ~]# ansible test -a 'crontab -l'
192.168.1.106 | CHANGED | rc=0 >>
#Ansible: custom job
30 2 * * 1-5 sh tesh.sh
[root@ansible ~]#  ansible test -m cron -a 'name="custom job" minute=30 hour=2 day=* month=* weekday=1-5 job="sh tesh.sh" disabled=yes'
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "custom job"
    ]
}
[root@ansible ~]# ansible test -a 'crontab -l'
192.168.1.106 | CHANGED | rc=0 >>
#Ansible: custom job
#30 2 * * 1-5 sh tesh.sh
[root@ansible ~]#  ansible test -m cron -a 'name="custom job" state=absent'
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": []
}
[root@ansible ~]# ansible test -a 'crontab -l'
192.168.1.106 | CHANGED | rc=0 >>

[root@ansible ~]#

yum 模块

可以执行yum命令

[root@ansible ~]# ansible test -m yum -a "name=httpd state=absent"
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "removed": [
            "httpd"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "已加载插件:fastestmirror\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-93.el7.centos 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package       架构           版本                          源             大小\n================================================================================\n正在删除:\n httpd         x86_64         2.4.6-93.el7.centos           @base         9.4 M\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : httpd-2.4.6-93.el7.centos.x86_64                            1/1 \n  验证中      : httpd-2.4.6-93.el7.centos.x86_64                            1/1 \n\n删除:\n  httpd.x86_64 0:2.4.6-93.el7.centos                                            \n\n完毕!\n"
    ]
}
[root@ansible ~]# ansible test -m yum -a "name=httpd"
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "installed": [
            "httpd"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirror.upsi.edu.my\n * extras: centos.mirror.myduniahost.com\n * updates: centos.mirror.angkasa.id\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-93.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package       Arch           Version                        Repository    Size\n================================================================================\nInstalling:\n httpd         x86_64         2.4.6-93.el7.centos            base         2.7 M\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : httpd-2.4.6-93.el7.centos.x86_64                             1/1 \n  Verifying  : httpd-2.4.6-93.el7.centos.x86_64                             1/1 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-93.el7.centos                                            \n\nComplete!\n"
    ]
}
[root@ansible ~]#

service模块

service模块主要用来对系统中的服务进行管理。

[root@ansible ~]# ansible-doc -s service
- name: Manage services
  service:
      arguments:             # Additional arguments provided on the command line.
      enabled:               # Whether the service should start on boot. *At least one of state and enabled are required.*
      name:                  # (required) Name of the service.
      pattern:               # If the service does not respond to the status command, name a substring to look for as would be found in the output
                               of the `ps' command as a stand-in for a status result. If the string is found, the
                               service will be assumed to be started.
      runlevel:              # For OpenRC init scripts (e.g. Gentoo) only. The runlevel that this service belongs to.
      sleep:                 # If the service is being `restarted' then sleep this many seconds between the stop and start command. This helps to
                               work around badly-behaving init scripts that exit immediately after signaling a
                               process to stop. Not all service managers support sleep, i.e when using systemd this
                               setting will be ignored.
      state:                 # `started'/`stopped' are idempotent actions that will not run commands unless necessary. `restarted' will always
                               bounce the service. `reloaded' will always reload. *At least one of state and
                               enabled are required.* Note that reloaded will start the service if it is not
                               already started, even if your chosen init system wouldn't normally.
      use:                   # The service module actually uses system specific modules, normally through auto detection, this setting can force a
                               specific module. Normally it uses the value of the 'ansible_service_mgr' fact and
                               falls back to the old 'service' module when none matching is found.
[root@ansible ~]# 
相关参数如下:
name: 指定服务的名称。
state:指定对服务进行的操作,started, stopped, restarted, reloaded。【是对应动词的过去分词形式】
enabled: yes|no, 是否加入开机自启动。
runlevel: 启动的级别。

启动对应服务器上的httpd服务,如下:

[root@ansible ~]# ansible test -m service -a "name=httpd state=started"
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "httpd",
    "state": "started",
    "status": {
        "ActiveEnterTimestampMonotonic": "0",
        "ActiveExitTimestampMonotonic": "0",
        "ActiveState": "inactive",
        "After": "basic.target tmp.mount system.slice network.target -.mount nss-lookup.target systemd-journald.socket remote-fs.target",
        "AllowIsolate": "no",
        "AmbientCapabilities": "0",
        "AssertResult": "no",
        "AssertTimestampM"
[root@ansible ~]# ansible test -a "ss -ntl"
192.168.1.106 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128       [::]:80                    [::]:*
LISTEN     0      128       [::]:22                    [::]:*
LISTEN     0      100      [::1]:25                    [::]:*
[root@ansible ~]#

command模块

command 模块可以帮助我们在远程主机上执行命令。
注意:使用 command 模块在远程主机中执行命令时,不会经过远程主机的 shell 处理,在使用 command 模块时,如果需要执行的命令中含有重定向、管道符等操作时,这些符号也会失效,比如”<”, “>”, “|”, “;” 和 “&” 这些符号,如果你需要这些功能,可以参考后面介绍的 shell 模块。还有一点需要注意,如果远程节点是 windows 操作系统,则需要使用 win_command 模块。执行 ansible 时,不加 -m 默认使用 command ,可以在 /etc/ansible/ansible.cfg 中修改。
command模块的几个选项如下:

相关选项如下:
creates:一个文件名,当该文件存在,则该命令不执行
free_form:要执行的linux指令,这里的free_form不需要写成赋值的形式,直接写要执行的命令即可。
chdir:在执行指令之前,先切换到该目录
removes:一个文件名,当该文件不存在,则该选项不执行
executable:切换shell来执行指令,该执行路径必须是一个绝对路径

实例如下:

[root@docker5 ~]# ansible -i /root/hosts all -a "w"
10.0.102.212 | SUCCESS | rc=0 >>
 10:25:27 up 8 days, 13:04,  2 users,  load average: 0.09, 0.03, 0.05
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1                      12Feb19  8days  0.01s  0.01s -bash
root     pts/1    10.0.102.209     10:25    0.00s  0.12s  0.02s w

10.0.102.200 | SUCCESS | rc=0 >>
 10:25:30 up 9 days, 17:52,  3 users,  load average: 0.05, 0.04, 0.06
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1                      11Feb19  9days  0.01s  0.01s -bash
root     pts/1    172.16.100.19    08:02    2:19m  0.02s  0.01s /usr/local/mysql/bin/mysql -uroot -px xxxx
root     pts/2    10.0.102.209     10:25    0.00s  0.16s  0.03s w

10.0.102.162 | SUCCESS | rc=0 >>
 10:25:30 up 9 days, 17:52,  3 users,  load average: 0.16, 0.05, 0.06
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1                      11Feb19  9days  0.07s  0.07s -bash
root     pts/1    172.16.100.19    08:02    2:20m  0.03s  0.01s /usr/local/mysql/bin/mysql -uroot -px xxxx
root     pts/2    10.0.102.209     10:25    1.00s  0.21s  0.03s w

[root@docker5 ~]# ansible -i /root/hosts all -a "w creates=/tmp/test" 
10.0.102.212 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists

10.0.102.200 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists

10.0.102.162 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists

[root@docker5 ~]# 

上面已经提到过command模块不能执行管道,而shell模块可以,因此在平时使用时习惯使用shell模块。

command与shell比较的一个实例

script模块

script 模块可以帮助我们在远程主机上执行 ansible 管理主机上的脚本,也就是说,脚本一直存在于 ansible 管理主机本地,不需要手动拷贝到远程主机后再执行。

script模块的用法如下:

[root@docker5 tasks]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
  script:
      chdir:                 # cd into this directory on the remote node before running the script
      creates:               # a filename, when it already exists, this step will *not* be run.
      decrypt:               # This option controls the autodecryption of source files using vault.
      free_form:             # (required) Path to the local script file followed by optional arguments. There is no parameter actually named 'free form'; see the
                               examples!
      removes:               # a filename, when it does not exist, this step will *not* be run.
[root@docker5 tasks]# 

把本地的脚本在远程主机上执行。这个命令的选项和command差不多,不同的是这里执行的是shell脚本而已。

示例:

[root@ansible ~]# ansible k8sservers -m script -a 'test.sh'
192.168.1.114 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.1.114 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.1.114 closed."
    ],
    "stdout": "1245\r\n",
    "stdout_lines": [
        "1245"
    ]
}
192.168.1.111 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.1.111 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.1.111 closed."
    ],
    "stdout": "1245\r\n",
    "stdout_lines": [
        "1245"
    ]
}
192.168.1.113 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.1.113 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.1.113 closed."
    ],
    "stdout": "1245\r\n",
    "stdout_lines": [
        "1245"
    ]
}
[root@ansible ~]#

hostname模块

示例如下:

[root@ansible ~]# ansible 192.168.1.106 -m hostname -a 'name=test'
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "",
        "ansible_fqdn": "test",
        "ansible_hostname": "test",
        "ansible_nodename": "test",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "test"
}
[root@ansible ~]# ansible 192.168.1.106 -a 'hostname'
192.168.1.106 | CHANGED | rc=0 >>
test
[root@ansible ~]#

unarchive模块

这个模块的主要作用就是解压。模块有两种用法:

1:如果参数copy=yes,则把本地的压缩包拷贝到远程主机,然后执行压缩。

2:如果参数copy=no,则直接解压远程主机上给出的压缩包。

creates:指定一个文件名,当该文件存在时,则解压指令不执行

dest:远程主机上的一个路径,即文件解压的路径 

grop:解压后的目录或文件的属组

list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项

mode:解决后文件的权限

src:如果copy为yes,则需要指定压缩文件的源路径 

owner:解压后文件或目录的属主

实例如下:

[root@ansible ~]# ansible test -m unarchive -a 'src=/root/ansible-tower-setup-bundle-latest.el8.tar.gz dest=/tmp/ copy=yes'
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/tmp/",
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar",
            "--extract",
            "-C",
            "/tmp/",
            "-z",
            "-f",
            "/root/.ansible/tmp/ansible-tmp-1596078884.6408756-78125-191332661192420/source"
        ],
        "err": "",
        "out": "",
        "rc": 0
    },
    "gid": 0,
    "group": "root",
    "handler": "TgzArchive",
    "mode": "01777",
    "owner": "root",
    "secontext": "system_u:object_r:tmp_t:s0",
    "size": 4096,
    "src": "/root/.ansible/tmp/ansible-tmp-1596078884.6408756-78125-191332661192420/source",
    "state": "directory",
    "uid": 0
}
[root@ansible ~]# ansible test -a 'ls -l /tmp'
192.168.1.106 | CHANGED | rc=0 >>
总用量 0
drwx------. 2 root root  41 7月  29 23:17 ansible_command_payload_WjHpfT
drwxr-xr-x. 6 root root 190 6月  17 06:50 ansible-tower-setup-bundle-3.7.1-1
drwxr-xr-x. 2 root root   6 7月  21 12:02 hsperfdata_root
drwx------. 3 root root  17 7月  27 10:29 systemd-private-ea6ae227571847ce8735c60bd0441345-chronyd.service-XFjVs3
drwxr-xr-x. 3 root root  18 7月  21 08:46 tomcat.1157605043846008267.8083
drwxr-xr-x. 3 root root  18 7月  21 08:44 tomcat.4359714464398435032.8080
drwxr-xr-x. 3 root root  18 7月  21 08:46 tomcat.8798180483937495567.8082
drwx------. 2 root root   6 7月  27 10:29 vmware-root_784-2966103535
drwx------. 2 root root   6 7月  19 10:49 vmware-root_789-4290756532
drwx------. 2 root root   6 7月  26 11:03 vmware-root_804-2991071810

与之相对的压缩命令的模块是archive。

archive压缩命令

查看其文档用法如下:

[root@docker5 tasks]# ansible-doc -s archive
- name: Creates a compressed archive of one or more files or trees
  archive:
      attributes:            # Attributes the file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain the attributes in
                               the same order as the one displayed by `lsattr'.
      dest:                  # The file name of the destination archive. This is required when `path' refers to multiple files by either specifying a glob, a directory or multiple paths in a list.
      exclude_path:          # Remote absolute path, glob, or list of paths or globs for the file or files to exclude from the archive
      format:                # The type of compression to use. Support for xz was added in version 2.5.
      group:                 # Name of the group that should own the file/directory, as would be fed to `chown'.
      mode:                  # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like `0644' or `01777'). Leaving off the leading
                               zero will likely have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx' or
                               `u=rw,g=r,o=r').
      owner:                 # Name of the user that should own the file/directory, as would be fed to `chown'.
      path:                  # (required) Remote absolute path, glob, or list of paths or globs for the file or files to compress or archive.
      remove:                # Remove any added source files and trees after adding to archive.
      selevel:               # Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
      serole:                # Role part of SELinux file context, `_default' feature works as for `seuser'.
      setype:                # Type part of SELinux file context, `_default' feature works as for `seuser'.
      seuser:                # User part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if available.
      unsafe_writes:         # Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are configured or just broken in
                               ways that prevent this. One example are docker mounted files, they cannot be updated atomically and can only be done in an unsafe manner.
                               This boolean option allows ansible to fall back to unsafe methods of updating files for those cases in which you do not have any other
                               choice. Be aware that this is subject to race conditions and can lead to data corruption.

示例如下:

[root@ansible ~]# ansible test -m archive -a "path=/test/ format=gz dest=/tmptest.tar.gz"
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "archived": [
        "/test/sysconfig/ip6tables-config",
        "/test/sysconfig/iptables-config",
        "/test/sysconfig/ebtables-config",
        "/test/sysconfig/nftables.conf",
        "/test/sysconfig/run-parts",
        "/test/sysconfig/crond",
        "/test/sysconfig/grub",
        "/test/sysconfig/selinux",
        "/test/sysconfig/cpupower",
        "/test/sysconfig/kdump",
        "/test/sysconfig/samba",
        "/test/sysconfig/firewalld",
        "/test/sysconfig/sshd",
        "/test/sysconfig/chronyd",
        "/test/sysconfig/atd",
        "/test/sysconfig/raid-check",
        "/test/sysconfig/smartmontools",
        "/test/sysconfig/irqbalance",
        "/test/sysconfig/man-db",
        "/test/sysconfig/kernel",
        "/test/sysconfig/network",
        "/test/sysconfig/anaconda",
        "/test/sysconfig/svnserve",
        "/test/sysconfig/memcached",
        "/test/sysconfig/rsyslog",
        "/test/sysconfig/ansible-tower",
        "/test/sysconfig/network-scripts/ifcfg-ens192"
    ],
    "arcroot": "/test/",
    "changed": true,
    "dest": "/tmptest.tar.gz",
    "expanded_exclude_paths": [],
    "expanded_paths": [
        "/test/"
    ],
    "gid": 0,
    "group": "root",
    "missing": [],
    "mode": "0644",
    "owner": "root",
    "secontext": "unconfined_u:object_r:etc_runtime_t:s0",
    "size": 6613,
    "state": "file",
    "uid": 0
}
[root@ansible ~]# ansible test -a "ls -l / |grep tmptest "
192.168.1.106 | CHANGED | rc=0 >>
-rw-r--r--.   1 root root 6613 7月  29 23:47 tmptest.tar.gz
[root@ansible ~]#

因为源目录里面有两个文件,但是上面的压缩只压缩了一个文件。

replace模块

这个模块可以根据我们指定的正则表达式替换文件的匹配的内容。

先看一个例子:

 - name: change the start script
   #shell: sed -i "s/^datadir=/datadir=\/data\/mysql/" /etc/init.d/mysqld
   replace: path=/etc/init.d/mysqld replace="datadir={{ datadir_name }}" regexp="^datadir=" backup=yes#安装MySQL的时候,需要修改MySQL的启动脚本,配置datadir参数,这里两行的作用是一样的。只是在执行playbook的时候,使用shell模块会报出警告说建议使用replcae模块。#模块参数如下:path: 指定远程主机要替换的文件的路径。regexp: 指定在文件中匹配的正则表达式,上面匹配以“datadir=”开头的行replace: 指定替换的文件,就是把上面正则匹配到的文件,替换成这里的内容。backup:表示在对文件操作之前是否备份文件。

示例:

[root@ansible ~]# ansible test -a 'cat /etc/fstab'
192.168.1.106 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Tue May 19 01:18:20 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=27c0e916-7156-4ec3-b5e8-d4a32c43850f /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
[root@ansible ~]# ansible test -m  replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1' "
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "msg": "1 replacements made"
}
[root@ansible ~]# ansible test -a 'cat /etc/fstab'
192.168.1.106 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Tue May 19 01:18:20 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
#UUID=27c0e916-7156-4ec3-b5e8-d4a32c43850f /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
[root@ansible ~]#

反向操作:

[root@ansible ~]# ansible test -m  replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1' "
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "msg": "1 replacements made"
}
[root@ansible ~]# ansible test -a 'cat /etc/fstab'
192.168.1.106 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Tue May 19 01:18:20 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=27c0e916-7156-4ec3-b5e8-d4a32c43850f /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
[root@ansible ~]#

lineinfile模块

这个模块会遍历文本中每一行,然后对其中的行进行操作。

path参数 :必须参数,指定要操作的文件。

line参数 : 使用此参数指定文本内容。

regexp参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,        这么这些行都会被删除。

state参数:当想要删除对应的文本时,需要将state参数的值设置为absent,absent为缺席之意,表示删除,state的默认值为present。

backrefs参数:默认情况下,当根据正则替换文本时,即使regexp参数中的正则存在分组,在line参数中也不能对正则中的分组进行引用,除非将backrefs参数的值设置为yes。      backrefs=yes表示开启后向引用,这样,line参数中就能对regexp参数中的分组进行后向引用了,这样说不太容易明白,可以参考后面的示例命令理解。backrefs=yes      除了能够开启后向引用功能,还有另一个作用,默认情况下,当使用正则表达式替换对应行时,如果正则没有匹配到任何的行,那么line对应的内容会被插入到文本的末尾,      不过,如果使用了backrefs=yes,情况就不一样了,当使用正则表达式替换对应行时,同时设置了backrefs=yes,那么当正则没有匹配到任何的行时,      则不会对文件进行任何操作,相当于保持原文件不变。

insertafter参数:借助insertafter参数可以将文本插入到“指定的行”之后,insertafter参数的值可以设置为EOF或者正则表达式,EOF为End Of File之意,表示插入到文档的末尾,      默认情况下insertafter的值为EOF,如果将insertafter的值设置为正则表达式,表示将文本插入到匹配到正则的行之后,如果正则没有匹配到任何行,则插入到文件末尾,      当使用backrefs参数时,此参数会被忽略。

insertbefore参数:借助insertbefore参数可以将文本插入到“指定的行”之前,insertbefore参数的值可以设置为BOF或者正则表达式,BOF为Begin Of File之意,      表示插入到文档的开头,如果将insertbefore的值设置为正则表达式,表示将文本插入到匹配到正则的行之前,如果正则没有匹配到任何行,则插入到文件末尾,      当使用backrefs参数时,此参数会被忽略。

backup参数:是否在修改文件之前对文件进行备份。

create参数 :当要操作的文件并不存在时,是否创建对应的文件。

示例如下:

[root@ansible ~]# ansible test -a "cat /etc/selinux/config"
192.168.1.106 | CHANGED | rc=0 >>

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted
[root@ansible ~]# ansible test -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing1'"
192.168.1.106 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}
[root@ansible ~]# ansible test -a "cat /etc/selinux/config"
192.168.1.106 | CHANGED | rc=0 >>

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=enforcing1
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

setup模块

用来收集信息

        "ansible_distribution": "CentOS",
        "ansible_distribution_file_parsed": true,
        "ansible_distribution_file_path": "/etc/redhat-release",
        "ansible_distribution_file_variety": "RedHat",
        "ansible_distribution_major_version": "7",
        "ansible_distribution_release": "Core",
        "ansible_distribution_version": "7.8",
[root@ansible ~]# ansible all -m setup -a 'filter="ansible_distribution_version"'
192.168.1.106 | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution_version": "7.8",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
192.168.1.114 | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution_version": "7.8",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
192.168.1.111 | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution_version": "7.8",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
192.168.1.113 | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution_version": "7.8",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
192.168.1.117 | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution_version": "7.8",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
[root@ansible ~]#

posted @ 2020-07-30 13:22  天宇轩-王  阅读(289)  评论(0编辑  收藏  举报