目录

  1. Ansible - 安装介绍
  2. Ansible -常用模块介绍
  3. Ansbile - Playbook 使用
  4. Ansible - Roles 使用示例


基础配置

[root@localhost ~]# cat /etc/ansible/hosts 
[server]
10.91.156.209

[node]
10.91.156.205




Command模块

功能

在远程主机执行命令,此为默认模块,可忽略-m选项

注意:此命令不支持 $VARNAME < > | ; & 等,用shell模块实现

文档

[root@localhost ~]# ansible-doc -s command
- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly (for example "user name"). Only the
                               string or the list form can be provided, not both.  One or the other must be provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
      free_form:             # The command module takes a free form command to run. There is no actual parameter named 'free form'.
      removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # If set to `yes', append a newline to stdin data.
      strip_empty_ends:      # Strip empty lines from the end of stdout/stderr in result.
      warn:                  # Enable or disable task warnings.

示例

# 切换到/etc目录下 查看centos-release
[root@localhost ~]# ansible server -m command -a 'chdir=/etc cat centos-release'
10.91.156.209 | CHANGED | rc=0 >>
CentOS Linux release 7.6.1810 (Core)




Shell模块

功能

和command相似,用shell执行命令

注意:调用bash执行命令 类似cat /tmp/test.md | awk -F‘|’ ‘{print 1,1,1,2}’ &> /tmp/example.txt这些复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器

文档

[root@localhost ~]# ansible-doc -s shell
- name: Execute shell commands on targets
  shell:
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run followed by optional arguments.
      creates:               # A filename, when it already exists, this step will *not* be run.
      executable:            # Change the shell used to execute the command. This expects an absolute path to the executable.
      free_form:             # The shell module takes a free form command to run, as a string. There is no actual parameter named 'free form'. See the examples on how to use this module.
      removes:               # A filename, when it does not exist, this step will *not* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # Whether to append a newline to stdin data.
      warn:                  # Whether to enable task warnings.

示例

  1. 将shell模块代替command,设为默认模块。编辑/etc/ansible/ansible.cfg文件
# default module name for /usr/bin/ansible
#module_name = command
module_name = shell
  1. 打印主机的hostname。对比发现command模块输出有问题,shell可以正常打印
[root@localhost ~]# ansible server -m command -a 'echo $HOSTNAME'
10.91.156.209 | CHANGED | rc=0 >>
$HOSTNAME
[root@localhost ~]# ansible server -m shell -a 'echo $HOSTNAME'
10.91.156.209 | CHANGED | rc=0 >>
node




Script模块

功能

在远程主机上运行ansible服务器上的脚本

文档

[root@localhost ~]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
  script:
      chdir:                 # Change into this directory on the remote node before running the script.
      cmd:                   # Path to the local script to run followed by optional arguments.
      creates:               # A filename on the remote node, when it already exists, this step will *not* be run.
      decrypt:               # This option controls the autodecryption of source files using vault.
      executable:            # Name or path of a executable to invoke the script with.
      free_form:             # Path to the local script file followed by optional arguments.
      removes:               # A filename on the remote node, when it does not exist, this step will *not* be run.

示例

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

echo sever HostName is `hostname`

[root@localhost ~]# ansible server -m script -a 'test.sh'
10.91.156.209 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 10.91.156.209 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 10.91.156.209 closed."
    ], 
    "stdout": "sever HostName is node\r\n", 
    "stdout_lines": [
        "sever HostName is node"
    ]
}



Copy模块

功能

ansible服务器主控端复制文件到远程主机

[root@localhost ~]# ansible-doc -s copy
- name: Copy files to remote locations
  copy:
  .....

示例

#如目标存在,默认覆盖,此处指定先备份
ansible websrvs -m copy -a “src=/root/test1.sh dest=/tmp/test2.sh    owner=wang  mode=600 backup=yes” 
#指定内容,直接生成目标文件    
ansible websrvs -m copy -a "content='test line1\ntest line2' dest=/tmp/test.txt"
#复制/etc/下的文件,不包括/etc/目录自身
ansible websrvs -m copy -a “src=/etc/ dest=/backup”




Fetch模块

功能

从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录




File模块

功能

设置文件属性

常见参数

参数

含义

group

文件所属组

mode

文件权限

owner

文件拥有者

path

需要管理的文件路径(必选)

recurse

递归设置(当state取值为directory)

src

文件的链接地址 (只当state值为link或hard时设置)

state

absent:目录会递归删除,文件会被删除,符号链接会被取消链接

directory:创建目录

hard 创建或修改硬链接 link 创建或修改软链接

touch:如果path指定的文件不存在,则创建

示例

[root@localhost ~]# ansible server -m file -a 'path=/root/test.txt state=touch'
10.91.156.209 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/root/test.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@localhost ~]# ansible server -a 'ls -l'
10.91.156.209 | CHANGED | rc=0 >>
...
-rw-r--r--. 1 root root         0 12月 24 16:51 test.txt




unarchive模块

功能

解包解压缩

实现有两种用法:
1、将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes
2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no

常见参数

  • copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件
  • remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上
  • src:源路径,可以是ansible主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置copy=no
  • dest:远程主机上的目标路径
  • mode:设置解压缩后的文件权限

示例

# 创建压缩包
[root@localhost ~]# tar -czvf testDir.tar.gz testDir/
testDir/
testDir/test.sh
# 将压缩包拷至远程主机 /root 目录下并解压
[root@localhost ~]# ansible server -m unarchive -a 'src=./testDir.tar.gz dest=/root copy=yes'
10.91.156.209 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/root", 
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar", 
            "--extract", 
            "-C", 
            "/root", 
            "-z", 
            "-f", 
            "/root/.ansible/tmp/ansible-tmp-1608812600.88-13937-63576563579965/source"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "TgzArchive", 
    "mode": "0550", 
    "owner": "root", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 244, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608812600.88-13937-63576563579965/source", 
    "state": "directory", 
    "uid": 0
}

# 查看远程主机解压结果
[root@localhost ~]# ansible server -a 'ls -l /root/testDir/'
10.91.156.209 | CHANGED | rc=0 >>
总用量 4
-rwxr-xr-x. 1 root root 47 12月 24 14:31 test.sh




Archive模块

功能

打包压缩

示例

# 将目标主机 /roor/testDir 目录压缩至 /root/testDir.tar.gz 权限为 644
[root@localhost ~]# ansible server -m archive -a 'path=/root/testDir/ dest=/root/testDir.tar.gz format=gz mode=644'
10.91.156.209 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "archived": [
        "/root/testDir/test.sh"
    ], 
    "arcroot": "/root/testDir/", 
    "changed": true, 
    "dest": "/root/testDir.tar.gz", 
    "expanded_exclude_paths": [], 
    "expanded_paths": [
        "/root/testDir/"
    ], 
    "gid": 0, 
    "group": "root", 
    "missing": [], 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 175, 
    "state": "file", 
    "uid": 0
}

[root@localhost ~]# ansible server -a 'ls -l /root'
10.91.156.209 | CHANGED | rc=0 >>
...
-rw-r--r--. 1 root root       175 12月 24 21:48 testDir.tar.gz




Hostname模块

功能

管理主机名

参数

说明

name

(必填)主机名称

use

更新策略

示例

ansible server -m hostname -a “name=suhw”




Cron模块

功能

计划任务

常用参数

参数

含义

minute


hour

小时

day


month


weekday

作业应该在一周的哪一天运行(周日-周六为0-6)

job

任务路径

disabled

是否禁用任务

user

应该修改crontab的特定用户。如果没有设置,这个参数默认使用’ root’。

示例

# 脚本内容:输出当前时间至log文件
[root@localhost ~]# cat /root/date.sh 
#/!/bin/sh
date >> /root/date.log

# 先拷贝到目标主机上
[root@localhost ~]# ansible server -m copy -a "src=./date.sh dest=/root/date.sh mode=755"

# 将脚本每分钟执行一次
[root@localhost ~]# ansible server -m cron -a "job=/root/date.sh minute=*/1 name=GetDate"
10.91.156.205 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "GetDate"
    ]
}

# 查看目标主机定时任务列表
[root@localhost ~]# ansible server -a 'crontab -l'
10.91.156.205 | CHANGED | rc=0 >>
#Ansible: GetDate
*/1 * * * * /root/date.sh
# 查看执行结果
[root@localhost ~]# ansible server -a 'cat /root/date.log'
10.91.156.205 | CHANGED | rc=0 >>
Fri Dec 25 19:48:01 CST 2020

# 使用 disabled 属性取消该任务
[root@localhost ~]# ansible server -m cron -a "job=/root/date.sh minute=*/1 name=GetDate disabled=true"
10.91.156.205 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "GetDate"
    ]
}
# 再次查看发现已经注释取消
[root@localhost ~]# ansible server -a 'crontab -l'
10.91.156.205 | CHANGED | rc=0 >>
#Ansible: GetDate
#*/1 * * * * /root/date.sh




Yum模块

功能

管理软件包,只支持RHELCentOSfedora,不支持Ubuntu其它版本

常用参数

参数

含义

name

包名或带有版本的包说明符,如’ name-1.0’。

state

可选:absent, installed, latest, present, removed



Service模块

功能

管理服务

常见参数

参数

含义

name

包名或带有版本的包说明符,如’ name-1.0’。

state

可选:started 、stopped 、 restarted 、 reloaded

enabled

是否开机启动

示例

# 关闭远程主机docker服务
[root@localhost ~]# ansible server -m service -a 'name=docker state=stopped'




User模块

功能

管理用户

示例

# 添加用户
[root@localhost ~]# ansible server -m user -a 'name=test01 uid=8888 home=/home/test01 group=root'
...
[root@localhost ~]# ansible server -a 'getent passwd test01'
10.91.156.205 | CHANGED | rc=0 >>
test01:x:8888:0::/home/test01:/bin/bash

# 删除 test01 用户并删除家目录
[root@localhost ~]# ansible server -m user -a 'name=test01 state=absent remove=yes'




Group模块

功能

管理用户组

示例

#创建组
ansible websrvs -m group  -a 'name=nginx gid=88 system=yes'
#删除组
ansible websrvs -m group  -a 'name=nginx state=absent'




Lineinfile模块

功能

相当于sed,可以修改文件内容。

ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,存在问题,无法正常进行替换 。其实在ansible自身提供了两个模块:lineinfile模块和replace模块,可以方便的进行替换

示例

ansible all -m   lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing'"
ansible all -m lineinfile  -a 'dest=/etc/fstab state=absent regexp="^#"'




Replace模块

功能

该模块有点类似于sed命令,主要也是基于正则进行匹配和替换

示例

ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"  
ansible all -m replace -a "path=/etc/fstab regexp='^#(.*)' replace='\1'"




Setup模块

功能

setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,会影响执行速度,可以使用

gather_facts: no

来禁止 Ansible 收集 facts 信息

常见参数

参数

说明

filter

按照key过滤输出结果,支持通配符

gather_timeout

设置收集数据的超时时间

示例

[root@localhost ~]# ansible server -m setup -a 'filter=ansible_virtualization_type'
10.91.156.205 | SUCCESS => {
    "ansible_facts": {
        "ansible_virtualization_type": "kvm", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

可不加filter获取全部信息后,找到自己所需的字段,再通过filter方式获取指定字段