linux环境下部署和使用Ansible管理服务器

linux环境下部署和使用Ansible管理服务器_第1张图片

由上面的图可以看到 Ansible 的组成由 5 个部分组成: Ansible : Ansible核心 Modules : 包括 Ansible 自带的核心模块及自定义模块 Plugins : 完成模块功能的补充,包括连接插件、邮件插件等 Playbooks : 剧本,定义 Ansible 多任务配置文件,由Ansible 自动执行 Inventory : 定义 Ansible 管理主机的清单 [ˈɪnvəntri] 清单

ip 主机名 角色
192.168.88.67 server67 manager
192.168.88.69 server69 node
192.168.88.70 server70 node
​
​
[root@server67 ~]# yum install -y epel-release
[root@server67 ~]# yum install -y ansible
[root@server67 ~]# cat >>/etc/ansible/hosts< {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.88.69 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
至此ansible和node节点连接成功

常见模块和常见命令

command

作为Ansible的默认模块,可以运行远程权限范围内的所有shell命令,不支持管道,没法批量执行命令

(1)检查Ansible节点的运行时间(uptime)
[root@server67 ~]# ansible -i /etc/ansible/hosts 'web-servers'  -m command -a uptime
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED | rc=0 >>
 21:41:38 up  1:22,  2 users,  load average: 0.00, 0.01, 0.01
192.168.88.70 | CHANGED | rc=0 >>
 21:41:38 up  1:16,  3 users,  load average: 0.00, 0.01, 0.02
(2)检查节点的内核版本
[root@server67 ~]#  ansible -m command -a "uname -r" 'web-servers' 
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.70 | CHANGED | rc=0 >>
3.10.0-514.el7.x86_64
192.168.88.69 | CHANGED | rc=0 >>
3.10.0-514.el7.x86_64
(3)给节点创建用户
[root@server67 ~]# ansible -m command -a "useradd pekeka" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED | rc=0 >>
​
192.168.88.70 | CHANGED | rc=0 >>
(4)执行df命令
[root@server67 ~]# ansible -m command -a "df -Th" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED | rc=0 >>
文件系统              类型      容量  已用  可用 已用% 挂载点
/dev/mapper/rhel-root xfs        17G  1.2G   16G    7% /
devtmpfs              devtmpfs  478M     0  478M    0% /dev
tmpfs                 tmpfs     489M     0  489M    0% /dev/shm
tmpfs                 tmpfs     489M  6.7M  482M    2% /run
tmpfs                 tmpfs     489M     0  489M    0% /sys/fs/cgroup
/dev/sda1             xfs      1014M  139M  876M   14% /boot
tmpfs                 tmpfs      98M     0   98M    0% /run/user/0
/dev/sr0              iso9660   3.6G  3.6G     0  100% /mnt
192.168.88.70 | CHANGED | rc=0 >>
文件系统              类型      容量  已用  可用 已用% 挂载点
/dev/mapper/rhel-root xfs        17G  1.2G   16G    7% /
devtmpfs              devtmpfs  478M     0  478M    0% /dev
tmpfs                 tmpfs     489M     0  489M    0% /dev/shm
tmpfs                 tmpfs     489M  6.8M  482M    2% /run
tmpfs                 tmpfs     489M     0  489M    0% /sys/fs/cgroup
/dev/sda1             xfs      1014M  139M  876M   14% /boot
tmpfs                 tmpfs      98M     0   98M    0% /run/user/0
/dev/sr0              iso9660   3.6G  3.6G     0  100% /mnt

shell

使用shell模块,在远程命令通过/bin/sh来执行;所以在终端输入的各种命令方式,都可以使用

(1)可以使用管道符并且过滤信息
[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m shell -a " df -h | grep sda1"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED | rc=0 >>
/dev/sda1             1014M  139M  876M   14% /boot
192.168.88.70 | CHANGED | rc=0 >>
/dev/sda1             1014M  139M  876M   14% /boot

scripts

如果在远程待执行的语句比较多,可写成一个脚本,通过copy模块传到远端,然后再执行;

(1)可以执行一个脚本
[root@server67 tmp]# vim /etc/ansible/test.sh
[root@server67 tmp]# cat /etc/ansible/test.sh
#!/bin/bash
date
hostname
[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m script -a "/etc/ansible/test.sh"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.70 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.88.70 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.88.70 closed."
    ], 
    "stdout": "2022年 11月 28日 星期一 22:01:32 CST\r\nserver70\r\n", 
    "stdout_lines": [
        "2022年 11月 28日 星期一 22:01:32 CST", 
        "server70"
    ]
}
192.168.88.69 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.88.69 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.88.69 closed."
    ], 
    "stdout": "2022年 11月 28日 星期一 22:01:32 CST\r\nserver69\r\n", 
    "stdout_lines": [
        "2022年 11月 28日 星期一 22:01:32 CST", 
        "server69"
    ]
}

copy

实现主控端向目标主机拷贝文件,类似scp功能

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m copy -a "src=/etc/hosts dest=/tmp/ owner=root group=root mode=0755"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "7335999eb54c15c67566186bdfc46f64e0d5a1aa", 
    "dest": "/tmp/hosts", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "54fb6627dbaa37721048e4549db3224d", 
    "mode": "0755", 
    "owner": "root", 
    "size": 158, 
    "src": "/root/.ansible/tmp/ansible-tmp-1669644560.71-7227-280650757666305/source", 
    "state": "file", 
    "uid": 0
}
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "7335999eb54c15c67566186bdfc46f64e0d5a1aa", 
    "dest": "/tmp/hosts", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "54fb6627dbaa37721048e4549db3224d", 
    "mode": "0755", 
    "owner": "root", 
    "size": 158, 
    "src": "/root/.ansible/tmp/ansible-tmp-1669644560.7-7226-267393540456623/source", 
    "state": "file", 
    "uid": 0
}
[root@server69 ~]# cat /tmp/hosts 
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@server70 tmp]# cat /tmp/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

file

设置文件属性

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m file -a "path=/tmp/hosts mode=666"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0666", 
    "owner": "root", 
    "path": "/tmp/hosts", 
    "size": 158, 
    "state": "file", 
    "uid": 0
}
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0666", 
    "owner": "root", 
    "path": "/tmp/hosts", 
    "size": 158, 
    "state": "file", 
    "uid": 0
}
[root@server69 tmp]# ll
总用量 8
-rw-rw-rw-  1 root root 158 11月 28 22:09 hosts

stat

获取远程文件信息

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m stat -a "path=/tmp/hosts"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.70 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "stat": {
        "atime": 1669644623.7588527, 
        "attr_flags": "", 
        "attributes": [], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "7335999eb54c15c67566186bdfc46f64e0d5a1aa", 
        "ctime": 1669644761.0759568, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": false, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 50836849, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0666", 
        "mtime": 1669644561.1473494, 
        "nlink": 1, 
        "path": "/tmp/hosts", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 158, 
        "uid": 0, 
        "version": "18446744073190799215", 
        "wgrp": true, 
        "woth": true, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": false, 
        "xoth": false, 
        "xusr": false
    }
}
192.168.88.69 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "stat": {
        "atime": 1669644601.5610764, 
        "attr_flags": "", 
        "attributes": [], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "7335999eb54c15c67566186bdfc46f64e0d5a1aa", 
        "ctime": 1669644761.0813437, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": false, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 17149477, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0666", 
        "mtime": 1669644561.1497555, 
        "nlink": 1, 
        "path": "/tmp/hosts", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 158, 
        "uid": 0, 
        "version": "371226921", 
        "wgrp": true, 
        "woth": true, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": false, 
        "xoth": false, 
        "xusr": false
    }
}

get_url

实现远程主机下载指定url到本地,支持sha256sum文件校验。

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m get_url -a "url=https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm  dest=/tmp/ mode=0440 force=yes"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum_dest": null, 
    "checksum_src": "772e0dbc7c1690a950cd733901097cdeabd8dc09", 
    "dest": "/tmp/epel-release-latest-7.noarch.rpm", 
    "elapsed": 2, 
    "gid": 0, 
    "group": "root", 
    "md5sum": "966ae7fbf5106958334a7ec9a8c22ba4", 
    "mode": "0440", 
    "msg": "OK (15608 bytes)", 
    "owner": "root", 
    "size": 15608, 
    "src": "/root/.ansible/tmp/ansible-tmp-1669645410.53-7362-49615837482747/tmpFMCV_L", 
    "state": "file", 
    "status_code": 200, 
    "uid": 0, 
    "url": "https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm"
}
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum_dest": null, 
    "checksum_src": "772e0dbc7c1690a950cd733901097cdeabd8dc09", 
    "dest": "/tmp/epel-release-latest-7.noarch.rpm", 
    "elapsed": 3, 
    "gid": 0, 
    "group": "root", 
    "md5sum": "966ae7fbf5106958334a7ec9a8c22ba4", 
    "mode": "0440", 
    "msg": "OK (15608 bytes)", 
    "owner": "root", 
    "size": 15608, 
    "src": "/root/.ansible/tmp/ansible-tmp-1669645410.53-7363-223887116002380/tmpo43hPT", 
    "state": "file", 
    "status_code": 200, 
    "uid": 0, 
    "url": "https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm"
}
如果force=yes,当下载文件时,如果所下的内容和原目录下的文件内容不一样,则替换原文件,如果一样,就不下载了。
如果为“force=no”,则仅在目标不存在时才下载文件。
没有发生改变,那么显示绿色
发生改变,那么显示浅黄色
[root@server69 tmp]# ls
epel-release-latest-7.noarch.rpm

yum

Linux平台软件包管理,可以提供的status状态: latest ,present,installed #这3个是安装;removed, absent #这2个是卸载

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m yum -a "name=httpd  state=latest"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ], 
        "updated": []
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: product-id, search-disabled-repos, subscription-manager\nThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-45.el7 will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-45.el7 for package: httpd-2.4.6-45.el7.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-45.el7.x86_64\n--> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-45.el7.x86_64\n--> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-45.el7.x86_64\n--> Running transaction check\n---> Package apr.x86_64 0:1.4.8-3.el7 will be installed\n---> Package apr-util.x86_64 0:1.5.2-6.el7 will be installed\n---> Package httpd-tools.x86_64 0:2.4.6-45.el7 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-45.el7            local         1.2 M\nInstalling for dependencies:\n apr                 x86_64         1.4.8-3.el7             local         103 k\n apr-util            x86_64         1.5.2-6.el7             local          92 k\n httpd-tools         x86_64         2.4.6-45.el7            local          84 k\n mailcap             noarch         2.1.41-2.el7            local          31 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+4 Dependent packages)\n\nTotal download size: 1.5 M\nInstalled size: 4.3 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                               50 MB/s | 1.5 MB  00:00     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : apr-1.4.8-3.el7.x86_64                                       1/5 \n  Installing : apr-util-1.5.2-6.el7.x86_64                                  2/5 \n  Installing : httpd-tools-2.4.6-45.el7.x86_64                              3/5 \n  Installing : mailcap-2.1.41-2.el7.noarch                                  4/5 \n  Installing : httpd-2.4.6-45.el7.x86_64                                    5/5 \n  Verifying  : httpd-tools-2.4.6-45.el7.x86_64                              1/5 \n  Verifying  : apr-util-1.5.2-6.el7.x86_64                                  2/5 \n  Verifying  : mailcap-2.1.41-2.el7.noarch                                  3/5 \n  Verifying  : httpd-2.4.6-45.el7.x86_64                                    4/5 \n  Verifying  : apr-1.4.8-3.el7.x86_64                                       5/5 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-45.el7                                                   \n\nDependency Installed:\n  apr.x86_64 0:1.4.8-3.el7                 apr-util.x86_64 0:1.5.2-6.el7       \n  httpd-tools.x86_64 0:2.4.6-45.el7        mailcap.noarch 0:2.1.41-2.el7       \n\nComplete!\n"
    ]
}
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ], 
        "updated": []
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: product-id, search-disabled-repos, subscription-manager\nThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-45.el7 will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-45.el7 for package: httpd-2.4.6-45.el7.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-45.el7.x86_64\n--> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-45.el7.x86_64\n--> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-45.el7.x86_64\n--> Running transaction check\n---> Package apr.x86_64 0:1.4.8-3.el7 will be installed\n---> Package apr-util.x86_64 0:1.5.2-6.el7 will be installed\n---> Package httpd-tools.x86_64 0:2.4.6-45.el7 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-45.el7            local         1.2 M\nInstalling for dependencies:\n apr                 x86_64         1.4.8-3.el7             local         103 k\n apr-util            x86_64         1.5.2-6.el7             local          92 k\n httpd-tools         x86_64         2.4.6-45.el7            local          84 k\n mailcap             noarch         2.1.41-2.el7            local          31 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+4 Dependent packages)\n\nTotal download size: 1.5 M\nInstalled size: 4.3 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                               71 MB/s | 1.5 MB  00:00     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : apr-1.4.8-3.el7.x86_64                                       1/5 \n  Installing : apr-util-1.5.2-6.el7.x86_64                                  2/5 \n  Installing : httpd-tools-2.4.6-45.el7.x86_64                              3/5 \n  Installing : mailcap-2.1.41-2.el7.noarch                                  4/5 \n  Installing : httpd-2.4.6-45.el7.x86_64                                    5/5 \n  Verifying  : httpd-tools-2.4.6-45.el7.x86_64                              1/5 \n  Verifying  : apr-util-1.5.2-6.el7.x86_64                                  2/5 \n  Verifying  : mailcap-2.1.41-2.el7.noarch                                  3/5 \n  Verifying  : httpd-2.4.6-45.el7.x86_64                                    4/5 \n  Verifying  : apr-1.4.8-3.el7.x86_64                                       5/5 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-45.el7                                                   \n\nDependency Installed:\n  apr.x86_64 0:1.4.8-3.el7                 apr-util.x86_64 0:1.5.2-6.el7       \n  httpd-tools.x86_64 0:2.4.6-45.el7        mailcap.noarch 0:2.1.41-2.el7       \n\nComplete!\n"
    ]
}
[root@server69 tmp]# rpm -qa httpd
httpd-2.4.6-45.el7.x86_64
​
​
​
​
[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m yum -a "name=httpd  state=removed"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "removed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:product-id, search-disabled-repos, subscription-manager\nThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-45.el7 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package         架构             版本                   源                大小\n================================================================================\n正在删除:\n httpd           x86_64           2.4.6-45.el7           @local           3.7 M\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:3.7 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : httpd-2.4.6-45.el7.x86_64                                   1/1 \n  验证中      : httpd-2.4.6-45.el7.x86_64                                   1/1 \n\n删除:\n  httpd.x86_64 0:2.4.6-45.el7                                                   \n\n完毕!\n"
    ]
}
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "removed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:product-id, search-disabled-repos, subscription-manager\nThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-45.el7 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package         架构             版本                   源                大小\n================================================================================\n正在删除:\n httpd           x86_64           2.4.6-45.el7           @local           3.7 M\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:3.7 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : httpd-2.4.6-45.el7.x86_64                                   1/1 \n  验证中      : httpd-2.4.6-45.el7.x86_64                                   1/1 \n\n删除:\n  httpd.x86_64 0:2.4.6-45.el7                                                   \n\n完毕!\n"
    ]
}
[root@server69 tmp]# rpm -qa httpd
​
​

cron

远程主机crontab配置

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m cron -a "name='list dir' minute='*' job='touch /opy/test.txt' "
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "list dir"
    ]
}
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "list dir"
    ]
}
[root@server69 tmp]# crontab -l
#Ansible: list dir
* * * * * touch /opt/test.txt
[root@server69 opt]# ll
总用量 0
-rw-r--r-- 1 root root 0 11月 28 22:34 test.txt

service

远程主机系统服务管理

name参数:此参数用于指定需要操作的服务名称,比如 nginx,httpd

state 的值设置为 started;如果想要停止远程主机中的服务,则可以将 state 的值设置为 stopped, 此参数的可用值有 started、stopped、restarted(重启)、reloaded

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m service -a "name=httpd state=started"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "nss-lookup.target system.slice systemd-journald.socket tmp.mount remote-fs.target network.target -.mount basic.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": "3820", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3820", 
        "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"
    }
}
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "tmp.mount network.target systemd-journald.socket nss-lookup.target remote-fs.target basic.target -.mount 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": "3820", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3820", 
        "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@server69 opt]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since 一 2022-11-28 22:37:53 CST; 39s ago
     Docs: man:httpd(8)
           man:apachectl(8)

sysctl

远程主机sysctl配置

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m sysctl -a "name=net.ipv4.ip_forward value=1 reload=yes"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true
}
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true
}
[root@server69 opt]# cat /proc/sys/net/ipv4/ip_forward
1

user

远程主机用户管理

[root@server67 tmp]# ansible -i /etc/ansible/hosts web-servers -m user -a "name=legend state=present"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.88.69 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/legend", 
    "name": "legend", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}
192.168.88.70 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/legend", 
    "name": "legend", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}
[root@server69 opt]# id legend
uid=1001(legend) gid=1001(legend) 组=1001(legend)

 

你可能感兴趣的:(服务器,linux,ansible)