ansible安装与使用

ansible:自动化的一个程序
自动化:减轻运维工作人员压力,提高效率,实现批量部署。
系统自动化:pxe+ks(kickstart)
程序自动化:ansible saltack puppet
区别:
puppet: 基于ruby开发的 支持多系统 支持1000台以上
saltstack: 基于python开发的 支持统一管理 比较轻量级 支持1000台以上
ansible: 基于python开发的 使用ssh协议进行管理 支持100太以上
架构:
puppet/saltstack: c/s(client/server)需要客户端和服务端同时安装服务
ansible: 无客户端模式 服务器安装此程序即可
监控自动化:zabbix 天兔
代码自动化:jenkins
ansible特点:

1、无客户端模式 只是在服务端安装服务
2、通过ssh协议来和客户端进行联系
3、服务端分发任务使用模块来实现

ansible核心模块:
1、ansible core 内核
2、host inventory 主机清单
3、connection plugins ssh
4、playbook 剧本 role角色
5、core modules 核心模块
6、custom modules 自定义模块(需要开发来实现)
www.ansible.com 官网
ansible在中国社区的官网
ansible和远程主机有链接是因为ssh协议 ansible要对远程主机进行登录
ssh免密登录的原理:
主控端生成一对密钥,将公钥传递到远程主机上,当主控端想要连接远程主机时,远程主机会随机发送一 串字符给主控端,主
控端将这串字符用私钥加密,返回给远程主机,远程主机使用公钥将加密的字符解密,如果和自己生成的字符一 致,则验证通
过,可以进行登录

一、ansible两种安装方法

1、以下任意一种操作做完之后在进行其他的操作
1)不联网的安装方式:

[root@CentOS1 ~]# mkdir app
[root@CentOS1 ~]# createrepo /root/app
[root@CentOS1 ~]# cd /etc/yum.repos.d/
[root@CentOS1 yum.repos.d]# vim ansible.repo
#添加	确保只有这一个yum源
[ansible]
name=ansibel
baseurl=file:///root/app
enabled=1
gpgcheck=0
[root@CentOS1 yum.repos.d]# yum -y install ansible

2)联网的安装方式:

[root@CentOS1 yum.repos.d]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@CentOS1 yum.repos.d]# yum -y install ansible

2、编辑清单文件

[root@CentOS1 ~]# vim /etc/ansible/hosts
#在末尾处添加
[web]
192.168.1.2

ssh免密登录

[root@CentOS1 ~]# ssh root@192.168.1.2	#被操控的主机
[root@CentOS1 ansible]# ssh-keygen	#直接四此回车即可
[root@CentOS1 ~]# ssh-copy-id root@192.168.1.2	#将公钥传送到被操控主机中实现免密登录
[root@CentOS1 ansible]# ssh root@192.168.1.2	#被操控主机的IP

二、ansible的操作及模块

ansible hosts (主机清单) -m module_ name (模块名) -a job (对后端主机进行什么样的操作)
绿色 执行成功
红色 执行失败
黄色 执行成功 并且对后端的主机进行了修改
紫色 警告

[root@CentOS1 ~]# ansible-doc -s ping	#查看模块帮助信息	-s 后是模块名
- name: Try to connect to host, verify a usable python and return `pon
  ping:
      data:                  # Data to return for the `ping' return va
                               this parameter is
                               set to `crash',
                               the module will
                               cause an
                               exception.

[root@CentOS1 ~]# ansible-doc -l	#查看所有模块信息
[root@CentOS1 ~]# ansible 192.168.1.2 -m ping	#-m 后跟的是模块名称
192.168.1.2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@CentOS1 ~]# ansible web -m ping	#wed清单名称
192.168.1.2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
[root@CentOS1 ~]# ansible all -m ping	#all所有清单中的主机
192.168.1.2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

command:在远程主机上执行指定的命令 不能使用特殊符号

[root@CentOS1 ~]# ansible all -m command -a "ls /home"
192.168.1.2 | SUCCESS | rc=0 >>
centos2

1、chdir 切换目录

#先切换目录在查看
[root@CentOS1 ~]# ansible all -m command -a "chdir=/home ls"
192.168.1.2 | SUCCESS | rc=0 >>
centos2

2、creates:当指定文件存在时, 命令不执行当指定文件不存在时,命令执行

[root@CentOS1 ~]# ansible all -m command -a "creates=/etc/fstab ls /home"
192.168.1.3 | SUCCESS | rc=0 >>
skipped, since /etc/fstab exists

192.168.1.2 | SUCCESS | rc=0 >>
skipped, since /etc/fstab exists

[root@CentOS1 ~]# ansible all -m command -a "creates=/etc/fstab123 ls /home"
192.168.1.2 | SUCCESS | rc=0 >>
centos2

3、removes:当指定的文件存在时,命令执行当指定文件不存在时命令不执行

[root@CentOS1 ~]# ansible all -m command -a "removes=/etc/fstab ls /home"
192.168.1.2 | SUCCESS | rc=0 >>
centos2

[root@CentOS1 ~]# ansible all -m command -a "removes=/etc/fstab123 ls /home"
192.168.1.2 | SUCCESS | rc=0 >>
skipped, since /etc/fstab123 does not exist

4、shell:万能模块 特殊符号也可以执行

[root@CentOS1 ~]# ansible all -m shell -a "touch /home/test"	#创建test文件
 [WARNING]: Consider using file module with state=touch rather than running
touch

192.168.1.2 | SUCCESS | rc=0 >>
[root@CentOS1 ~]# ansible all -m shell -a "echo '123' >/home/test"	#将123重定向到test文件中
192.168.1.3 | SUCCESS | rc=0 >>
[root@CentOS1 ~]# ansible all -m shell -a "cat /home/test"	#列出test文件中的信息
192.168.1.2 | SUCCESS | rc=0 >>
123

5、user:用户模块 如果没有你所要创建的用户则创建用户 有则会列出test用户的详细信息

[root@CentOS1 ~]# ansible all -m user -a "name=test"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1001, 
    "home": "/home/test", 
    "name": "test", 
    "shell": "/bin/bash", 
    "state": "present", 
    "stderr": "useradd:警告:此主目录已经存在。\n不从 skel 目录里向其中复制任何文件。\n", 
    "stderr_lines": [
        "useradd:警告:此主目录已经存在。", 
        "不从 skel 目录里向其中复制任何文件。"
    ], 
    "system": false, 
    "uid": 1001
}
[root@CentOS1 ~]# ansible all -m user -a "name=test"
192.168.1.2 | SUCCESS => {
    "append": false, 
    "changed": false, 
    "comment": "", 
    "group": 1001, 
    "home": "/home/test", 
    "move_home": false, 
    "name": "test", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1001
}

参数:

  • uid:指定用户的uid
  • group:指定用户的基本组
  • groups:指定用户的附加组
  • append=yes:增量增加附加组 相当于把用户添加到另- - 个附加组中
  • append=no:全量添加附加组 相当于只设置一个附加组

5.1给用户指定uid

[root@CentOS1 ~]# ansible all -m user -a "uid=1030 name=test"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1030, 
    "home": "/home/test", 
    "name": "test", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1030
}

5.2指定基本组

[root@CentOS1 ~]# ansible all -m user -a "name=test group=test"
192.168.1.2 | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 1001, 
    "home": "/home/test", 
    "move_home": false, 
    "name": "test", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1030
}

5.3指定附加组

[root@CentOS1 ~]# ansible all -m user -a "name=test groups=test"
192.168.1.2 | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 1001, 
    "groups": "test", 
    "home": "/home/test", 
    "move_home": false, 
    "name": "test", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1030
}

5.4增量添加附加组

[root@CentOS1 ~]# ansible all -m user -a " name=test group=test append=yes"
192.168.1.2 | SUCCESS => {
    "append": true, 
    "changed": false, 
    "comment": "", 
    "group": 1030, 
    "home": "/home/test", 
    "move_home": false, 
    "name": "test", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1001
}

5.5全量添加附加组

[root@CentOS1 ~]# ansible all -m user -a " name=test group=test append=no"
192.168.1.2 | SUCCESS => {
    "append": false, 
    "changed": false, 
    "comment": "", 
    "group": 1030, 
    "home": "/home/test", 
    "move_home": false, 
    "name": "test", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1001
}

5.6state= absent:删除用户默认不删除家目录

[root@CentOS1 ~]# ansible all -m user -a "name=test state=absent"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "test", 
    "remove": false, 
    "state": "absent"
}

5.7remove=yes:删除用户的同时删除掉家目录

[root@CentOS1 ~]# ansible all -m user -a "name=test state=absent remove=yes"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "123", 
    "remove": true, 
    "state": "absent"
}

6、password:给用户添加密码 修改密码

[root@CentOS1 ~]# yum -y install openssl-devel
root@CentOS1 ~]# openssl passwd -1(数字1) 123.com	#使用MD5加密算法生成密码	
[root@CentOS1 ~]# ansible all -m user -a 'name=test password=$1$xwIV9a.B$O9tChBayLN2pW.iSkrRv11'	#给用户添加密码	需要使用单引号不可以用双引号
192.168.1.2 | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 1001, 
    "home": "/home/test", 
    "move_home": false, 
    "name": "test", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1001
}

7、group:创建或管理远程主机的组
参数:

  • name 指定组 如果不存在则创建
  • gid 修改或指定组的gid
  • state=absent 删除指定组
[root@CentOS1 yum.repos.d]# ansible web -m group -a "name=one"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "gid": 1002, 
    "name": "one", 
    "state": "present", 
    "system": false
}
[root@CentOS1 yum.repos.d]# ansible web -m shell -a "tail -1 /etc/group"
192.168.1.2 | SUCCESS | rc=0 >>
one:x:1002:

2)指定gid

[root@CentOS1 yum.repos.d]# ansible web -m group -a "name=two gid=1030"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "gid": 1030, 
    "name": "two", 
    "state": "present", 
    "system": false
}
[root@CentOS1 yum.repos.d]# ansible web -m shell -a "tail -1 /etc/group"
192.168.1.2 | SUCCESS | rc=0 >>
two:x:1030:

3)删除组

[root@CentOS1 yum.repos.d]# ansible web -m group -a "name=two state=absent"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "name": "two", 
    "state": "absent"
}
[root@CentOS1 yum.repos.d]# ansible web -m shell -a "tail -1 /etc/group"
192.168.1.2 | SUCCESS | rc=0 >>
one:x:1002:

8、script:在远程主机上执行本机脚本
参数:

  • chdir 切换目录 远程主机上的目录
  • creates文件存 在脚本不执行
  • removes文件存在 脚本执行

1)执行脚本

[root@CentOS1 ~]# ansible web -m script -a " /root/test.sh"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.1.2 closed.\r\n", 
    "stdout": "src\r\n", 
    "stdout_lines": [
        "src"
    ]
}

2)文件存在不执行

[root@CentOS1 ~]# ansible web -m script -a "creates=/etc chdir=/root /root/test.sh"
192.168.1.2 | SKIPPED

3)文件存在执行脚本

[root@CentOS1 ~]# ansible web -m script -a "removes=/etc chdir=/root /root/test.sh"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.1.2 closed.\r\n", 
    "stdout": "src\r\n", 
    "stdout_lines": [
        "src"
    ]
}

9、setup 查看远程主机的信息 查看自带的变量
参数:

  • filter 过滤

1)查看被操控端的信息

[root@CentOS1 ~]# ansible web -m setup
192.168.1.2 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.122.1", 
            "192.168.1.2"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::29d8:3f91:b38e:413f"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "07/29/2019", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-514.el7.x86_64", 
            "LANG": "zh_CN.UTF-8", 
            "crashkernel": "auto", 
            "quiet": true, 
            "rd.lvm.lv": "cl/swap", 
            "rhgb": true, 
            "ro": true, 
            "root": "/dev/mapper/cl-root"
        }, 
        "ansible_date_time": {
            "date": "2020-06-11", 
            "day": "11", 
            "epoch": "1591837016", 
            "hour": "08", 
            "iso8601": "2020-06-11T00:56:56Z", 
            "iso8601_basic": "20200611T085656242271", 
            "iso8601_basic_short": "20200611T085656", 
            "iso8601_micro": "2020-06-11T00:56:56.242332Z", 
            "minute": "56", 
            "month": "06", 
            "second": "56", 
            "time": "08:56:56", 
            "tz": "CST", 
            "tz_offset": "+0800", 
            "weekday": "星期四", 
            "weekday_number": "4", 
            "weeknumber": "23", 
            "year": "2020"
        }, 
        "ansible_default_ipv4": {}, 
        "ansible_default_ipv6": {}, 
        "ansible_device_links": {
            "ids": {
                "dm-0": [
                    "dm-name-cl-root", 
                    "dm-uuid-LVM-jPkRLMddUR9kM2cMprJq4Vy3vkcypLMe7Kq6LqQmAUeIKASDY4Vn61DPrkLSVaXG"
                ], 
                "dm-1": [
                    "dm-name-cl-swap", 
                    "dm-uuid-LVM-jPkRLMddUR9kM2cMprJq4Vy3vkcypLMeiNzqMZG79XBBomAEuQzCYj1LLPZucqLi"
                ], 
                "sda2": [
                    "lvm-pv-uuid-IcmN73-dYHa-zyAK-U0Og-ZMQm-wIVl-mrhJ4c"
                ], 
                "sr0": [
                    "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                ]
            }, 
            "labels": {
                "sr0": [
                    "CentOS\\x207\\x20x86_64"
                ]
            }, 
            "masters": {
                "sda2": [
                    "dm-0", 
                    "dm-1"
                ]
            }, 
            "uuids": {
                "dm-0": [
                    "1ed50a8f-7417-468d-a58d-be908d86536a"
                ], 
                "dm-1": [
                    "2187456e-1789-4526-8b1f-a472257fe2ad"
                ], 
                "sda1": [
                    "efaa8b9e-183b-4264-9dff-93d8102db041"
                ], 
                "sr0": [
                    "2019-09-11-18-50-31-00"
                ]
            }
        }, 
        "ansible_devices": {
            "dm-0": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "dm-name-cl-root", 
                        "dm-uuid-LVM-jPkRLMddUR9kM2cMprJq4Vy3vkcypLMe7Kq6LqQmAUeIKASDY4Vn61DPrkLSVaXG"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": [
                        "1ed50a8f-7417-468d-a58d-be908d86536a"
                    ]
                }, 
                "model": null, 
                "partitions": {}, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "", 
                "sectors": "35643392", 
                "sectorsize": "512", 
                "size": "17.00 GB", 
                "support_discard": "0", 
                "vendor": null, 
                "virtual": 1
            }, 
            "dm-1": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "dm-name-cl-swap", 
                        "dm-uuid-LVM-jPkRLMddUR9kM2cMprJq4Vy3vkcypLMeiNzqMZG79XBBomAEuQzCYj1LLPZucqLi"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": [
                        "2187456e-1789-4526-8b1f-a472257fe2ad"
                    ]
                }, 
                "model": null, 
                "partitions": {}, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "", 
                "sectors": "4194304", 
                "sectorsize": "512", 
                "size": "2.00 GB", 
                "support_discard": "0", 
                "vendor": null, 
                "virtual": 1
            }, 
            "sda": {
                "holders": [], 
                "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)", 
                "links": {
                    "ids": [], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": []
                }, 
                "model": "VMware Virtual S", 
                "partitions": {
                    "sda1": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "efaa8b9e-183b-4264-9dff-93d8102db041"
                            ]
                        }, 
                        "sectors": "2097152", 
                        "sectorsize": 512, 
                        "size": "1.00 GB", 
                        "start": "2048", 
                        "uuid": "efaa8b9e-183b-4264-9dff-93d8102db041"
                    }, 
                    "sda2": {
                        "holders": [
                            "cl-root", 
                            "cl-swap"
                        ], 
                        "links": {
                            "ids": [
                                "lvm-pv-uuid-IcmN73-dYHa-zyAK-U0Og-ZMQm-wIVl-mrhJ4c"
                            ], 
                            "labels": [], 
                            "masters": [
                                "dm-0", 
                                "dm-1"
                            ], 
                            "uuids": []
                        }, 
                        "sectors": "39843840", 
                        "sectorsize": 512, 
                        "size": "19.00 GB", 
                        "start": "2099200", 
                        "uuid": null
                    }
                }, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "41943040", 
                "sectorsize": "512", 
                "size": "20.00 GB", 
                "support_discard": "0", 
                "vendor": "VMware,", 
                "virtual": 1
            }, 
            "sr0": {
                "holders": [], 
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)", 
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                    ], 
                    "labels": [
                        "CentOS\\x207\\x20x86_64"
                    ], 
                    "masters": [], 
                    "uuids": [
                        "2019-09-11-18-50-31-00"
                    ]
                }, 
                "model": "VMware IDE CDR10", 
                "partitions": {}, 
                "removable": "1", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "cfq", 
                "sectors": "9109504", 
                "sectorsize": "2048", 
                "size": "17.38 GB", 
                "support_discard": "0", 
                "vendor": "NECVMWar", 
                "virtual": 1
            }
        }, 
        "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.3.1611", 
        "ansible_dns": {}, 
        "ansible_domain": "", 
        "ansible_effective_group_id": 0, 
        "ansible_effective_user_id": 0, 
        "ansible_ens33": {
            "active": true, 
            "device": "ens33", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "off [fixed]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "off [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off", 
                "rx_checksumming": "off", 
                "rx_fcs": "off", 
                "rx_vlan_filter": "on [fixed]", 
                "rx_vlan_offload": "on", 
                "rx_vlan_stag_filter": "off [fixed]", 
                "rx_vlan_stag_hw_parse": "off [fixed]", 
                "scatter_gather": "on", 
                "tcp_segmentation_offload": "on", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "on", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "off [fixed]", 
                "tx_checksumming": "on", 
                "tx_fcoe_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "off [fixed]", 
                "tx_mpls_segmentation": "off [fixed]", 
                "tx_nocache_copy": "off", 
                "tx_scatter_gather": "on", 
                "tx_scatter_gather_fraglist": "off [fixed]", 
                "tx_sctp_segmentation": "off [fixed]", 
                "tx_sit_segmentation": "off [fixed]", 
                "tx_tcp6_segmentation": "off [fixed]", 
                "tx_tcp_ecn_segmentation": "off [fixed]", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "on [fixed]", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "off [fixed]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "192.168.1.2", 
                "broadcast": "192.168.1.255", 
                "netmask": "255.255.255.0", 
                "network": "192.168.1.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::29d8:3f91:b38e:413f", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "00:0c:29:44:44:47", 
            "module": "e1000", 
            "mtu": 1500, 
            "pciid": "0000:02:01.0", 
            "promisc": false, 
            "speed": 1000, 
            "timestamping": [
                "tx_software", 
                "rx_software", 
                "software"
            ], 
            "type": "ether"
        }, 
        "ansible_env": {
            "HOME": "/root", 
            "LANG": "zh_CN.UTF-8", 
            "LESSOPEN": "||/usr/bin/lesspipe.sh %s", 
            "LOGNAME": "root", 
            "LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:", 
            "MAIL": "/var/mail/root", 
            "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", 
            "PWD": "/root", 
            "SELINUX_LEVEL_REQUESTED": "", 
            "SELINUX_ROLE_REQUESTED": "", 
            "SELINUX_USE_CURRENT_RANGE": "", 
            "SHELL": "/bin/bash", 
            "SHLVL": "2", 
            "SSH_CLIENT": "192.168.1.1 46762 22", 
            "SSH_CONNECTION": "192.168.1.1 46762 192.168.1.2 22", 
            "SSH_TTY": "/dev/pts/2", 
            "TERM": "xterm", 
            "USER": "root", 
            "XDG_RUNTIME_DIR": "/run/user/0", 
            "XDG_SESSION_ID": "16", 
            "_": "/usr/bin/python"
        }, 
        "ansible_fips": false, 
        "ansible_form_factor": "Other", 
        "ansible_fqdn": "CentOS2", 
        "ansible_hostname": "CentOS2", 
        "ansible_interfaces": [
            "lo", 
            "virbr0", 
            "virbr0-nic", 
            "ens33"
        ], 
        "ansible_kernel": "3.10.0-514.el7.x86_64", 
        "ansible_lo": {
            "active": true, 
            "device": "lo", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "on [fixed]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "on [fixed]", 
                "netns_local": "on [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off [fixed]", 
                "rx_checksumming": "on [fixed]", 
                "rx_fcs": "off [fixed]", 
                "rx_vlan_filter": "off [fixed]", 
                "rx_vlan_offload": "off [fixed]", 
                "rx_vlan_stag_filter": "off [fixed]", 
                "rx_vlan_stag_hw_parse": "off [fixed]", 
                "scatter_gather": "on", 
                "tcp_segmentation_offload": "on", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "on [fixed]", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "on [fixed]", 
                "tx_checksumming": "on", 
                "tx_fcoe_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "on [fixed]", 
                "tx_mpls_segmentation": "off [fixed]", 
                "tx_nocache_copy": "off [fixed]", 
                "tx_scatter_gather": "on [fixed]", 
                "tx_scatter_gather_fraglist": "on [fixed]", 
                "tx_sctp_segmentation": "on", 
                "tx_sit_segmentation": "off [fixed]", 
                "tx_tcp6_segmentation": "on", 
                "tx_tcp_ecn_segmentation": "on", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "off [fixed]", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "on", 
                "vlan_challenged": "on [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "127.0.0.1", 
                "broadcast": "host", 
                "netmask": "255.0.0.0", 
                "network": "127.0.0.0"
            }, 
            "ipv6": [
                {
                    "address": "::1", 
                    "prefix": "128", 
                    "scope": "host"
                }
            ], 
            "mtu": 65536, 
            "promisc": false, 
            "timestamping": [
                "rx_software", 
                "software"
            ], 
            "type": "loopback"
        }, 
        "ansible_local": {}, 
        "ansible_lsb": {}, 
        "ansible_lvm": {
            "lvs": {
                "root": {
                    "size_g": "17.00", 
                    "vg": "cl"
                }, 
                "swap": {
                    "size_g": "2.00", 
                    "vg": "cl"
                }
            }, 
            "pvs": {
                "/dev/sda2": {
                    "free_g": "0", 
                    "size_g": "19.00", 
                    "vg": "cl"
                }
            }, 
            "vgs": {
                "cl": {
                    "free_g": "0", 
                    "num_lvs": "2", 
                    "num_pvs": "1", 
                    "size_g": "19.00"
                }
            }
        }, 
        "ansible_machine": "x86_64", 
        "ansible_machine_id": "753deeb8d319448bb57c0adaf686d934", 
        "ansible_memfree_mb": 122, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 321, 
                "used": 655
            }, 
            "real": {
                "free": 122, 
                "total": 976, 
                "used": 854
            }, 
            "swap": {
                "cached": 4, 
                "free": 2030, 
                "total": 2047, 
                "used": 17
            }
        }, 
        "ansible_memtotal_mb": 976, 
        "ansible_mounts": [
            {
                "block_available": 3474880, 
                "block_size": 4096, 
                "block_total": 4452864, 
                "block_used": 977984, 
                "device": "/dev/mapper/cl-root", 
                "fstype": "xfs", 
                "inode_available": 8763984, 
                "inode_total": 8910848, 
                "inode_used": 146864, 
                "mount": "/", 
                "options": "rw,seclabel,relatime,attr2,inode64,noquota", 
                "size_available": 14233108480, 
                "size_total": 18238930944, 
                "uuid": "1ed50a8f-7417-468d-a58d-be908d86536a"
            }, 
            {
                "block_available": 215444, 
                "block_size": 4096, 
                "block_total": 259584, 
                "block_used": 44140, 
                "device": "/dev/sda1", 
                "fstype": "xfs", 
                "inode_available": 523958, 
                "inode_total": 524288, 
                "inode_used": 330, 
                "mount": "/boot", 
                "options": "rw,seclabel,relatime,attr2,inode64,noquota", 
                "size_available": 882458624, 
                "size_total": 1063256064, 
                "uuid": "efaa8b9e-183b-4264-9dff-93d8102db041"
            }, 
            {
                "device": "/dev/sr0", 
                "fstype": "iso9660", 
                "mount": "/run/media/root/CentOS\\0407\\040x86_64", 
                "options": "ro,nosuid,nodev,relatime,uid=0,gid=0,iocharset=utf8,mode=0400,dmode=0500", 
                "uuid": "2019-09-11-18-50-31-00"
            }, 
            {
                "block_available": 0, 
                "block_size": 2048, 
                "block_total": 2277351, 
                "block_used": 2277351, 
                "device": "/dev/sr0", 
                "fstype": "iso9660", 
                "inode_available": 0, 
                "inode_total": 0, 
                "inode_used": 0, 
                "mount": "/cdrom", 
                "options": "ro,relatime,uid=0,gid=0,iocharset=utf8,mode=0400,dmode=0500", 
                "size_available": 0, 
                "size_total": 4664014848, 
                "uuid": "2019-09-11-18-50-31-00"
            }
        ], 
        "ansible_nodename": "CentOS2", 
        "ansible_os_family": "RedHat", 
        "ansible_pkg_mgr": "yum", 
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz"
        ], 
        "ansible_processor_cores": 1, 
        "ansible_processor_count": 1, 
        "ansible_processor_threads_per_core": 1, 
        "ansible_processor_vcpus": 1, 
        "ansible_product_name": "VMware Virtual Platform", 
        "ansible_product_serial": "VMware-56 4d 08 ba 75 50 c1 f2-bf 33 19 a5 16 44 44 47", 
        "ansible_product_uuid": "BA084D56-5075-F2C1-BF33-19A516444447", 
        "ansible_product_version": "None", 
        "ansible_python": {
            "executable": "/usr/bin/python", 
            "has_sslcontext": true, 
            "type": "CPython", 
            "version": {
                "major": 2, 
                "micro": 5, 
                "minor": 7, 
                "releaselevel": "final", 
                "serial": 0
            }, 
            "version_info": [
                2, 
                7, 
                5, 
                "final", 
                0
            ]
        }, 
        "ansible_python_version": "2.7.5", 
        "ansible_real_group_id": 0, 
        "ansible_real_user_id": 0, 
        "ansible_selinux": {
            "config_mode": "enforcing", 
            "mode": "permissive", 
            "policyvers": 28, 
            "status": "enabled", 
            "type": "targeted"
        }, 
        "ansible_selinux_python_present": true, 
        "ansible_service_mgr": "systemd", 
        "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLtq9ghGQ1PpdywvR0M03hHJO1Amb6jHoBQsXDozMClP1FzuzHn7ALO9cfi7xBZ6Yg1hiDjmRgfkR/oPogR34To=", 
        "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIAz/KiyWHXm0O4d4Yavc2td5LhzjGvdLHvhmjs/oPsc7", 
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQCq6mwJKvtlxuiklEl0D73CmlcMb/Fr06ToxqyI+zgT3+8I4D42DkxgtUNDuF50QHwFJBYh1+EEhos5KQF3Qf2+0rK1Rclv3eMWMX7BMDZFwqwmjo4EVP41yRlXuBR4O3H9dzlLZ2GABPmDmGVY4ZQDpnkFeTBj0ngjfcUkqaVhFVWxYJD0e0Wpv0Sb4ScN5NTc4nR/irAOaaU/jqQ0iE5wLO5LYuqnDkjh8gSgC39AgcsK5menV7/KQEnD2UZQqk/pTKyOvYgs1cJ0bGXkFE9PjKs8suKgB2NrQYKsq85xfvHxYVb3iEoqOSNDeT3XAYdi21QX2wtwYyWCxxb/KoKz", 
        "ansible_swapfree_mb": 2030, 
        "ansible_swaptotal_mb": 2047, 
        "ansible_system": "Linux", 
        "ansible_system_capabilities": [
            "cap_chown", 
            "cap_dac_override", 
            "cap_dac_read_search", 
            "cap_fowner", 
            "cap_fsetid", 
            "cap_kill", 
            "cap_setgid", 
            "cap_setuid", 
            "cap_setpcap", 
            "cap_linux_immutable", 
            "cap_net_bind_service", 
            "cap_net_broadcast", 
            "cap_net_admin", 
            "cap_net_raw", 
            "cap_ipc_lock", 
            "cap_ipc_owner", 
            "cap_sys_module", 
            "cap_sys_rawio", 
            "cap_sys_chroot", 
            "cap_sys_ptrace", 
            "cap_sys_pacct", 
            "cap_sys_admin", 
            "cap_sys_boot", 
            "cap_sys_nice", 
            "cap_sys_resource", 
            "cap_sys_time", 
            "cap_sys_tty_config", 
            "cap_mknod", 
            "cap_lease", 
            "cap_audit_write", 
            "cap_audit_control", 
            "cap_setfcap", 
            "cap_mac_override", 
            "cap_mac_admin", 
            "cap_syslog", 
            "35", 
            "36+ep"
        ], 
        "ansible_system_capabilities_enforced": "True", 
        "ansible_system_vendor": "VMware, Inc.", 
        "ansible_uptime_seconds": 2319, 
        "ansible_user_dir": "/root", 
        "ansible_user_gecos": "root", 
        "ansible_user_gid": 0, 
        "ansible_user_id": "root", 
        "ansible_user_shell": "/bin/bash", 
        "ansible_user_uid": 0, 
        "ansible_userspace_architecture": "x86_64", 
        "ansible_userspace_bits": "64", 
        "ansible_virbr0": {
            "active": false, 
            "device": "virbr0", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "off [requested on]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "on [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off [fixed]", 
                "rx_checksumming": "off [fixed]", 
                "rx_fcs": "off [fixed]", 
                "rx_vlan_filter": "off [fixed]", 
                "rx_vlan_offload": "off [fixed]", 
                "rx_vlan_stag_filter": "off [fixed]", 
                "rx_vlan_stag_hw_parse": "off [fixed]", 
                "scatter_gather": "on", 
                "tcp_segmentation_offload": "off", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "on", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "off [fixed]", 
                "tx_checksumming": "on", 
                "tx_fcoe_segmentation": "off [requested on]", 
                "tx_gre_segmentation": "on", 
                "tx_gso_robust": "off [requested on]", 
                "tx_ipip_segmentation": "on", 
                "tx_lockless": "on [fixed]", 
                "tx_mpls_segmentation": "on", 
                "tx_nocache_copy": "off", 
                "tx_scatter_gather": "on", 
                "tx_scatter_gather_fraglist": "on", 
                "tx_sctp_segmentation": "off [requested on]", 
                "tx_sit_segmentation": "on", 
                "tx_tcp6_segmentation": "off [requested on]", 
                "tx_tcp_ecn_segmentation": "off [requested on]", 
                "tx_tcp_segmentation": "off [requested on]", 
                "tx_udp_tnl_segmentation": "on", 
                "tx_vlan_offload": "on", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "off [requested on]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "id": "8000.52540011d44f", 
            "interfaces": [
                "virbr0-nic"
            ], 
            "ipv4": {
                "address": "192.168.122.1", 
                "broadcast": "192.168.122.255", 
                "netmask": "255.255.255.0", 
                "network": "192.168.122.0"
            }, 
            "macaddress": "52:54:00:11:d4:4f", 
            "mtu": 1500, 
            "promisc": false, 
            "stp": true, 
            "timestamping": [
                "rx_software", 
                "software"
            ], 
            "type": "bridge"
        }, 
        "ansible_virbr0_nic": {
            "active": false, 
            "device": "virbr0-nic", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "off [fixed]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "off [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off [fixed]", 
                "rx_checksumming": "off [fixed]", 
                "rx_fcs": "off [fixed]", 
                "rx_vlan_filter": "off [fixed]", 
                "rx_vlan_offload": "off [fixed]", 
                "rx_vlan_stag_filter": "off [fixed]", 
                "rx_vlan_stag_hw_parse": "off [fixed]", 
                "scatter_gather": "on", 
                "tcp_segmentation_offload": "off", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "off [requested on]", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "off [fixed]", 
                "tx_checksumming": "off", 
                "tx_fcoe_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "on [fixed]", 
                "tx_mpls_segmentation": "off [fixed]", 
                "tx_nocache_copy": "off", 
                "tx_scatter_gather": "on", 
                "tx_scatter_gather_fraglist": "on", 
                "tx_sctp_segmentation": "off [fixed]", 
                "tx_sit_segmentation": "off [fixed]", 
                "tx_tcp6_segmentation": "off [requested on]", 
                "tx_tcp_ecn_segmentation": "off [requested on]", 
                "tx_tcp_segmentation": "off [requested on]", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "on", 
                "tx_vlan_stag_hw_insert": "on", 
                "udp_fragmentation_offload": "off [requested on]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "macaddress": "52:54:00:11:d4:4f", 
            "mtu": 1500, 
            "promisc": true, 
            "timestamping": [
                "rx_software", 
                "software"
            ], 
            "type": "ether"
        }, 
        "ansible_virtualization_role": "guest", 
        "ansible_virtualization_type": "VMware", 
        "gather_subset": [
            "all"
        ], 
        "module_setup": true
    }, 
    "changed": false
}

2)过滤

[root@CentOS1 ~]# ansible web -m setup -a "filter=module_setup"
192.168.1.2 | SUCCESS => {
    "ansible_facts": {
        "module_setup": true
    }, 
    "changed": false
}

9、copy:将控制端的文件复制到被操控端,只针对文件不能复制空目录,目录中必须有文件
参数:

  • src 要复制的文件 操控端的位置
  • dest 目标位置 被操控端的位置 content 将指定的内容写入到远程主机的文件中,会覆盖原内容
  • copy当没有任何参数的时候当主控端复制的文件和远程主机 上的文件名一致时,但是内容不一致, 则会强制覆盖
  • force=no 当主控端复制的文件和远程主机上的文件名一致时,但是内容不一致,则不会覆盖会放弃复制
  • backup=yes 当主控端复制的文件和远程主机上的文件名一致时,但是内容不一致,则会覆盖会进行备份
  • owner:指定文件的属主
  • group:指定文件的属组
  • mode:指定文件的权限
    1)将文件复制到被操控端的目标位置
[root@CentOS1 ~]# ansible web -m copy -a "src=/root/lll dest=/root"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/root/lll", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1591837697.26-97012014785415/source", 
    "state": "file", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "ls /root"
192.168.1.2 | SUCCESS | rc=0 >>
anaconda-ks.cfg
initial-setup-ks.cfg
ip_yum_lkx_v1.1.0.sh
lll

2)添加内容

[root@CentOS1 ~]# ansible web -m copy -a "content='123\n456' dest=/root/lll"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "checksum": "74f203f85a3c316fef672843907c9584cbac8371", 
    "dest": "/root/lll", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f38193d972d9313330ddef3447b5d435", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 7, 
    "src": "/root/.ansible/tmp/ansible-tmp-1591838035.18-73247689631864/source", 
    "state": "file", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "cat /root/lll"
192.168.1.2 | SUCCESS | rc=0 >>
123
456

3)复制时不加任何操作

[root@CentOS1 ~]# echo "lkx" >/root/lll 
[root@CentOS1 ~]# ansible web -m copy -a "src=/root/lll dest=/root/lll"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "checksum": "954a3c012f457ff25d9d0785c0162c8286c6c1d0", 
    "dest": "/root/lll", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "87354b811c0cec78e8f4b2228cb9f1a8", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 4, 
    "src": "/root/.ansible/tmp/ansible-tmp-1591838271.64-270618738511192/source", 
    "state": "file", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "cat /root/lll"
192.168.1.2 | SUCCESS | rc=0 >>
lkx

4)force=no 如果目标位置有同名的文件放弃复制

[root@CentOS1 ~]# echo 123 >/root/lll 
[root@CentOS1 ~]# cat /root/lll 
123
[root@CentOS1 ~]# ansible web -m copy -a "src=/root/lll dest=/root force=no"
192.168.1.2 | SUCCESS => {
    "changed": false, 
    "dest": "/root", 
    "src": "/root/lll"
}
[root@CentOS1 ~]# ansible web -m shell -a "cat /root/lll"
192.168.1.2 | SUCCESS | rc=0 >>
lkx

5)force=no 如果目标位置有同名的文件会复制但是会备份

[root@CentOS1 ~]# ansible web -m copy -a "src=/root/lll dest=/root backup=yes"
192.168.1.2 | SUCCESS => {
    "backup_file": "/root/lll.19307.2020-06-11@09:25:03~", 
    "changed": true, 
    "checksum": "a8fdc205a9f19cc1c7507a60c4f01b13d11d7fd0", 
    "dest": "/root/lll", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "ba1f2511fc30423bdbb183fe33f3dd0f", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 4, 
    "src": "/root/.ansible/tmp/ansible-tmp-1591838702.9-241931830333407/source", 
    "state": "file", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "cat /root/lll"
192.168.1.2 | SUCCESS | rc=0 >>
123

6)指定属主

[root@CentOS1 ~]# ansible web -m copy -a "src=/root/lll dest=/root/lll owner=cc"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "checksum": "a8fdc205a9f19cc1c7507a60c4f01b13d11d7fd0", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "cc", 
    "path": "/root/lll", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 4, 
    "state": "file", 
    "uid": 1002
}
[root@CentOS1 ~]# ansible web -m shell -a "ls -l /root/lll"
192.168.1.2 | SUCCESS | rc=0 >>
-rw-r--r--. 1 cc root 4 6月  11 09:25 /root/lll

7)指定属组

[root@CentOS1 ~]# ansible web -m copy -a "src=/root/lll dest=/root/lll group=cc"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "checksum": "a8fdc205a9f19cc1c7507a60c4f01b13d11d7fd0", 
    "gid": 1003, 
    "group": "cc", 
    "mode": "0644", 
    "owner": "cc", 
    "path": "/root/lll", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 4, 
    "state": "file", 
    "uid": 1002
}
[root@CentOS1 ~]# ansible web -m shell -a "ls -l /root/lll"
192.168.1.2 | SUCCESS | rc=0 >>
-rw-r--r--. 1 cc cc 4 6月  11 09:25 /root/lll

8)指定文件权限

[root@CentOS1 ~]# ansible web -m copy -a "src=/root/lll dest=/root/lll mode=777"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "checksum": "a8fdc205a9f19cc1c7507a60c4f01b13d11d7fd0", 
    "gid": 1003, 
    "group": "cc", 
    "mode": "0777", 
    "owner": "cc", 
    "path": "/root/lll", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 4, 
    "state": "file", 
    "uid": 1002
}
[root@CentOS1 ~]# ansible web -m shell -a "ls -l /root/lll"
192.168.1.2 | SUCCESS | rc=0 >>
-rwxrwxrwx. 1 cc cc 4 6月  11 09:25 /root/lll

10、yum:在被控端使用yum安装软件
参数:

  • name 软件名
  • state=installed 安装
  • state=removed 卸载
    安装软件
[root@CentOS1 ~]# ansible web -m yum -a "name=httpd state=installed"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-90.el7.centos will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-90.el7.centos for package: httpd-2.4.6-90.el7.centos.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-90.el7.centos.x86_64\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.4.6-90.el7.centos will be installed\n---> Package mailcap.noarch 0:2.1.41-2.el7 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-90.el7.centos          lkx        2.7 M\nInstalling for dependencies:\n httpd-tools        x86_64        2.4.6-90.el7.centos          lkx         91 k\n mailcap            noarch        2.1.41-2.el7                 lkx         31 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+2 Dependent packages)\n\nTotal download size: 2.8 M\nInstalled size: 9.6 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                              8.0 MB/s | 2.8 MB  00:00     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : httpd-tools-2.4.6-90.el7.centos.x86_64                       1/3 \n  Installing : mailcap-2.1.41-2.el7.noarch                                  2/3 \n  Installing : httpd-2.4.6-90.el7.centos.x86_64                             3/3 \n  Verifying  : mailcap-2.1.41-2.el7.noarch                                  1/3 \n  Verifying  : httpd-tools-2.4.6-90.el7.centos.x86_64                       2/3 \n  Verifying  : httpd-2.4.6-90.el7.centos.x86_64                             3/3 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-90.el7.centos                                            \n\nDependency Installed:\n  httpd-tools.x86_64 0:2.4.6-90.el7.centos     mailcap.noarch 0:2.1.41-2.el7    \n\nComplete!\n"
    ]
}

卸载软件

[root@CentOS1 ~]# ansible web -m yum -a "name=httpd state=removed"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror, langpacks\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-90.el7.centos 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package       架构           版本                           源            大小\n================================================================================\n正在删除:\n httpd         x86_64         2.4.6-90.el7.centos            @lkx         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-90.el7.centos.x86_64                            1/1 \n  验证中      : httpd-2.4.6-90.el7.centos.x86_64                            1/1 \n\n删除:\n  httpd.x86_64 0:2.4.6-90.el7.centos                                            \n\n完毕!\n"
    ]
}

11、service:管理被控端的服务
参数:

  • name 用户名
  • state=started 开启
  • state=stopped 关闭
  • state=restarted 重启
  • state=reloaded 重新加载(服务必须是开启状态)
  • enabled=yes 加入到开机自启中

1)启动服务

[root@CentOS1 ~]# ansible web -m service -a "name=httpd state=started"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "remote-fs.target systemd-journald.socket basic.target -.mount network.target tmp.mount nss-lookup.target system.slice", 
        "AllowIsolate": "no", 
        "AssertResult": "no", 
        "AssertTimestampMonotonic": "0", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "no", 
        "ConditionTimestampMonotonic": "0", 
        "Conflicts": "shutdown.target", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestampMonotonic": "0", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "3782", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3782", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "0", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target -.mount", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StopWhenUnneeded": "no", 
        "SubState": "dead", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestampMonotonic": "0", 
        "WatchdogUSec": "0"
    }
}
[root@CentOS1 ~]# ansible web -m shell -a "netstat -anput | grep httpd"
192.168.1.2 | SUCCESS | rc=0 >>
tcp6       0      0 :::80                   :::*                    LISTEN      59037/httpd

2)关闭服务

[root@CentOS1 ~]# ansible web -m shell -a "netstat -anput | grep httpd"
192.168.1.2 | SUCCESS | rc=0 >>
tcp6       0      0 :::80                   :::*                    LISTEN      59037/httpd         

[root@CentOS1 ~]# ansible web -m service -a "name=httpd state=stopped"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "stopped", 
    "status": {
        "ActiveEnterTimestamp": "四 2020-06-11 09:57:42 CST", 
        "ActiveEnterTimestampMonotonic": "5965181100", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "active", 
        "After": "basic.target network.target system.slice remote-fs.target nss-lookup.target tmp.mount -.mount systemd-journald.socket", 
        "AllowIsolate": "no", 
        "AssertResult": "yes", 
        "AssertTimestamp": "四 2020-06-11 09:57:41 CST", 
        "AssertTimestampMonotonic": "5964508530", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "yes", 
        "ConditionTimestamp": "四 2020-06-11 09:57:41 CST", 
        "ConditionTimestampMonotonic": "5964508530", 
        "Conflicts": "shutdown.target", 
        "ControlGroup": "/system.slice/httpd.service", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "59037", 
        "ExecMainStartTimestamp": "四 2020-06-11 09:57:41 CST", 
        "ExecMainStartTimestampMonotonic": "5964510210", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[四 2020-06-11 09:57:41 CST] ; stop_time=[n/a] ; pid=59037 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestamp": "四 2020-06-11 09:57:41 CST", 
        "InactiveExitTimestampMonotonic": "5964510238", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "3782", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3782", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "59037", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target -.mount", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec", 
        "StopWhenUnneeded": "no", 
        "SubState": "running", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestamp": "四 2020-06-11 09:57:42 CST", 
        "WatchdogTimestampMonotonic": "5965181065", 
        "WatchdogUSec": "0"
    }
}
[root@CentOS1 ~]# ansible web -m shell -a "netstat -anput | grep httpd"
192.168.1.2 | FAILED | rc=1 >>
non-zero return code

3)重启服务

[root@CentOS1 ~]# ansible web -m service -a "name=httpd state=restarted"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "network.target basic.target system.slice tmp.mount systemd-journald.socket remote-fs.target -.mount nss-lookup.target", 
        "AllowIsolate": "no", 
        "AssertResult": "no", 
        "AssertTimestampMonotonic": "0", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "no", 
        "ConditionTimestampMonotonic": "0", 
        "Conflicts": "shutdown.target", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestampMonotonic": "0", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "3782", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3782", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "0", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target -.mount", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StopWhenUnneeded": "no", 
        "SubState": "dead", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestampMonotonic": "0", 
        "WatchdogUSec": "0"
    }
}
[root@CentOS1 ~]# ansible web -m shell -a "netstat -anput | grep httpd"
192.168.1.2 | SUCCESS | rc=0 >>
tcp6       0      0 :::80                   :::*                    LISTEN      59445/httpd         

4)重新加载

[root@CentOS1 ~]# ansible web -m service -a "name=httpd state=reloaded"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestamp": "四 2020-06-11 10:03:04 CST", 
        "ActiveEnterTimestampMonotonic": "6287556094", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "active", 
        "After": "system.slice nss-lookup.target basic.target network.target systemd-journald.socket tmp.mount remote-fs.target -.mount", 
        "AllowIsolate": "no", 
        "AssertResult": "yes", 
        "AssertTimestamp": "四 2020-06-11 10:03:04 CST", 
        "AssertTimestampMonotonic": "6287518302", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "yes", 
        "ConditionTimestamp": "四 2020-06-11 10:03:04 CST", 
        "ConditionTimestampMonotonic": "6287518301", 
        "Conflicts": "shutdown.target", 
        "ControlGroup": "/system.slice/httpd.service", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "59445", 
        "ExecMainStartTimestamp": "四 2020-06-11 10:03:04 CST", 
        "ExecMainStartTimestampMonotonic": "6287519371", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[四 2020-06-11 10:03:04 CST] ; stop_time=[n/a] ; pid=59445 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestamp": "四 2020-06-11 10:03:04 CST", 
        "InactiveExitTimestampMonotonic": "6287519396", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "3782", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3782", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "59445", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target -.mount", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec", 
        "StopWhenUnneeded": "no", 
        "SubState": "running", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestamp": "四 2020-06-11 10:03:04 CST", 
        "WatchdogTimestampMonotonic": "6287556055", 
        "WatchdogUSec": "0"
    }
}

5)将服务设置为开机自启

[root@CentOS1 ~]# ansible web -m service -a "name=httpd enabled=yes"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "status": {
        "ActiveEnterTimestamp": "四 2020-06-11 10:03:04 CST", 
        "ActiveEnterTimestampMonotonic": "6287556094", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "active", 
        "After": "system.slice nss-lookup.target basic.target network.target systemd-journald.socket tmp.mount remote-fs.target -.mount", 
        "AllowIsolate": "no", 
        "AssertResult": "yes", 
        "AssertTimestamp": "四 2020-06-11 10:03:04 CST", 
        "AssertTimestampMonotonic": "6287518302", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "yes", 
        "ConditionTimestamp": "四 2020-06-11 10:03:04 CST", 
        "ConditionTimestampMonotonic": "6287518301", 
        "Conflicts": "shutdown.target", 
        "ControlGroup": "/system.slice/httpd.service", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "59445", 
        "ExecMainStartTimestamp": "四 2020-06-11 10:03:04 CST", 
        "ExecMainStartTimestampMonotonic": "6287519371", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[四 2020-06-11 10:03:59 CST] ; stop_time=[四 2020-06-11 10:03:59 CST] ; pid=59624 ; code=exited ; status=0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[四 2020-06-11 10:03:04 CST] ; stop_time=[n/a] ; pid=59445 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestamp": "四 2020-06-11 10:03:04 CST", 
        "InactiveExitTimestampMonotonic": "6287519396", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "3782", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3782", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "59445", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target -.mount", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec", 
        "StopWhenUnneeded": "no", 
        "SubState": "running", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestamp": "四 2020-06-11 10:03:04 CST", 
        "WatchdogTimestampMonotonic": "6287556055", 
        "WatchdogUSec": "0"
    }
}
[root@CentOS1 ~]# ansible web -m shell -a "systemctl is-enabled httpd"	#查看服务是否开机自启
192.168.1.2 | SUCCESS | rc=0 >>
enabled
[root@CentOS1 ~]# ansible web -m service -a "name=httpd enabled=no"	#将服务设为开机不自启

12、file:管理远程主机上的文件或目录
参数:

  • path 指定路径 如果被控端没有此文件 则创建
  • state=touch 创建文件
  • state=directory 创建目录
  • state=link 创建软连接
  • state=hard 创建硬链接
  • 创建软硬链接必须写绝对路径src 远程主机上的源文件path (dest) 远程主机上的链接文件
  • owner 修改或指定属主
  • group 修改或指定属组
  • mode 修改或指定权限
  • state=absent 删除文件或目录

1)创建文件

[root@CentOS1 ~]# ansible web -m file -a "state=touch path=/root/touch"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "dest": "/root/touch", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "ls /root"
192.168.1.2 | SUCCESS | rc=0 >>
anaconda-ks.cfg
initial-setup-ks.cfg
ip_yum_lkx_v1.1.0.sh
lll
lll.19307.2020-06-11@09:25:03~
touch

2)创建目录

[root@CentOS1 ~]# ansible web -m file -a "state=directory path=/root/qwe"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/root/qwe", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "ls /root"
192.168.1.2 | SUCCESS | rc=0 >>
anaconda-ks.cfg
initial-setup-ks.cfg
ip_yum_lkx_v1.1.0.sh
lll
lll.19307.2020-06-11@09:25:03~
qwe

3)创建软连接

[root@CentOS1 ~]# ansible web -m file -a "state=link src=/usr/src/qwe path=/usr/src/ttt"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "dest": "/usr/src/ttt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 12, 
    "src": "/usr/src/qwe", 
    "state": "link", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "ls /usr/src/ttt"
192.168.1.2 | SUCCESS | rc=0 >>
lll.txt

4)创建硬链接

[root@CentOS1 ~]# ansible web -m file -a "state=hard src=/root/lll.txt path=/usr/src/qwe"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "dest": "/usr/src/qwe/lll.txt", 
    "gid": 1003, 
    "group": "cc", 
    "mode": "0777", 
    "owner": "cc", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 4, 
    "src": "/root/lll.txt", 
    "state": "hard", 
    "uid": 1002
}
[root@CentOS1 ~]# ansible web -m shell -a "ls -lh /usr/src/qwe"
192.168.1.2 | SUCCESS | rc=0 >>
总用量 4.0K
-rwxrwxrwx. 2 cc cc 4 6月  11 09:25 lll.txt

5)创建文件并给予权限

[root@CentOS1 ~]# ansible web -m shell -a "ls -l /root/q.txt"
192.168.1.2 | SUCCESS | rc=0 >>
-rwxrwxrwx. 1 root root 0 6月  11 10:44 /root/q.txt
#更改权限
[root@CentOS1 ~]# ansible web -m file -a "path=/root/q.txt mode=555"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0555", 
    "owner": "root", 
    "path": "/root/q.txt", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@CentOS1 ~]# ansible web -m shell -a "ls -l /root/q.txt"
192.168.1.2 | SUCCESS | rc=0 >>
-r-xr-xr-x. 1 root root 0 6月  11 10:44 /root/q.txt

6)更改属主

[root@CentOS1 ~]# ansible web -m file -a "path=/root/q.txt owner=centos2"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0555", 
    "owner": "centos2", 
    "path": "/root/q.txt", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}
[root@CentOS1 ~]# ansible web -m shell -a "ls -l /root/q.txt"
192.168.1.2 | SUCCESS | rc=0 >>
-r-xr-xr-x. 1 centos2 root 0 6月  11 10:44 /root/q.txt

7)更改属组

[root@CentOS1 ~]# ansible web -m file -a "path=/root/q.txt group=centos2"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "gid": 1000, 
    "group": "centos2", 
    "mode": "0555", 
    "owner": "centos2", 
    "path": "/root/q.txt", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}
[root@CentOS1 ~]# ansible web -m shell -a "ls -l /root/q.txt"
192.168.1.2 | SUCCESS | rc=0 >>
-r-xr-xr-x. 1 centos2 centos2 0 6月  11 10:44 /root/q.txt

8)删除文件或目录

[root@CentOS1 ~]# ansible web -m file -a "path=/usr/src/qwe state=absent"
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "path": "/usr/src/qwe", 
    "state": "absent"
}
[root@CentOS1 ~]# ansible web -m shell -a "ls /usr/src/ | grep qwe"
192.168.1.2 | FAILED | rc=1 >>
non-zero return code

13、cron:在被控端主机添加计划任务
参数:

  • minute 分钟
  • hour 小时
  • day 日
  • mouth 月
  • weekday 周
  • job 执行命令
  • name 计划任务名
  • special_time-hourly 每小时
    创建计划任务
[root@CentOS1 ~]# ansible web -m cron -a "name=test minute=10 hour=8 job='echo test' "
192.168.1.2 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test"
    ]
}
[root@CentOS1 ~]# ansible web -m shell -a "crontab -l"
192.168.1.2 | SUCCESS | rc=0 >>
#Ansible: test
10 8 * * * echo test

删除计划任务

[root@CentOS1 ~]# ansible web -m shell -a "crontab -r"
192.168.1.2 | SUCCESS | rc=0 >>


[root@CentOS1 ~]# ansible web -m shell -a "crontab -l"
192.168.1.2 | FAILED | rc=1 >>
no crontab for rootnon-zero return code

14、 lineinfile:用来给文件中添加内容或者修改文件中的内容

  • regexp 正则匹配 ^…以什么开头 ……$以什么结尾
  • line将匹配的内容进行替换
  • line 单独使用是在文件的最后添加内容
  • insertbefore 在匹配行的前面添加内容
  • insertafter 在匹配行的之后添加
    1)在最后添加内容
[root@CentOS1 ~]# ansible web -m lineinfile -a "line='444' path=/root/q"
192.168.1.2 | SUCCESS => {
    "backup": "", 
    "changed": true, 
    "msg": "line added"
}
[root@CentOS1 ~]# ansible web -m shell -a "cat q"
192.168.1.2 | SUCCESS | rc=0 >>
111
222
333
444

2)替换以2开头的行

[root@CentOS1 ~]# ansible web -m lineinfile -a "regexp='^2' line='5555' path=/root/q "
192.168.1.2 | SUCCESS => {
    "backup": "", 
    "changed": true, 
    "msg": "line replaced"
}
[root@CentOS1 ~]# ansible web -m shell -a "cat q"
192.168.1.2 | SUCCESS | rc=0 >>
111
5555
333
444

3)替换以3结尾的行

[root@CentOS1 ~]# ansible web -m lineinfile -a "regexp='3$' line='5555' path=/root/q "
192.168.1.2 | SUCCESS => {
    "backup": "", 
    "changed": true, 
    "msg": "line replaced"
}
[root@CentOS1 ~]# ansible web -m shell -a "cat q"
192.168.1.2 | SUCCESS | rc=0 >>
111
5555
5555
444

4)匹配行前添加内容

[root@CentOS1 ~]# ansible web -m lineinfile -a "insertbefore='^4' line='666' path=/root/q " 
192.168.1.2 | SUCCESS => {
    "backup": "", 
    "changed": true, 
    "msg": "line added"
}
[root@CentOS1 ~]# ansible web -m shell -a "cat q"
192.168.1.2 | SUCCESS | rc=0 >>
111
5555
5555
666
444
[root@CentOS1 ~]# ansible web -m lineinfile -a "insertbefore='^4' line='666' path=/root/q " 
192.168.1.2 | SUCCESS => {
    "backup": "", 
    "changed": true, 
    "msg": "line added"
}
[root@CentOS1 ~]# ansible web -m shell -a "cat q"
192.168.1.2 | SUCCESS | rc=0 >>
111
5555
5555
666
444

5)匹配行后添加内容

[root@CentOS1 ~]# ansible web -m lineinfile -a "insertafter='6$' line='777' path=/root/q "
192.168.1.2 | SUCCESS => {
    "backup": "", 
    "changed": true, 
    "msg": "line added"
}
[root@CentOS1 ~]# ansible web -m shell -a "cat q"
192.168.1.2 | SUCCESS | rc=0 >>
111
5555
5555
666
777

15、playbook:剧本
语法格式:

  • —代表yaml文件
  • 区分大小写
  • 层级是通过缩进使用空格
  • #注释
  • 数据类型
  • 集合
  • 列表.
  • 字符串
  • 数据
  • 对象
  • yaml语言编写的playbook剧本中特殊字符的含义
  • tasks任务
  • handlers触发器
  • variables变量
    格式:
[root@CentOS1 ~]# vim test.yml
---	#代表yaml文件
    - hosts: web	#清单
      remote_user: root	#用户
      tasks:	#任务
        - name: touch file	#任务名
          shell: echo{{var}} >haha	#调用模块执行操作

1)通过命令指定变量值 -e

[root@CentOS1 ~]# ansible-playbook -e "var=haha" test.yml 

PLAY [web] ********************************************************************************

TASK [Gathering Facts] ********************************************************************
ok: [192.168.1.2]

TASK [touch file] *************************************************************************
changed: [192.168.1.2]

PLAY RECAP ********************************************************************************
192.168.1.2                : ok=2    changed=1    unreachable=0    failed=0   
[root@CentOS1 ~]# ansible web -m shell -a "cat haha"
192.168.1.2 | SUCCESS | rc=0 >>
haha

2)在剧本中指定变量值


[root@CentOS1 ~]# ansible-playbook test.yml 

PLAY [web] ********************************************************************************

TASK [Gathering Facts] ********************************************************************
ok: [192.168.1.2]

TASK [touch file] *************************************************************************
changed: [192.168.1.2]

PLAY RECAP ********************************************************************************
192.168.1.2                : ok=2    changed=1    unreachable=0    failed=0   

[root@CentOS1 ~]# ansible web -m shell -a "cat haha"
192.168.1.2 | SUCCESS | rc=0 >>
hehe

3)通过文件来调用变量

[root@CentOS1 ~]# vim var.yaml
---
        var1: samba
        var2: vsftpd
[root@CentOS1 ~]# vim test.yaml
---
      - hosts: web
        remote_user: root
        vars_files:
          - var.yaml
        tasks:
          - name: touch
            shell: echo {{var1}} > haha
          - name: yum install vsftpd
            yum: name={{var2}} state=installed

[root@CentOS1 ~]# ansible-playbook test.yaml 

PLAY [web] ********************************************************************************

TASK [Gathering Facts] ********************************************************************
ok: [192.168.1.2]

TASK [touch] ******************************************************************************
changed: [192.168.1.2]

TASK [yum install vsftpd] *****************************************************************
changed: [192.168.1.2]

PLAY RECAP ********************************************************************************
192.168.1.2                : ok=3    changed=2    unreachable=0    failed=0  
[root@CentOS1 ~]# ansible web -m shell -a "cat haha"
192.168.1.2 | SUCCESS | rc=0 >>
samba 

4)可以在主机清单中设hi变量 这种方式基本不用

[web]
192.168.1.2
#添加 要给那个清单写变量就在那个清单后添加
[web:vars]
var3=dhcp
[root@CentOS1 ~]# ansible-playbook test.yaml 

PLAY [web] ********************************************************************************

TASK [Gathering Facts] ********************************************************************
ok: [192.168.1.2]

TASK [touch] ******************************************************************************
changed: [192.168.1.2]

TASK [yum install vsftpd] *****************************************************************
changed: [192.168.1.2]

PLAY RECAP ********************************************************************************
192.168.1.2                : ok=3    changed=2    unreachable=0    failed=0   
[root@CentOS1 ~]# ansible web -m shell -a "cat haha"
192.168.1.2 | SUCCESS | rc=0 >>
dhcp

三、角色

角色官网
role:角色 把剧本进行规范
roles:

  • 变更主机组频繁
  • 命名规范
  • 需要使用多个剧本
  • 针对于大型的项目
    1、角色的两种实现方式:
    1)通过官网来下角色
#需要联网
[root@CentOS1 ~]# ansible-galaxy install robertdebock.httpd	#robertdebock.httpd 去官网中去找

2)自己手写来实现
创建角色

[root@CentOS1 ~]# cd /etc/ansible/roles/
[root@CentOS1 roles]# mkdir nginx
[root@CentOS1 roles]# cd nginx/
[root@CentOS1 nginx]# mkdir {tasks,vars,handlers,files,templates}
[root@CentOS1 nginx]# ls
files  handlers  templates  tesks  vars

编辑nginx配置文件

[root@CentOS1 files]# cp /root/nginx-1.11.5.tar.gz ./
[root@CentOS1 files]# echo 1111 > index.html
#金甲模板文件 带变量的文件
[root@CentOS1 ~]# tar zxf nginx-1.11.5.tar.gz
[root@CentOS1 ~]# cp /root/nginx-1.11.5/conf/nginx.conf /etc/ansible/roles/nginx/templates/nginx.conf.j2 
[root@CentOS1 ~]# cd /etc/ansible/roles/nginx/templates/
[root@CentOS1 templates]# vim nginx.conf.j2 
  3 woker_processes {{ ansible_processor_cores}};
  13     worker_connections  {{ woker_connections}};

写变量文件

[root@CentOS1 templates]# cd ../vars/
[root@CentOS1 vars]# vim main.yml

---
        worker_connections: 10240
        listen: 8080

写任务

[root@CentOS1 templates]# cd ../tesks/
[root@CentOS1 tesks]# vim main.yaml
---
          - name: yum install nginx
            yum: name=pcre-devel,zlib-devel,openssl-devel,zlib state=installed
          - name: copy nginx.rpm
            copy: src=nginx-1.11.5.tar.gz dest=/usr/src/nginx-1.11.5.tar.gz
          - name: tar nginx
            shell: cd /usr/src && tar zxf nginx-1.11.5.tar.gz
          - name: useradd nginx
            user: name=nginx shell=/sbin/nologin
          - name: config
            shell: cd /usr/src/nginx-1.11.5 && ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx && make -j4 && make install
          - name: link
            file: src=/usr/local/nginx/sbin/nginx state=link path=/usr/local/sbin/nginx          
          - name: stat server
          - name: copy index.html
            copy: src=index.tml dest=/usr/local/nginx/html/index.html
          - name: copy nginx.conf
            template: src=nginx.conf.j2 dest=/usr/local/nginx/conf/nginx.conf
            notify: restart nginx

触发器

[root@CentOS1 tesks]# cd ../handlers/
[root@CentOS1 handlers]# vim main.yaml
---
        - name: restart nginx
          shell: nginx

编写与运行文件

[root@CentOS1 nginx]# cd ../../
[root@CentOS1 ansible]# vim nginx.yaml
---
        - hosts: web
          remote_user: root
          roles:
           - nginx	#角色名
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值