zoukankan      html  css  js  c++  java
  • Ansible-基础配置及常用模块

    一、Ansible介绍

    1.1、什么是ansible?

    Ansible是一个配置管理系统configuration management system, python 语言是运维人员必须会的语言, ansible 是一个基于python 开发的自动化运维工具, 其功能实现基于ssh远程连接服务, ansible 可以实现批量系统配置,批量软件部署,批量文件拷贝,批量运行命令等功能, 除了ansible之外,还有saltstack 等批量管理软件.

    1.2、软件特点

    1)ansible不需要单独安装客户端,SSH相当于ansible客户端。

    2)ansible不需要启动任何服务,仅需安装对应工具即可。

    3)ansible依赖大量的python模块来实现批量管理。

    4)ansible配置文件/etc/ansible/ansible.cfg

    5)Ansible是一种agentless(基于ssh),可实现批量配置、命令执行和控制,基于Python实现的自动化运维工具。Ansible的两个特性:

    • 模块化:通过调用相关模块,完成指定任务,且支持任何语言编写的自定义模块;
    • playbook:剧本,可根据需要一次执行完剧本中的所有任务或某些任务;

    1.3、架构特点

    15365930348150

    1)连接插件(connectior plugins) :用于连接主机 用来连接被管理端。

    2)核心模块(core modules) :连接主机实现操作, 它依赖于具体的模块来做具体的事情。

    3)自定义模块(custom modules): 根据自己的需求编写具体的模块。

    4)插件(plugins): 完成模块功能的补充。

    5)剧本(playbooks):ansible的配置文件,将多个任务定义在剧本中,由ansible自动执行。

    6)主机清单(host inventory):定义ansible需要操作主机的范围。

    1.4、任务执行模式

    1.4.1、ad-hoc模式(点对点模式)

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

    1.4.2、playbook模式(剧本模式)

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

    1.5、命令执行流程

    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安装配置

    2.1、ansible安装

    1)yum安装

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

    2)pip安装

    yum install python-pip
    pip install ansible

    2.2、程序结构及配置文件

    2.2.1、安装目录

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

    2.2.2、配置文件:/etc/ansible/ansible.cfg

    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日志的文件(默认不记录日志)

    补充如下:

    host_key_checking  
    host_key_checking=False 禁用验证host_key_checking
     
    inventory 
    定义库文件位置,脚本,或者存放可通信主机的目录
    inventory = /etc/ansible/hosts
     
    library
    ansible默认搜寻模块的位置
    library = /usr/share/ansible
    Ansible知道如何搜寻多个用冒号隔开的路径,同时也会搜索在playbook中的"./library"。
     
    log_path
    日志存放位置
    默认不开启,ansible将会吧模块加载纪录在系统日志系统中.不包含用密码.
    log_path=/var/log/ansible.log
     
    module_name
    这个是/usr/bin/ansible的默认模块名(-m). 默认是'command'模块。command模块不支持shell变量,管道,配额。所以最好把这个参数改为'shell'。
    module_name = command
     
    nocolor
    默认ansible会为输出结果加上颜色,用来更好的区分状态信息和失败信息。如果你想关闭这一功能,可以把'nocolor'设置为'1'。
    nocolor=0
     
    nocows 
    默认ansible可以调用一些cowsay的特性,使得/usr/bin/ansible-playbook运行起来更加愉快。
    如果不喜欢cows,可以通通过将'nocows'设置为'1'来禁用这一选项:
    nocows=0
     
    poll_interval
    对于Ansible中的异步任务,这个是设置定义,当具体的poll interval 没有定义时,多少时间回查一下这些任务的状态, 默认值是一个折中选择15秒钟.这个时间是个回查频率和任务完成叫回频率和当任务完成时的回转频率的这种:
    poll_interval=15
     
    private_key_file
    如果你是用pem密钥文件而不是SSH客户端或秘密啊认证的话, 你可以设置这里的默认值, 来避免每一次提醒设置密钥文件位置"--ansible-private-keyfile":
    private_key_file=/path/to/file.pem
     
    remote_port
    这个设置是你系统默认的远程SSH端口, 如果不指定,默认为22号端口:(建议修改成别的端口)
    remote_port = 22
     
    remote_user
    这是个ansible使用/usr/bin/ansible-playbook连接的默认用户名。注意如果不指定, /usr/bin/ansible默认使用当前用户名称:
    remote_user = root
     
    timeout
    这个事默认SSH链接尝试超市时间:
    timeout = 10
     
    transport
    如果"-c <transport_name>" 选项没有在使用/usr/bin/ansible 或者 /usr/bin/ansible-playbook 特指的话, 这个参数提供了默认通信机制。默认值为'smart'。
    如果本地系统支持ControlPersist技术的话, 将会使用(基于OpenSSH)'ssh', 如果不支持该技术,将使用'paramiko'库,其他传输选项包括'local', 'chroot','jail'等等。
    用户通常可以这个设置为'smart',让playbook在需要的条件自己选择'connectin:'参数.
     
    record_host_keys
    默认设置会记录并验证通过在用户hostfile中新发现的的主机(如果host key checking 被激活的话)。这个选项在有很多主机的时候将会性能很差!!
    在这种情况下,建议使用SSH传输代替。当设置为False时, 性能将会提升,在hostkey checking 被禁用时候, 建议使用!!!
    record_host_keys=True
     
    scp_if_ssh
    又是用户操控一个一个没有开启SFTP协议的远程系统.如果这个设置为True, scp将代替用来为远程主机传输文件:
    scp_if_ssh=False   
    如果没有遇到这样的问题没有必要来修改这个设置。当然修改这个设置也没有什么明显的弊端。大部分的系统环境都默认支持SFTP, 通常情况下不需要修改。
     
    pipelining
    在不通过实际文件传输的情况下执行ansible模块来使用管道特性, 从而减少执行远程模块SSH操作次数。如果开启这个设置,将显著提高性能!!
    然而当使用"sudo:"操作的时候, 你必须在所有管理的主机的/etc/sudoers中禁用'requiretty'。
    默认这个选项为了保证与sudoers requiretty的设置(在很多发行版中时默认的设置)的兼容性是禁用的。但是为了提高性能强烈建议开启这个设置。
    pipelining=False
     
    accelerate_port
    在急速模式下使用的端口。
    accelerate_port = 5099
     
    accelerate_timeout
    这个设置时用来控制从客户机获取数据的超时时间.如果在这段时间内没有数据传输,套接字连接会被关闭. 一个保持连接(keepalive)数据包通常每15秒回发回给控制台,所以这个超时时间不应该低于15秒(默认值为30秒):
    accelerate_timeout = 30
     
    accelerate_connect_timeout
    这个设置空着套接字调用的超时时间。这个应该设置相对比较短。
    这个和'accelerate_port'连接在回滚到ssh或者paramiko(受限于你默认的连接设置)连接方式之前会尝试三次开始远程加速daemon守护进程。默认设置为1.0秒!
    accelerate_connect_timeout = 1.0
    需要注意: 这个选项值可以设置为小于1秒钟,但是除非你拥有一个速度很快而且很可靠的网络,否则也许这样并不是一个很好的选择。
    如果你使用英特网访问你的系统,最好提高这个值!!!
     
    accelerate_daemon_timeout
    这个控制加速daemon守护进程的超时时间,用分钟来衡量.默认为30分钟!
    accelerate_daemon_timeout = 30
    注意, 在1.6版本之前,daemon发起的超时时间是硬编码的.对于1.6以后的版本,超时时间是根据daemon上一次活动信息和这个可设置的选项。
     
    accelerate_multi_key
    如果这个选项开启,这个设置将允许多个私钥被加载到daemon。任何客户端要想连接daemon都需要开启这个选项!!!
    accelerate_multi_key = yes
    通过本地套接字文件连接的通过SSH上传密钥文件到目标节点的新客户端, 必须在登陆daemon时使用原始的登陆密钥登陆。

    2.2.3、主机清单:/etc/ansible/hosts

    /etc/ansible/hosts是ansible默认主机资产清单文件,用于定义被管理主机的认证信息, 例如ssh登录用户名、密码以及key相关信息

    1)基于密码连接

    [root@m ~]# cat /etc/ansible/hosts
    
    #方式一、主机+端口+密码
    [webservers]
    10.0.0.31 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123456'
    10.0.0.41 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123456'
    
    #方式二、主机+端口+密码
    [webservers]
    web[1:2].oldboy.com ansible_ssh_pass='123456'
    
    #方式三、主机+端口+密码
    [webservers]
    web[1:2].oldboy.com
    [webservers:vars]
    ansible_ssh_pass='123456'

    2)基于密钥连接,需要先创建公钥和私钥,并下发公钥至被控端

    [root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.41
    [root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.31
    
    #方式一、主机+端口+密钥
    [group_name]
    10.0.0.31:22
    10.0.0.41
    
    #方式二、别名+主机+端口+密钥
    [group_name]
    nfs-node1 ansible_ssh_host=10.0.0.31 ansible_ssh_port=22

    3)主机组使用方式

    #方式一、主机组变量+主机+密码
    [group_name1]
    10.0.0.31
    10.0.0.41
    [group_name1:vars]
    ansible_ssh_pass='123456'
    
    #方式二、主机组变量+主机+密钥
    [group_name2]
    10.0.0.7
    10.0.0.8
    
    #定义多组,多组汇总整合
    # webservers组包括两个子组[apache,nginx]
    [webservers:children]
    [group_name1]
    [group_name2]

    三、Ansible常用命令

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

    常用的是/usr/bin/ansible/usr/bin/ansible-playbook

    3.1、ansible-doc命令

    ansible-doc 命令常用于获取模块信息及其使用帮助,一般用法如下:

    ansible-doc -l              #获取全部模块的信息
    ansible-doc -s MOD_NAME     #获取指定模块的使用帮助

    示例:

    [root@Manager ~]#ansible-doc -l|grep mysql
    azure_rm_mysqlfirewallrule_info                               Get Azure MySQL Firewall Rule facts                     
    azure_rm_mysqlconfiguration_info                              Get Azure MySQL Configuration facts                     
    mysql_info                                                    Gather information about MySQL servers                  
    mysql_db                                                      Add or remove MySQL databases from a remote host        
    azure_rm_mysqlserver_info                                     Get Azure MySQL Server facts                            
    azure_rm_mysqldatabase_info                                   Get Azure MySQL Database facts                          
    mysql_variables                                               Manage MySQL global variables                           
    mysql_user                                                    Adds or removes a user from a MySQL database            
    proxysql_backend_servers                                      Adds or removes mysql hosts from proxysql admin interfac...
    azure_rm_mysqlconfiguration                                   Manage Configuration instance                           
    azure_rm_mysqlfirewallrule                                    Manage MySQL firewall rule instance                     
    azure_rm_mysqlserver                                          Manage MySQL Server instance                            
    mysql_replication                                             Manage MySQL replication                                
    proxysql_mysql_users                                          Adds or removes mysql users from proxysql admin interfac...
    azure_rm_mysqldatabase                                        Manage MySQL Database instance                          
    [root@Manager ~]#ansible-doc -s mysql_user
    - name: Adds or removes a user from a MySQL database
      mysql_user:
          append_privs:          # Append the privileges defined by priv to the existing ones for this user instead of
                                   overwriting existing ones.
          ca_cert:               # The path to a Certificate Authority (CA) certificate. This option, if used, must specify
                                   the same certificate as used by the server.
          check_implicit_admin:   # Check if mysql allows login as root/nopassword before trying supplied credentials.
          client_cert:           # The path to a client public key certificate.
          client_key:            # The path to the client private key.
          config_file:           # Specify a config file from which user and password are to be read.
          connect_timeout:       # The connection timeout when connecting to the MySQL server.
          encrypted:             # Indicate that the 'password' field is a `mysql_native_password` hash.
          host:                  # The 'host' part of the MySQL username.
          host_all:              # Override the host option, making ansible apply changes to all hostnames for a given user.
                                   This option cannot be used when creating users.
          login_host:            # Host running the database.
          login_password:        # The password used to authenticate with.
          login_port:            # Port of the MySQL server. Requires `login_host' be defined as other than localhost if
                                   login_port is used.
          login_unix_socket:     # The path to a Unix domain socket for local connections.
          login_user:            # The username used to authenticate with.
          name:                  # (required) Name of the user (role) to add or remove.
          password:              # Set the user's password..
          priv:                  # MySQL privileges string in the format: `db.table:priv1,priv2'. Multiple privileges can be
                                   specified by separating each one using a forward slash:
                                   `db.table:priv/db.table:priv'. The format is based on MySQL
                                   `GRANT' statement. Database and table names can be quoted,
                                   MySQL-style. If column privileges are used, the
                                   `priv1,priv2' part must be exactly as returned by a `SHOW
                                   GRANT' statement. If not followed, the module will always
                                   report changes. It includes grouping columns by permission
                                   (`SELECT(col1,col2') instead of
                                   `SELECT(col1',SELECT(col2))).
          sql_log_bin:           # Whether binary logging should be enabled or disabled for the connection.
          state:                 # Whether the user should exist. When `absent', removes the user.
          update_password:       # `always' will update passwords if they differ. `on_create' will only set the password for
                                   newly created users.

    3.2、ansible命令

    15444333387910

    语法格式:
    ansible <pattern_goes_here> -m <module_name> -a <arguments>
    ansible  匹配模式   -m  模块  -a  '需要执行的内容'
    
    解释说明:
    匹配模式:即哪些机器生效 (可以是某一台, 或某一组, 或all) , 默认模块为command , 执行常规的shell命令.
    -m name, --module-name=name:  指定执行使用的模块。
    -u username, --user=username:  指定远程主机以username运行命令。
    -s, --sudo:  相当于linux系统下的sudo命令。
    -u sudo_username, --sudo-user=sudo_username:  使用sudo, 相当于linux系统下的sudo命令。
    -C, --check:  只检查不实际执行。
    -e, 即extra_vars:  引用外部参数。
    -i, 即inventory:  指定仓库列表, 默认/etc/ansible/hosts。
    --list-host:  列出执行主机列。

    详细说明:

    语法:ansible <host-pattern> [options]
     
    使用ansible --help可以查看到命令参数,
    常用选项参数:
    --version               #显示版本
    -m module               #指定使用的模块,默认为command
    -v                      #查看执行的详细过程(-vv、-vvvv更详细)
    --list-hosts            #显示主机列表(可以简写为--list)
    -k,--ask-pass           #提示输入ssh连接密码,默认使用key验证
    -K,--ask-become-pass    #提示执行输入sudo的密码
    -C,--check              #检查,并不执行
    -T,--timeout=TIMEOUT    #执行命令的超时时间,默认10s
    -u,--user=REMOTE_USER   #指定远程执行的执行用户
    -b,--become             #代替旧版本的sudo切换
    -h,--help               #显示使用帮助
    -u                      #指定远程主机运行此命令的用户
    -s                      #相当于sudo
    -S                      #使用sudo
     
    ======================================================
    [普通选项]
    -a MODULE_ARGS
    --args=MODULE_ARGS
    传递参数给模块
      
    --ask-vault-pass
    询问vault的密码
      
    -B SECONDS
    --background=SECONDS
    异步后台⽅式执⾏任务,并在指定的秒数后超时,超时会杀掉任务的进程。默认是同步,即保持长连接,它会等待
    所有执⾏完毕(即阻塞模式)。但有时候是没必要这样的,⽐如某些命令的执⾏时间⽐ssh的超时时间还长。如果
    不指定超时秒数,将以同步⽅式运⾏任务
      
    -P POLL_INTERVAL
    --poll=POLL_INTERVAL
    异步模式下轮询任务的时间间隔,默认60秒
      
    -C
    --check
    不对远程主机做一些改变,而是预测某些可能发生的改变(检查功能)
      
    -e EXTRA_VARS
    --extra-vars=EXTRA_VARS
    配置额外的配置变量(key=value或者YAML/JSON格式)
      
    -f FORKS
    --forks=FORKS
    指定并行处理的进程数量,默认5个
      
    -h
    --help
    显示帮助信息
      
    -i INVENTORY
    --inventory-file=INVENTORY
    指定inventory⽂件,多个⽂件使⽤逗号分隔。默认为/etc/ansible/hosts
      
    -l SUBSET
    --limit=SECONDS
    使⽤额外的匹配模式来筛选⽬标主机列表。
    此处的匹配模式是在已有匹配模式下进⾏的,所以是更严格的筛选。例如指定了主机组的情况下,使⽤-l选项从中只选⼀台主机进⾏控制
      
    --list-hosts
    不会执行任何操作,而是列出匹配到的主机列表
      
    -m MODULE_NAME
    --module-name=MODULE_NAME
    指定要执行的模块名,默认的模块为"command"
      
    --new-vault-password-file=NEW_VAULT_PASSWORD_FILE
    new vault password f ile f or rekey
      
    -o
    --one-line
    简化输出(一行输出模式)
      
    --output-OUTPUT_FILE
    output f ile name f or encrypt or decrypt; use - f or stdout
      
    --syntax-check
    检查playbook的语法,不会执行
      
    -t TREE
    --tree=TREE
    记录输出到此⽬录中(测试时以每个host名如IP地址为⽂件名记录,结果记录到对应的⽂件中)。
    此选项在ansible巨慢的时候(如瞬间应该返回的命令还需要10多秒才完成)有奇⽤,或者将ansible的结果重
    定向到某个⽂件中也能解决,为什么如此,我也不明⽩(表⾯看来和输出⽅式有关系),多次亲测有效。
      
    --vault-password-file=VAULT_PASSWORD_FILE
    指定vault密码文件
      
    -v
    --verbose
    输出详细信息,-vvv和-vvvv输出更详细的信息
      
    --version
    显示ansbile的版本
      
    ======================================================
    [以下是连接选项,⽤于控制谁以及如何连接主机]
    -k
    --ask-pass
    询问连接时的密码
      
    --private-key=KEY_FILE
    --key-file=KEY_FILE
    使用文件来认证SSH连接的过程
      
    -u REMOTE_USER
    --user=REMOTE_USER
    使用指定的用户名进行连接
      
    -c CINNECTION
    --connection=CINNECTION
    连接类型,默认为ssh。paramiko (SSH), ssh, winrm and local. local is mostly usef ul f or crontab or kickstarts.
      
    -T TIMEOUT
    --time=TIMEOUT
    连接的超时时间,单位为秒,默认10秒
      
    --ssh-common-args=SSH_COMMON_ARGS
    指定传递给sftp/scp/ssh等⼯具的通⽤额外参数
      
    --sftp-extra-args=SFTP_EXTRA_ARGS
    指定只传递给sftp的额外参数,如-f
      
    --scp-extra-args=SCP_EXTRA_ARGS
    指定只传递给scp的额外参数,如-l
      
    --ssh-extra-args=SSH_EXTRA_ARGS
    指定只传递给ssh的额外参数,如-R
      
    ======================================================
    [以下是权限控制选项:控制在⽬标主机上以什么⾝份和权限运⾏任务]
    -s
    --sudo
    为运行ansible命令的用户提升权限为sudo_user的权限,此命令已经报废,使用become代替
      
    -u SUDO_USER
    --sudo-user=SUDO_USER
    期望的sudo_user,默认为root,已报废,使用become代替
      
    -S
    --su
    使⽤su的⽅式执⾏操作,已废弃,使⽤become替代
      
    -R SU_USER
    --su-user=SU_USER
    使⽤此user的su执⾏操作,默认为root,已废弃,使⽤become替代
      
    -b
    --become
    使用become的方式升级权限
      
    --become-method=BECOME_METHOD
    指定提升权限的方式,可选以下⼏种:sudo/su/pbrun/pf exec/doas/dzdo/ksu/runas值
      
    --become-user=BECOME_USER
    要提升为哪个user的权限,默认为root
      
    --ask-sudo-pass
    询问sudo密码,已废弃,使⽤become替代
      
    --ask-su-pass
    询问su的密码,已废弃,使⽤become替代
      
    -K
    --ask-become-pass
    询问become提升权限时的密码

    3.3、ansible-playbook命令

    ansible-playbook是日常用的最多的命令,其工作机制是:通过读取预先编写好的playbook文件实现批量管理,要实现的功能与命令ansbile一样,可以理解为按一定的条件组成ansible的任务集ansible-playbook命令后跟YML格式的playbook文件,执行事先编排好的任务集

    #使用ansible-playbook执行一个yaml文件
    [root@ansible ~]# ansible-playbook -C /opt/ansible-playbook/test.yaml

    3.4、ansible-console(交互终端)

    Ansible-console是ansible为用户提供的一款交互式工具,用户可在ansible-console虚拟出的终端上使用ansible内置的各种命令。所有的操作与shell类似,并支持tab补全.

    #对所有受控端进行操作
    [root@Manager ~]#ansible-console 
    Welcome to the ansible console.
    Type help or ? to list commands.
    
    root@all (2)[f:5]$ uptime
    172.16.93.165 | CHANGED | rc=0 >>
     14:43:10 up 140 days, 23 min,  3 users,  load average: 0.44, 0.23, 0.12
    
    172.16.93.167 | CHANGED | rc=0 >>
     14:43:10 up 140 days, 23 min,  1 user,  load average: 0.00, 0.01, 0.05
    
    #对web组操作
    [root@Manager ~]#ansible-console web
    Welcome to the ansible console.
    Type help or ? to list commands.
    
    root@web (1)[f:5]$ list
    172.16.93.165
    root@web (1)[f:5]$ cat /etc/passwd|grep root
    172.16.93.165 | CHANGED | rc=0 >>
    root:x:0:0:root:/root:/bin/bash
    operator:x:11:0:operator:/root:/sbin/nologin
    
    root@web (1)[f:5]$ exit
    
    #-------------------------------------------------
    在终端可做的操作
    设置并发数: forks n  例如:forks 10
    切换组: cd 组名      例如:cd web
    列出当前组主机列表   例如:list
    列出所有的内置命令(其实就是内置的模块)   例如:?或者help
    exit命令退出终端

    3.5、ansible-inventory命令

    查看被控制端主机清单的详细信息默认情况下它使用库存脚本,返回JSON格式:

    [root@Manager ~]#ansible-inventory --list
    {
        "_meta": {
            "hostvars": {
                "172.16.93.165": {
                    "ansible_port": 2812
                }, 
                "172.16.93.167": {
                    "ansible_port": 2812
                }
            }
        }, 
        "all": {
            "children": [
                "db", 
                "ungrouped", 
                "web"
            ]
        }, 
        "db": {
            "hosts": [
                "172.16.93.167"
            ]
        }, 
        "web": {
            "hosts": [
                "172.16.93.165"
            ]
        }
    }
    

    3.6、ansible-vault命令

    ansible-vault主要用于配置文件的加密,如编写的playbook配置文件中包含敏感的信息,不希望其他人随便的看,ansible-vault可加密/解密这个配置文件:

    语法:ansible-vault [create|decrypt|edit|encrypt|encrypt_string|rekey|view] [options] [vaultfile.yml]
    参数:
    --ask-vault-pass      ask for vault password
    -h, --help                                          #查看帮助信息
    --new-vault-id=NEW_VAULT_ID                         #设置用于rekey的新vault标识
    --new-vault-password-file=NEW_VAULT_PASSWORD_FILE   #新的保险库密码文件为rekey
    --vault-id=VAULT_IDS                                #要使用的保险库标识
    --vault-password-file=VAULT_PASSWORD_FILES          #库密码文件
    -v, --verbose                                       #查看执行的详细过程(-vv、-vvvv更详细)
    --version                                           #查看版本
      
    使用参数:
    encrypt (加密)
    decrypt (解密)
    create (创建)
    view (查看)
    edit (编辑)
    rekey (修改密码)

    示例如下:

    [root@Manager ~]#echo lawrence > bo.yaml
    
    #加密
    [root@Manager ~]#ansible-vault encrypt bo.yaml 
    New Vault password: 
    Confirm New Vault password: 
    Encryption successful
    [root@Manager ~]#cat bo.yaml 
    $ANSIBLE_VAULT;1.1;AES256
    36356635383935353964353133343530643163373437643736356139653031333639323332666534
    6439326336616430393936636235386637333663623864300a393563626536396134643564346635
    35386339653263613961363937643934663331613931623362396432363833343037303832333862
    3538383633653335340a386530343566653439646338663666316438613465616262356264333762
    6537
    
    #解密查看
    [root@Manager ~]#ansible-vault decrypt bo.yaml 
    Vault password: 
    Decryption successful
    [root@Manager ~]#cat bo.yaml 
    lawrence
    
    #直接查看
    [root@Manager ~]#ansible-vault encrypt bo.yaml
    New Vault password: 
    Confirm New Vault password: 
    Encryption successful
    [root@Manager ~]#ansible-vault view bo.yaml 
    Vault password: 
    lawrence
    
    #编辑
    [root@Manager ~]#ansible-vault edit bo.yaml
    Vault password: 
    [root@Manager ~]#ansible-vault view bo.yaml 
    Vault password: 
    lawrence
    test
    
    #创建加密文件
    [root@Manager ~]#ansible-vault create grace.yaml
    New Vault password: 
    Confirm New Vault password: 
    [root@Manager ~]#ansible-vault view grace.yaml 
    Vault password: 
    test
    

    四、Ansible常用模块

    4.1、ping模块

    #查看受控端
    [root@Manager ~]#ansible all --list-hosts
      hosts (2):
        172.16.93.165
        172.16.93.167
    [root@Manager ~]#ansible web --list-hosts
      hosts (1):
        172.16.93.165
    [root@Manager ~]#ansible db --list-hosts
      hosts (1):
        172.16.93.167
    
    #ping 模块
    [root@Manager ~]#ansible all -m ping
    172.16.93.167 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }
    [root@Manager ~]#ansible web -m ping
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }
    [root@Manager ~]#ansible db -m ping
    172.16.93.167 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }
    [root@Manager ~]#ansible -i /etc/ansible/hosts all -m ping
    172.16.93.167 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }
    
    #查看帮助说明
    [root@Manager ~]#ansible-doc -v ping

    4.2、command模块

    command 是ansible的默认模块, 即不指定模块的时候默认使用的模块就是command !  使用ansible自带模块执行命令 如果要用 > < | & ‘ ‘ ,最好使用shell 模块, command是不支持管道符之类的。

    image

    [root@Manager ~]#ansible all -a "date"
    172.16.93.167 | CHANGED | rc=0 >>
    Mon Jan  6 16:46:04 CST 2020
    
    172.16.93.165 | CHANGED | rc=0 >>
    Mon Jan  6 16:46:04 CST 2020
    
    [root@Manager ~]#ansible all -m command -a "date"
    172.16.93.167 | CHANGED | rc=0 >>
    Mon Jan  6 16:46:43 CST 2020
    
    172.16.93.165 | CHANGED | rc=0 >>
    Mon Jan  6 16:46:43 CST 2020
    
    #在命令执行之前, 先切换到指定的目录路径下
    [root@Manager ~]#ansible web -m command -a "chdir=/tmp pwd"
    172.16.93.165 | CHANGED | rc=0 >>
    /tmp
    
    #文件是否存在,存在就不执行,不存在就执行
    [root@Manager ~]#ansible web -m command -a "creates=/etc/hosts date"
    172.16.93.165 | SUCCESS | rc=0 >>
    skipped, since /etc/hosts exists
    
    [root@Manager ~]#ansible web -m command -a "creates=/etc/hosts123 date"
    172.16.93.165 | CHANGED | rc=0 >>
    Mon Jan  6 16:48:15 CST 2020
    
    #removes 文件是否存在,存在就执行,不存在就执行
    [root@Manager ~]#ansible web -m command -a "removes=/etc/hosts uptime"
    172.16.93.165 | CHANGED | rc=0 >>
     16:48:57 up 138 days,  2:29,  2 users,  load average: 0.00, 0.04, 0.05
    
    [root@Manager ~]#ansible web -m command -a "removes=/etc/hosts123 uptime"
    172.16.93.165 | SUCCESS | rc=0 >>
    skipped, since /etc/hosts123 does not exist

    4.3、shell模块

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

    [root@Manager ~]#ansible web -m shell -a "cat /etc/passwd|grep root"
    172.16.93.165 | CHANGED | rc=0 >>
    root:x:0:0:root:/root:/bin/bash
    operator:x:11:0:operator:/root:/sbin/nologin
    
    #shell 模块在远程执行脚本时,远程主机上一定要有相应的脚本
    [root@Manager ~]#ansible web -m shell -a "/bin/bash /tmp/test.sh"
    172.16.93.165 | FAILED | rc=127 >>
    /bin/bash: /tmp/test.sh: No such file or directorynon-zero return code

    4.4、copy模块

    把主控节点本地的文件上传同步到远程受控节点上, 该模块不支持从远程受控节点拉取文件到主控节点上。 参数选项如下:

    src:指定源文件路径,可以是相对路径,也可以是绝对路径,可以是目录(并非是必须的,可以使用content,直接生成文件内容). src即是要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用”/”来结尾,则只复制目录里的内容,如果没有使用”/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync。
    dest:指定目标文件路径,只能是绝对路径,如果src是目录,此项必须是目录. 这个是必选项!
    owner:指定属主;
    group:指定属组;
    mode:指定权限,可以以数字指定比如0644;
    content:代替src,直接往dest文件中写内容,可以引用变量,也可以直接使用inventory中的主机变量. 写后会覆盖原文件内容!
    backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
    force: 如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes ;
    directory_mode:递归的设定目录的权限,默认为系统默认权限;
    others:所有的file模块里的选项都可以在这里使用;

    测试:

    [root@Manager ~]#ansible web -m copy -a "src=~/script dest=/tmp/ backup=yes"
    [root@Manager ~]#ansible web -m copy -a "src=/etc/hosts dest=/tmp/ owner=root group=root mode=0644"
    [root@Manager ~]#ansible web -m copy -a 'src=/etc/hosts dest=/tmp/ owner=root group=root mode="u=rw,g=rw,o=rw"'
    
    #向远程受控节点文件写入内容, 把原内容覆盖掉,并备份
    [root@Manager ~]#ansible web -m copy -a 'content="hello,test" dest=/tmp/hosts backup=yes'
    172.16.93.165 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "backup_file": "/tmp/hosts.19520.2020-01-06@17:14:48~", 
        "changed": true, 
        "checksum": "5f677f1dc185b643d6f436491f1e165d4151103c", 
        "dest": "/tmp/hosts", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "bf2fcd5a98ca557c37106f400c2954be", 
        "mode": "0666", 
        "owner": "root", 
        "size": 10, 
        "src": "/root/.ansible/tmp/ansible-tmp-1578302087.54-20280675092284/source", 
        "state": "file", 
        "uid": 0
    }

    4.5、file模块

    file模块主要用于远程主机上的文件操作,file模块包含如下选项:

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

    测试:

    #创建文件
    [root@Manager ~]#ansible web -m file -a "path=/tmp/testfile state=touch mode=600 owner=root group=root"
    [root@Manager ~]#ansible web -m file -a "path=/tmp/filetest state=touch mode="u+rw,g-wx,o-rwx" owner=root group=root"
    
    #创建目录
    [root@Manager ~]#ansible web -m file -a "path=/tmp/testdir state=directory mode=755 owner=root group=root"
    #删除文件或目录
    [root@Manager ~]#ansible web -m file -a "path=/tmp/testdir state=absent"
    
    文件的软链接和硬链接
    [root@Manager ~]# ansible web -m file -a "src=/data/test dest=/opt/heihei state=link"
    [root@Manager ~]# ansible web -m file -a "src=/data/test dest=/mnt/hh state=hard" 
    [root@Manager ~]# ansible web -m file -a "src=/etc/passwd dest=/opt/heihei state=link force=yes"
     
    目录做软链接
    [root@Manager ~]# ansible web -m file -a "src=/data/haha/ dest=/root/aaa state=link"

    4.6、fetch模块

    用于从远程机器获取文件,并将其本地存储在由主机名组织的文件树中。
    src:  指定从远程控制节点上要拉取的文件, 记住: 这个只能拉取文件!!  不能拉取目录!!!  后续版本可能会支持递归提取。
    dest:  将远程节点拉取的文件保存到本地的目录路径. 例如,如果dest目录是/backup,在主机host.example.com上命名为/ etc/profile的src文件将被保存到/backup/host.example.com/etc/profile。
    flat: 允许覆盖将目标文件添加到主机名/path/to/file的默认行为。默认为no!!   如果设置为yes, 将不会显示类似172.16.60.221/root/信息. (即在dest的本机存放目录下不会创建远程节点ip命名的目录)

    #从受控点拉取文件到主控点
    [root@Manager ~]#ansible web -m fetch -a "dest=/tmp/ src=/root/appctl.sh"
    172.16.93.165 | CHANGED => {
        "changed": true, 
        "checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
        "dest": "/tmp/172.16.93.165/root/appctl.sh", 
        "md5sum": "c461a6b1b11858bbe6258ff0b9885a89", 
        "remote_checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
        "remote_md5sum": null
    }
    
    #发现dest定义的文件存放目录下会有以远程节点ip命名的目录
    [root@Manager ~]#ll /tmp/172.16.93.165/root/appctl.sh 
    -rwxr-xr-x 1 root root 2763 Jan  6 17:52 /tmp/172.16.93.165/root/appctl.sh
    
    #如果不想要从远程节点拉取过来的文件在本机存放目录里已远程节点ip命名的目录里面
    [root@Manager ~]#ansible web -m fetch -a "dest=/tmp/ src=/root/appctl.sh flat=yes"
    172.16.93.165 | CHANGED => {
        "changed": true, 
        "checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
        "dest": "/tmp/appctl.sh", 
        "md5sum": "c461a6b1b11858bbe6258ff0b9885a89", 
        "remote_checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
        "remote_md5sum": null
    }    
    [root@Manager ~]#ll /tmp/appctl.sh 
    -rwxr-xr-x 1 root root 2763 Jan  6 17:58 /tmp/appctl.sh

    4.7、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         # 以哪个用户的身份执行

    示例如下:

    #创建定时任务
    [root@Manager ~]#ansible web -m cron -a "name='test' hour='2-5' minute='*/5' day='1' month='3,4' weekday='1' job='ls -l' user=root"
    [root@Manager ~]#ansible web -m shell -a "crontab -l"
    172.16.93.165 | CHANGED | rc=0 >>
    #Ansible: test
    */5 2-5 1 3,4 1 ls -l
    
    #根据name删除定时任务
    [root@Manager ~]#ansible web -m cron -a "name=test state=absent"
    
    #--------------------------------------------------------------
    
    #没有指定name时
    [root@Manager ~]#ansible web -m cron -a "minute=* hour=* day=* month=* weekday=*  job='/bin/sh /server/scripts/test.sh'"
    [root@Manager ~]#ansible web -m shell -a "crontab -l"
    172.16.93.165 | CHANGED | rc=0 >>
    #Ansible: None
    * * * * * /bin/sh /server/scripts/test.sh
    
    #添加name
    [root@Manager ~]#ansible web -m cron -a "name='cron01' job='/bin/sh /server/scripts/test.sh'"
    [root@Manager ~]#ansible web -m shell -a "crontab -l"
    172.16.93.165 | CHANGED | rc=0 >>
    #Ansible: cron01
    * * * * * /bin/sh /server/scripts/test.sh
    
    #删除指定定时任务
    [root@Manager ~]#ansible web -m cron -a "name=cron01 state=absent"
    
    #注释相应定时任务,使定时任务失效 (disabled=yes 表示注释掉, 即无效; disabled=no 表示去掉注释, 即有效)
    [root@Manager ~]#ansible web -m cron -a "name=cron01 minute=* hour=* day=* month=* weekday=*  job='/bin/sh /server/scripts/test.sh' disabled=no"
    [root@Manager ~]#ansible web -m shell -a "crontab -l"
    172.16.93.165 | CHANGED | rc=0 >>
    #Ansible: cron01
    * * * * * /bin/sh /server/scripts/test.sh
    [root@Manager ~]#ansible web -m cron -a "name=cron01 disabled=yes"
    172.16.93.165 | FAILED! => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "msg": "You must specify 'job' to install a new cron job or variable"
    }
    [root@Manager ~]#ansible web -m cron -a "name=cron01 job='/bin/sh /server/scripts/test.sh' disabled=yes"
    [root@Manager ~]#ansible web -m shell -a "crontab -l"
    172.16.93.165 | CHANGED | rc=0 >>
    #Ansible: cron01
    #* * * * * /bin/sh /server/scripts/test.sh
    

    4.8、yum模块

    用于软件安装

    config_file:yum的配置文件 (optional)
    disable_gpg_check:关闭gpg_check (optional)
    disablerepo:不启用某个源 (optional)
    enablerepo:启用某个源(optional)
    name:要进行操作的软件包的名字,默认最新的程序包,指明要安装的程序包,可以带上版本号,也可以传递一个url或者一个本地的rpm包的路径
    state:表示是安装还是卸载的状态, 其中present、installed、latest 表示安装,  absent 、removed表示卸载删除;  present默认状态, laster表示安装最新版本.

    示例如下:

    安装httpd
    [root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=latest'
    [root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=present'
    [root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=installed'
     
    [root@ansible-server ~]# ansible web-nodes -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
    [root@ansible-server ~]# ansible web-nodes -m yum -a 'name="@Development tools" state=present'
     
    卸载httpd
    [root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=absent'
    [root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=removed'

    4.9、service服务

    管理服务的模块, service管理的服务必须是yum安装的服务, 即默认的系统服务脚本。编译安装的服务不好使用service模块管理.

    name: 服务名称;
    state:  started/stopped/restarted/reloaded;
    enabled: true/false;
    runlevel: 运行级别;
    sleep: 如果执行了restarted,在stop和start之间沉睡几秒;
    arguments: 给命令行提供一些选项;

    示例如下:

    [root@ansible-server ~]# ansible web-nodes -m service -a "name=sshd state=restarted"
    [root@ansible-server ~]# ansible web-nodes -m service -a "enabled=on name=httpd state=started"
    [root@ansible-server ~]# ansible web-nodes -m service -a "enabled=yes name=httpd state=started"
    [root@ansible-server ~]# ansible web-nodes -m service -a "name=httpd state=reloaded"   
    [root@ansible-server ~]# ansible web-nodes -m service -a "name=httpd state=stopped"

    4.10、systemd模块

    service模块适用于service管理程序的情况,如果是centos7系统,使用systemctl管理程序的话,可以使用systemd模块。systemctl可以控制程序启/停,reload,开机启动,观察程序状态(status)等。systemd模块的主要参数如下:

    name:  服务名称,例如crond.service,最好带上后缀 .service
    state:  需要的操作,started/stopped/restarted/reloaded
    enabled:是否需要开机启动
    daemon_reload:systemd 读取配置文件,每次修改了文件,最好都运行一次,确保应用了

    使用systemd前,如果是自己生成的配置文件,需要先放到/etc/systemd/system/ 目录中,然后使用daemon_reload 中就可以了,注意不要和系统之前自带的配置冲突,例如之前已经用yum安装过redis或haproxy 之类的,已经存在相应的服务了,需要自行判断要使用哪个文件。也可以使用.include 引用其他文件,具体参考systemd文档 (查看命令"ansible-doc systemd")。systemd模块在ansible的yml文件中配置示例如下:

    - name: Make sure a service is running
      systemd: state=started name=httpd
     
    - name: stop service cron on debian, if running
      systemd: name=cron state=stopped
     
    - name: restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
      systemd:
        state: restarted
        daemon_reload: yes
        name: crond
     
    - name: reload service httpd, in all cases
      systemd:
        name: httpd
        state: reloaded
     
    - name: enable service httpd and ensure it is not masked
      systemd:
        name: httpd
        enabled: yes
        masked: no
     
    - name: enable a timer for dnf-automatic
      systemd:
        name: dnf-automatic.timer
        state: started
        enabled: True
     
    - name: just force systemd to reread configs (2.4 and above)
      systemd: daemon_reload=yes

    4.11、user模块

    用来管理用户账号,参数如下:

    home: 指定用户的家目录, 需要与createhome配合使用。
    groups: 指定用户的属组。
    uid: 指定用的uid。
    password: 设定用户密码, password参数需要接受md5加密后的值. 特别注意: 指定password参数时, 不能使用明文密码, 因为后面这一串密码会被直接传送到被管理主机的/etc/shadow文件中, 所以需要先将密码字符串进行加密处理, 然后将得到的字符串放到password中即可。
    name: 指定用户名。
    system: 是否为系统用户。 表示默认创建为普通用户, 而非系统用户, 指定是用yes. 也就是说yes是默认创建为普通用户, 而非系统用户;
    update_password: 修改用户密码, 其中always: 新密码和旧密码不同时进行修改; on_create: 为新创建的用户指定密码.
    create_home: 创建家目录, 其中yes表示默认项, 即创建用户默认是有家目录的; no表示创建用户时不创建家目录.
    remove: 其中yes是删除用户家目录, 需要指定此参数; no是默认项, 删除用户时默认不删除用户的家目录. 当state=absent时, remove=yes则表示连同家目录一起删除, 等价于userdel -r。
    state: 用户状态是创建还是删除. (present, absent) ;默认为present; 其中present表示添加用户; absent表示删除用户
    shell: 指定用户的shell环境。
    generate_ssh_key: 是否为相关用户生成SSH密钥。 这不会覆盖现有的SSH密钥。
    ssh_key_bits: 可选择指定要创建的SSH密钥中的位数。
    ssh_key_passphrase: 设置SSH密钥的密码。 如果没有提供密码, SSH密钥将默认没有密码。
    ssh_key_file: 指定SSH密钥文件名(可选). 如果这是一个相对的文件名, 那么它将是相对于用户的主目录。
    ssh_key_type: 指定要生成的SSH密钥的类型(可选). 可用的SSH密钥类型将取决于目标主机上的实现。

    示例如下:

    使用bash shell添加用户haha,将组"管理员"和"开发人员"附加到用户组
    [root@ansible-server ~]# ansible web-nodes -m user -a "name=haha shell=/bin/bash groups=admins,developers append=yes"
      
    增加用户anhui (先对密码做明文到密文的处理)
    [root@ansible-server ~]# echo "anhui@123" | openssl passwd -1 -stdin
    $1$rj74jCVy$NDW80bgY0DUTuHUlSunVv1
    [root@ansible-server ~]# ansible web-nodes -m user -a 'name=anhui system=yes password=$1$rj74jCVy$NDW80bgY0DUTuHUlSunVv1 state=present'
      
    删除用户anhui
    [root@ansible-server ~]# ansible web-nodes -m user -a 'name=anhui remove=yes state=absent' 
      
    更新用户kevin的密码 (先对新密码kevin@bj123做明文到密文的处理)
    [root@ansible-server ~]# echo "kevin@bj123"| openssl passwd -1 -stdin 
    $1$5X5bH5.J$RwE6o6g6bX953W7vAaizv/
    [root@ansible-server ~]# ansible web-nodes -m user -a 'name=kevin update_password=always password=$1$5X5bH5.J$RwE6o6g6bX953W7vAaizv/'
      
    在~/.ssh/id_rsa中为用户bobo创建一个2048位的SSH密钥
    [root@ansible-server ~]# ansible web-nodes -m user -a 'name=bobo generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa'
     
    [root@ansible-server ~]# ansible web-nodes -m group -a "name=yang gid=888"
    [root@ansible-server ~]# ansible web-nodes -m user -a "name=yang uid=888 group=888 shell=/sbin/nologin create_home=no"

    可以使用debug模块将明文密码进行hash加密,然后进行用户创建

    [root@Manager ~]#ansible localhost -m debug -a "msg={{ 'bgx' | password_hash('sha512', 'salt') }}"
    localhost | SUCCESS => {
        "msg": "$6$salt$WP.Kb1hMfqJG7dtlBltkj4Um4rVhch54R5JCi6oP73MXzGhDWqqIY.JkSOnIsBSOeXpKglY7gUhHzY4ZtySm41"
    }
    [root@Manager ~]# ansible web -m user -a 'name=lawrence password=$6$salt$WP.Kb1hMfqJG7dtlBltkj4Um4rVhch54R5JCi6oP73MXzGhDWqqIY.JkSOnIsBSOeXpKglY7gUhHzY4ZtySm41 create_home=yes shell=/bin/bash'
    172.16.93.165 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "comment": "", 
        "create_home": true, 
        "group": 1003, 
        "home": "/home/lawrence", 
        "name": "lawrence", 
        "password": "NOT_LOGGING_PASSWORD", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 1003
    }

    4.12、group模块

    gid: 指定用的gid。
    name: 指定用户名。
    state: 是创建还是删除, (present,absent);
    system: 如果是,则表示创建的组是系统组;

    示例如下:

    [root@ansible-server ~]# ansible web-nodes -m group -a "name=huoqiu state=present"
    [root@ansible-server ~]# ansible web-nodes -m group -a "name=chenzun gid=897 state=present" 
    [root@ansible-server ~]# ansible web-nodes -m group -a "name=huoqiu state=absent"

    4.13、script模块

    将本机的脚本在被管理端的机器上运行。该模块直接指定脚本的路径即可

    需要注意: 使用scripts模块,不用将脚本传输到远程节点,脚本本身不用进行授权,即可利用script模块执行。直接执行脚本即可,不需要使用sh 或者 /bin/bash

    [root@Manager ~]#cat /tmp/df.sh 
    #!/bin/bash
    date >> /tmp/disk_total.log
    df -lh >> /tmp/disk_total.log
    
    [root@Manager ~]#ansible web -m script -a "/tmp/df.sh"
    172.16.93.165 | CHANGED => {
        "changed": true, 
        "rc": 0, 
        "stderr": "Shared connection to 172.16.93.165 closed.
    ", 
        "stderr_lines": [
            "Shared connection to 172.16.93.165 closed."
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
    [root@Manager ~]#ansible web -a "cat /tmp/disk_total.log"
    172.16.93.165 | CHANGED | rc=0 >>
    Wed Jan  8 10:26:22 CST 2020
    Filesystem      Size  Used Avail Use% Mounted on
    /dev/vda1       197G  5.5G  184G   3% /
    devtmpfs         16G     0   16G   0% /dev
    tmpfs            16G     0   16G   0% /dev/shm
    tmpfs            16G  560K   16G   1% /run
    tmpfs            16G     0   16G   0% /sys/fs/cgroup
    /dev/vdc1       400G  119G  282G  30% /data/mysql_db
    tmpfs           3.2G     0  3.2G   0% /run/user/0

    4.14、setup模块

    用于收集远程受控主机的一些基本信息. 

    filter参数:用于进行条件过滤。如果设置,仅返回匹配过滤条件的信息

    #打印受控机全部信息
    [root@Manager ~]#ansible web -m setup
    
    #获取ip地址
    [root@Manager ~]#ansible web -m setup -a "filter=ansible_all_ipv4_addresses"
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "ansible_all_ipv4_addresses": [
                "172.16.93.165"
            ], 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false
    }
    
    #获取内存信息
    [root@Manager ~]#ansible web -m setup -a "filter=ansible_memory_mb"
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "ansible_memory_mb": {
                "nocache": {
                    "free": 27947, 
                    "used": 4065
                }, 
                "real": {
                    "free": 15806, 
                    "total": 32012, 
                    "used": 16206
                }, 
                "swap": {
                    "cached": 0, 
                    "free": 0, 
                    "total": 0, 
                    "used": 0
                }
            }, 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false
    }
    
    #通过通配符实现模糊匹配,比如以”mb”关键字结尾的信息
    [root@Manager ~]#ansible web -m setup -a "filter=*mb"
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "ansible_memfree_mb": 15806, 
            "ansible_memory_mb": {
                "nocache": {
                    "free": 27947, 
                    "used": 4065
                }, 
                "real": {
                    "free": 15806, 
                    "total": 32012, 
                    "used": 16206
                }, 
                "swap": {
                    "cached": 0, 
                    "free": 0, 
                    "total": 0, 
                    "used": 0
                }
            }, 
            "ansible_memtotal_mb": 32012, 
            "ansible_swapfree_mb": 0, 
            "ansible_swaptotal_mb": 0, 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false
    }
    
    #获取信息保存至文件
    [root@Manager ~]#ansible web -m setup -a 'filter="*mem*"' --tree /tmp/facts
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "ansible_memfree_mb": 15806, 
            "ansible_memory_mb": {
                "nocache": {
                    "free": 27947, 
                    "used": 4065
                }, 
                "real": {
                    "free": 15806, 
                    "total": 32012, 
                    "used": 16206
                }, 
                "swap": {
                    "cached": 0, 
                    "free": 0, 
                    "total": 0, 
                    "used": 0
                }
            }, 
            "ansible_memtotal_mb": 32012, 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false
    }
    [root@Manager ~]#cd /tmp/facts/
    [root@Manager facts]#ls
    172.16.93.165
    [root@Manager facts]#cat 172.16.93.165   #JSON格式
    {"ansible_facts": {"ansible_memfree_mb": 15806, "ansible_memory_mb": {"nocache": {"free": 27947, "used": 4065}, "real": {"free": 15806, "total": 32012, "used": 16206}, "swap": {"cached": 0, "free": 0, "total": 0, "used": 0}}, "ansible_memtotal_mb": 32012, "discovered_interpreter_python": "/usr/bin/python"}, "changed": false}

    其他常用信息:

    ansible_all_ipv4_addresses:仅显示ipv4的信息。
    ansible_devices:仅显示磁盘设备信息。
    ansible_distribution:显示是什么系统,例:centos,suse等。
    ansible_distribution_major_version:显示是系统主版本。
    ansible_distribution_version:仅显示系统版本。
    ansible_machine:显示系统类型,例:32位,还是64位。
    ansible_eth0:仅显示eth0的信息。
    ansible_hostname:仅显示主机名。
    ansible_kernel:仅显示内核版本。
    ansible_lvm:显示lvm相关信息。
    ansible_memtotal_mb:显示系统总内存。
    ansible_memfree_mb:显示可用系统内存。
    ansible_memory_mb:详细显示内存情况。
    ansible_swaptotal_mb:显示总的swap内存。
    ansible_swapfree_mb:显示swap内存的可用内存。
    ansible_mounts:显示系统磁盘挂载情况。
    ansible_processor:显示cpu个数(具体显示每个cpu的型号)。
    ansible_processor_vcpus:显示cpu个数(只显示总的个数).

    4.15、selinux模块

    管理远程受控节点的selinux的模块

    [root@Manager ~]#ansible web -m selinux -a "state=disabled"
    172.16.93.165 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "configfile": "/etc/selinux/config", 
        "msg": "", 
        "policy": "targeted", 
        "reboot_required": false, 
        "state": "disabled"
    }

    4.16、find模块

    帮助在被管理的受控主机中查找符合条件的文件,就像 find 命令一样

    paths:  必须参数,指定在哪个目录中查找文件,可以指定多个路径,路径间用逗号隔开,此参数有别名,使用别名 path 或者别名 name 可以代替 paths。
    recurse: 默认情况下,只会在指定的目录中查找文件,也就是说,如果目录中还包含目录,ansible 并不会递归的进入子目录查找对应文件,如果想要递归的查找文件,需要使用 recurse 参数,当 recurse 参数设置为 yes 时,表示在指定目录中递归的查找文件。
    hidden: 默认情况下,隐藏文件会被忽略,当 hidden 参数的值设置为 yes 时,才会查找隐藏文件。
    file_type: 默认情况下,ansible 只会根据条件查找”文件”,并不会查找”目录”或”软链接”等文件类型,如果想要指定查找的文件类型,可以通过 file_type 指定文件类型,可指定的文件类型有 any、directory、file、link 四种。
    patterns: 使用此参数指定需要查找的文件名称,支持使用 shell(比如通配符)或者正则表达式去匹配文件名称,默认情况下,使用 shell 匹配对应的文件名,如果想要使用 python 的正则去匹配文件名,需要将 use_regex 参数的值设置为 yes。
    use_regex:默认情况下,find 模块不会使用正则表达式去解析 patterns 参数中对应的内容,当 use_regex 设置为 yes 时,表示使用 python 正则解析 patterns 参数中的表达式,否则,使用 glob 通配符解析 patterns 参数中的表达式。
    contains:使用此参数可以根据文章内容查找文件,此参数的值为一个正则表达式,find 模块会根据对应的正则表达式匹配文件内容。
    age: 使用此参数可以根据时间范围查找文件,默认以文件的 mtime 为准与指定的时间进行对比,比如,如果想要查找 mtime 在3天之前的文件,那么可以设置 age=3d,如果想要查找 mtime 在3天以内的文件,可以设置 age=-3d,这里所说的3天是按照当前时间往前推3天,可以使用的单位有秒(s)、分(m)、时(h)、天(d)、星期(w)。
    age_stamp: 文件的时间属性中有三个时间种类,atime、ctime、mtime,当我们根据时间范围查找文件时,可以指定以哪个时间种类为准,当根据时间查找文件时,默认以 mtime 为准。
    size: 使用此参数可以根据文件大小查找文件,比如,如果想要查找大于3M的文件,那么可以设置 size=3m,如果想要查找小于50k的文件,可以设置 size=-50k,可以使用的单位有 t、g、m、k、b。
    get_checksum: 当有符合查找条件的文件被找到时,会同时返回对应文件的 sha1校验码,如果要查找的文件比较大,那么生成校验码的时间会比较长

    示例如下:

    #在受控主机的 /data目录中查找文件内容中包含wang字符串的文件,隐藏文件会被忽略,不会进行递归查找。
    [root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data contains=".*wang.*""
     
    #在受控主机的的 /data目录以及其子目录中查找文件内容中包含wang字符串的文件,隐藏文件会被忽略。
    [root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data contains=".*wang.*" recurse=yes"
     
    #在受控主机的的 /data目录中查找以 .sh 结尾的文件,包括隐藏文件,但是不包括目录或其他文件类型,不会进行递归查找。
    [root@ansible-server ~]# ansible web-nodes -m find -a 'paths=/data patterns="*.sh" file_type=any hidden=yes'
     
    #在受控主机的的 /data目录中查找以 .sh 结尾的文件,只不过patterns对应的表达式为正则表达式,查找范围包括隐藏文件,包括所有文件类型,但是不会进行递归查找,不会对/data目录的子目录进行查找。
    [root@ansible-server ~]# ansible web-nodes -m find -a 'paths=/data patterns=".*.sh" use_regex=yes file_type=any hidden=yes' 
     
    #在受控主机的的 /data目录中以及其子目录中查找 mtime 在1天以内的文件,不包含隐藏文件,不包含目录或软链接文件等文件类型。
    [root@ansible-server ~]# ansible web-nodes -m find -a "path=/data age=-1d recurse=yes"
     
    在受控主机的的 /data目录中以及其子目录中查找大于 2g 的文件,不包含隐藏文件,不包含目录或软链接文件等文件类型。
    [root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data size=2g recurse=yes"
     
    在受控主机的的 /data目录中以及其子目录中查找以 .sh 结尾的文件,并且返回符合条件文件的 sha1 校验码,包括隐藏文件
    [root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data patterns=*.sh get_checksum=yes hidden=yes recurse=yes"

    4.17、mount模块

    在远程受控节点上挂载文件系统。可用参数

    present: 开机挂载,仅将挂载配置写入/etc/fstab(不常用)
    mounted: 挂载设备,并将配置写入/etc/fstab
    unmounted: 卸载设备,不会清除/etc/fstab写入的配置
    absent: 卸载设备,会清理/etc/fstab写入的配置

    示例如下:

    将受控节点的/dev/sd0设备挂载到/mnt/data目录上, 文件格式为ext4, 只读属性
    [root@ansible-server ~]# ansible web-nodes -m mount -a "path=/mnt/data src=/dev/sd0 fstype=ext4 ots=ro state=present"
     
    仅将挂载的配置写入/etc/fstab,并不会执行挂载操作
    [root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=present"
     
    临时挂载设备,并将挂载信息写入/etc/fstab
    [root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=mounted"
     
    临时卸载,不会清理/etc/fstab
    [root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=unmounted"
     
    卸载,不仅临时卸载,同时会清理/etc/fstab
    [root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=absent"
    
    [root@m01 ~]# ansible oldboy -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=present"
    [root@m01 ~]# ansible web -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=mounted"
    [root@m01 ~]# ansible web -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=unmounted"
    [root@m01 ~]# ansible web -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=absent"

    4.18、stat模块

    获取远程文件的状态信息,包括atime,ctime,mtime,md5,uid,gid等信息

    [root@Manager ~]#ansible web -m stat -a "path=/tmp/testfile"

    4.19、hostname模块

    使用hostname模块修改远程节点的主机名时, 最好指明远程单节点ip地址进行设置主机名了. 因为不同节点的主机名不一样

    [root@ansible-server ~]# ansible 172.16.60.213 -m hostname -a 'name="web-node03"'

    4.20、unarchive模块

    解压文件:

    copy: 在解压文件之前,是否先将文件复制到远程主机,默认为yes。若为no,则要求目标主机上压缩包必须存在。
    creates: 指定一个文件名,当该文件存在时,则解压指令不执行
    dest: 远程主机上的一个路径,即文件解压的绝对路径。 必须是一个目录路径!
    group: 解压后的目录或文件的属组;
    list_files: 如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项;
    mode: 解压后文件的权限;
    src: 如果copy为yes,则需要指定压缩文件的源路径;
    owner: 解压后文件或目录的属主;
    
    经测试, 该模块解压时识别zip, tgz , tar.gz, tar.bz2 格式的压缩包, gzip格式的测试时不支持.

    示例如下:

    #将控制机上/usr/local/src/nginx.tgz解压缩到/data/www中
    [root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=/usr/local/src/nginx.tgz dest=/data/www/"
     
    #解压远程受控节点上已存在的文件
    [root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=/root/file.zip dest=/usr/local remote_src=yes"
     
    #解压文档需要下载的文件(2.0中添加)
    [root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=https://example.com/example.zip dest=/usr/local/bin remote_src=yes"

    4.21、lineinfile模块

    用于对远程受控节点的文件编辑模块. 主要选项有:

    path: 指定要修改的配置文件, 包括:
             regexp:匹配要修改的内容
             line:要增加或者修改的内容
    state: 状态, 包括:
             absent:表示删除,当匹配到时进行删除
             present:表示增加,当匹配到时进行修改,当没有匹配到时在最后增加一行,默认为此项
    backrefs: 该参数值包括:
             no:表示如果没有匹配到,则增加line;如果匹配成功,则替换line;
             yes:表示如果没有匹配到,则不变line;如果匹配成功,则替换line;
    backup: 该参数值包括:
             no:表示如果没有匹配到,则增加line;如果匹配成功,则替换line;不备份原文件
             yes:表示如果没有匹配到,则增加line;如果匹配成功,则替换line;备份原文件
    insertafter(匹配的是此行): 在匹配到的行之后添加一行.  (经测试, 发现是匹配到的行的最后一行的后面添加一行)
    insertbefore(匹配的是此行): 在匹配到的行之前添加一行.  (经测试, 发现是匹配到的行的最后一行的前面添加一行)

    示例如下:

    #将远程受控节点的/data/test文件中的"123"字段修改为"lawrence"
    [root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile regexp="123" line="lawrence" backrefs=no"
    
    #匹配到的行后增加一行
    [root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile insertafter="lawrence" line="huihui""
    
    #匹配到的行前增加一行
    [root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile insertbefore="lawrence" line="test""
    
    #删除匹配到的行并备份原文件
    [root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile regexp="lawrence" state=absent backup=yes"
    

    4.22、get_url模块

    该模块主要用于从http、ftp、https服务器上下载文件(类似于wget), 主要有如下选项:

    sha256sum: 下载完成后进行sha256 check;
    timeout: 下载超时时间, 默认10s
    url: 下载的URL
    url_password、url_username: 主要用于需要用户名密码进行验证的情况
    dest: 将文件下载到哪里的绝对路径。如果dest是目录, 则使用服务器提供的文件名, 或者如果没有提供, 将使用远程服务器上的URL的基本名称。
    headers: 以格式“key: value, key: value”为请求添加自定义HTTP标头

    示例如下:

    [root@ansible-server ~]# ansible web-nodes -m get_url -a "url=http://lan.Okay686.com/RDPWrap-v1.6.1.zip dest=/usr/local/src/"
    [root@ansible-server ~]# ansible web-nodes -m get_url -a "url=http://10.0.8.50/ops.sh  dest=/opt/shell.sh mode=0440"
    [root@ansible-server ~]# ansible web-nodes -m get_url -a 'url=http://10.0.8.50/ops.sh dest=/opt/shell.sh headers="key:value,key:value"' 
    [root@ansible-server ~]# ansible web-nodes -m get_url -a 'url=http://10.0.8.50/ops.sh dest=/opt/shell.sh checksum=sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c'
    
    [root@Manager ~]#ansible web -m get_url -a "url=http://XXX:81/sc/service/about/rc-service.log dest=/tmp url_username=username url_password=password"

    4.21、template模块

    基于模板方式生成一个文件复制到远程主机(template使用Jinjia2格式作为文件模版,进行文档内变量的替换的模块。它的每次使用都会被ansible标记为”changed”状态。)

    backup: 如果原目标文件存在,则先备份目标文件
    src: 在ansible控制器上的Jinja2格式化模板的路径。 这可以是相对或绝对的路径。
    dest: 将模板渲染到远程机器上的位置。
    force: 是否强制覆盖,默认为yes
    owner: 目标文件属主
    group: 目标文件属组
    mode: 目标文件的权限模式,模式可以被指定为符号模式(例如,u + rwx或u = rw,g = r,o = r)

    示例如下:

    [root@ansible-server ~]# ansible web-nodes -m template -a "src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel  mode=0644"
     
    #同样的例子,但使用等效于0644的符号模式
    [root@ansible-server ~]# ansible web-nodes -m template -a "src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode="u=rw,g=r,o=r""

    4.22、synchronize模块

    这个模块是使用rsync同步文件,将主控方目录推送到指定受控节点的目录下。其参数如下:

    delete: 删除不存在的文件,delete=yes 使两边的内容一样(即以推送方为主),默认no
    src: 要同步到目的地的源主机上的路径; 路径可以是绝对的或相对的。如果路径使用”/”来结尾,则只复制目录里的内容,如果没有使用”/”来结尾,则包含目录在内的整个内容全部复制
    dest:目的地主机上将与源同步的路径; 路径可以是绝对的或相对的。
    dest_port:默认目录主机上的端口 ,默认是22,走的ssh协议。
    mode: push或pull,默认push,一般用于从本机向远程主机上传文件,pull 模式用于从远程主机上取文件。
    rsync_opts:通过传递数组来指定其他rsync选项。

    示例如下:

    将主控节点上/data/kevin目录同步到受控节点的/home目录下
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin dest=/home'
     
    将主控节点上/data/kevin/test.file文件同步到受控节点的/opt目录下
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/test.file dest=/opt'
     
    将主控节点上/data/kevin/test.file文件同步到受控节点的/root/bobo.file文件
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/test.file dest=/root/bobo.file'
     
    将主控节点上/opt/同步到受控节点的/opt/目录, 使受控节点保持和主控节点的opt目录一致, 不一样的就删除! 默认delete=no
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/opt/ dest=/opt/ delete=yes'
     
    注意命令中要加"/", 如果不加"/", 则主控节点的opt目录就同步到受控节点的/opt目录下即, 即/opt/opt
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/opt dest=/opt delete=yes' 
     
    将主控节点上/data/kevin目录同步到受控节点的/mnt/www目录下. 但是bobo目录排除在外!  rsync_opts可以进行多次传递.
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/ dest=/mnt/www/ rsync_opts="--no-motd" rsync_opts="--exclude=bobo"'
     
    强制两边同步保持一致! 跟主控节点源目录保持一致!
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/ dest=/mnt/www/ rsync_opts="--no-motd" rsync_opts="--exclude=bobo" delete=yes'
     
    从远程受控节点上将/usr/local/src/grace.file文件拉取到主控节点的/root目录下
    [root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/usr/local/src/grace.file dest=/root/ rsync_opts="-avpgolr" mode=pull '
    
    #指定sshd端口
    [root@Manager ~]#ansible web -m synchronize -a "src=/root/script dest=/tmp dest_port=2812"
    172.16.93.165 | CHANGED => {
        "changed": true, 
        "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh=/usr/bin/ssh -S none -o Port=2812 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /root/script 172.16.93.165:/tmp", 
        "msg": ".d..t...... script/
    ", 
        "rc": 0, 
        "stdout_lines": [
            ".d..t...... script/"
        ]
    }
    
    synchronize 模块相比copy模块来说, 同步速度增加很多.

    4.23、raw模块

    raw, shell, command三个模块都能调用对象机器上的某条指令或者某个可执行文件。raw和shell模块很像, 都支持管道; command模块不支持管道.raw模块执行的是系统原始命令, 执行后会主动关闭到被控制节点的连接!

    [root@Manager ~]#ansible web -m raw -a "hostname"
    172.16.93.165 | CHANGED | rc=0 >>
    test-mysqldb
    Shared connection to 172.16.93.165 closed.
    
    [root@Manager ~]#ansible web -m raw -a "cat /etc/passwd|grep root"
    172.16.93.165 | CHANGED | rc=0 >>
    root:x:0:0:root:/root:/bin/bash
    operator:x:11:0:operator:/root:/sbin/nologin
    Shared connection to 172.16.93.165 closed.
    
  • 相关阅读:
    prometheus TSDB和外部存储系统
    Prometheus时序数据
    Prometheus简介
    Docker网络
    Ingress
    CRI和多容器运行时
    K8s容器存储接口(CSI)介绍
    EasyNVR视频广场点击视频后切换码流才能播放是什么原因?
    EasyNVR更新H265转H264模块内存增长且显示占用高如何解决?
    EasyNVR拉公网RTSP流失败问题调试和解决
  • 原文地址:https://www.cnblogs.com/hujinzhong/p/12155691.html
Copyright © 2011-2022 走看看