ansible常用模块

1.ansible常用模块使用详解

ansible常用模块raw、command、shell的区别:

shell模块调用的/bin/sh指令执行
command模块不是调用的shell的指令,所以没有bash的环境变量
raw很多地方和shell类似,更多的地方建议使用shell和command模块。但是如果是使用老版本python,需要用到raw,又或者是客户端是路由器,因为没有安装python模块,那就需要使用raw模块了

2.ansible常用模块之ping

ping模块用于检查指定节点机器是否连通,用法很简单,不涉及参数,主机如果在线,则回复pong

[root@ansible ansible]# ansible all -m ping
web.example.com | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

3.ansible常用模块之command

command模块用于在远程主机上执行命令,ansible默认就是使用command模块。

#查看受控机tmp目录下的文件
[root@ansible ansible]# ansible all -a 'ls /tmp'
web.example.com | CHANGED | rc=0 >>
ansible_command_payload_tdefdja5
systemd-private-eab7ffb825514f3ba217c051a7d97e02-chronyd.service-iOeHYz

# 在受控机tmp目录下创建一个hehe
[root@ansible ansible]# ansible all -a 'touch /tmp/hehe'
[WARNING]: Consider using the file module with state=touch rather than running
'touch'.  If you need to use command because file is insufficient you can add
'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg
to get rid of this message.
web.example.com | CHANGED | rc=0 >>

#查看是否创建成功
[root@ansible ansible]# ansible all -a 'ls /tmp'
web.example.com | CHANGED | rc=0 >>
ansible_command_payload_e6tmdo8q
hehe
systemd-private-eab7ffb825514f3ba217c051a7d97e02-chronyd.service-iOeHYz

#command模块不支持管道符
[root@ansible ansible]# ansible all -a "echo 'hello world' > /tmp/hehe"
web.example.com | CHANGED | rc=0 >>
hello world > /tmp/hehe
[root@ansible ansible]# ansible all -a 'cat /tmp/hehe'
web.example.com | CHANGED | rc=0 >>

#切换到受管机查看未发现 hehe文件内有内容
[root@web ~]# cat /tmp/hehe 
[root@web ~]# 

#不支持重定向
[root@ansible ansible]# ansible all -a 'ps -ef|grep vsftpd'
web.example.com | FAILED | rc=1 >>
error: unsupported SysV option

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).non-zero return code

4. ansible常用模块之raw

raw模块用于在远程主机上执行命令,其支持管道符与重定向

#支持重定向
[root@ansible ansible]# ansible all -m raw -a 'echo "hello world" > /tmp/hehe'
web.example.com | CHANGED | rc=0 >>
Shared connection to web.example.com closed.

[root@ansible ansible]# ansible all -a 'cat /tmp/hehe'
web.example.com | CHANGED | rc=0 >>
hello world

#支持管道符
[root@ansible ansible]# ansible all -m raw -a 'cat /tmp/hehe | grep -Eo hello '
web.example.com | CHANGED | rc=0 >>
hello
Shared connection to web.example.com closed.

5. ansible常用模块之shell

shell模块用于在受控机上执行受控机上的脚本,亦可直接在受控机上执行命令。
shell模块亦支持管道与重定向。

#查看受控机脚本
[root@web ~]# cat test.sh 
#!/bin/bash
nohup sleep 7000 &

#执行脚本
[root@ansible ansible]# ansible all -m shell -a '/bin/bash /root/test.sh'
web.example.com | CHANGED | rc=0 >>

[root@ansible ansible]# ansible all -m shell -a 'ps -ef | grep sleep'
web.example.com | CHANGED | rc=0 >>
root       74979       1  0 04:50 ?        00:00:00 sleep 7000

6. ansible常用模块之script

script模块用于在受控机上执行主控机上的脚本

[root@ansible scripts]# ansible all -m script -a '/etc/ansible/scripts/a.sh & >/tmp/a'
web.example.com | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to web.example.com closed.\r\n",
    "stderr_lines": [
        "Shared connection to web.example.com closed."
    ],
    "stdout": "",
    "stdout_lines": []
}

[root@ansible scripts]# ansible all -m shell -a 'cat /tmp/a'
web.example.com | CHANGED | rc=0 >>

[root@ansible scripts]# ansible all -m shell -a 'ps -ef | grep sleep'
web.example.com | CHANGED | rc=0 >>
root      183277       1  0 05:48 ?        00:00:00 sleep 5000

//由此可见确是在受控机上执行了主控机上的脚本,且输出记录到了受控机上。因为此处 \
//的jerry用户是在受控机上才有的用户

7. ansible常用模块之template

template模块用于生成一个模板,并可将其传输至远程主机上。

#为受管主机配置阿里源
[root@ansible scripts]# ansible all -m shell -a  'rm -rf /etc/yum.repos.d/*'
[WARNING]: Consider using the file module with state=absent rather than running
'rm'.  If you need to use command because file is insufficient you can add 'warn:
false' to this command task or set 'command_warnings=False' in ansible.cfg to get
rid of this message.  //告警信息可无视
web.example.com | CHANGED | rc=0 >>

#切换到受管主机查看
[root@web ~]# ls /etc/yum.repos.d/
[root@web ~]# 

#阿里源的文件传到兽管主机
[root@ansible scripts]# ansible all -m template -a 'src=/etc/yum.repos.d/CentOS-Base.repo dest=/etc/yum.repos.d/CentOS-Base.repo owner=root group=root mode=0644'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "8bbf30b2d80c3b97292ca7b32f33ef494269a5b8",
    "dest": "/etc/yum.repos.d/CentOS-Base.repo",
    "gid": 0,
    "group": "root",
    "md5sum": "ed031c350da2532e6a8d09a4d9b05278",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:system_conf_t:s0",
    "size": 1653,
    "src": "/root/.ansible/tmp/ansible-tmp-1653472936.8950183-294061-30861987625384/source",
    "state": "file",
    "uid": 0
}

#切换受管主机查看
[root@web ~]# ll /etc/yum.repos.d/
总用量 4
-rw-r--r--. 1 root root 1653 525 06:02 CentOS-Base.repo

8. ansible常用模块之yum

yum模块用于在指定节点机器上通过yum管理软件,其支持的参数主要有两个

  • name:要管理的包名
  • state:要进行的操作
    state常用的值:
  • latest:安装软件
  • installed:安装软件
  • present:安装软件
  • removed:卸载软件
  • absent:卸载软件

若想使用yum来管理软件,请确保受控机上的yum源无异常。

#在受控机上查询看vsftpd软件是否安装
root@web ~]# rpm -qa | grep vsftpd
[root@web ~]# 

#在ansible主机上使用yum模块在受控机上安装vsftpd
[root@ansible ~]# ansible all -m yum -a 'name=vsftpd state=present'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: vsftpd-3.0.3-34.el8.x86_64"
    ]
}

#查看受控机上是否安装了vsftpd
[root@web ~]# rpm -qa | grep vsftpd
vsftpd-3.0.3-34.el8.x86_64

9.ansible常用模块之copy

copy模块用于复制文件至远程受控机。

#将test文件传输到受管主机的opt目录内
[root@ansible ~]# echo "holle world" > /opt/test
[root@ansible ~]# ansible all -m copy -a 'src=/opt/test dest=/opt/'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "1fd8781f95c73f7d47b85fc5ece1f88233aad000",
    "dest": "/opt/test",
    "gid": 0,
    "group": "root",
    "md5sum": "a6c80a31858e6196d0e363186887457d",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:usr_t:s0",
    "size": 12,
    "src": "/root/.ansible/tmp/ansible-tmp-1653474200.9157233-352757-269556345651388/source",
    "state": "file",
    "uid": 0
}

#查看
[root@web ~]# cat /opt/test 
holle world

10. ansible常用模块之group

group模块用于在受控机上添加或删除组。

#创建组apache gid为2000
[root@ansible ~]# ansible all -m group -a 'name=apache gid=2000 state=present'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 2000,
    "name": "apache",
    "state": "present",
    "system": false
}

[root@web ~]# grep apache /etc/group
apache:x:2000:

#删除组
[root@ansible ~]# ansible all -m group -a 'name=apache state=absent'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "name": "apache",
    "state": "absent"
}

#查看
[root@web ~]# grep apache /etc/group
[root@web ~]# 

1. ansible常用模块之user

user模块用于管理受控机的用户帐号。

[root@ansible ~]# ansible all -m user -a 'name=apache uid=500 system=yes create_home=no shell=/sbin/nologin state=present'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "comment": "",
    "create_home": false,
    "group": 500,
    "home": "/home/apache",
    "name": "apache",
    "shell": "/sbin/nologin",
    "state": "present",
    "system": true,
    "uid": 500
}

#查看
[root@web ~]# id apache 
uid=500(apache) gid=500(apache)=500(apache)

#删除用户
[root@ansible ~]# ansible all -m user -a 'name=apache state=absent'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "force": false,
    "name": "apache",
    "remove": false,
    "state": "absent"
}

#查看
[root@web ~]# id apache
id: “apache”:无此用户

12. ansible常用模块之service

service模块用于管理受控机上的服务。

#设置vsftpd 开机自启 启动
[root@ansible ~]# ansible all -m user -a 'name=apache uid=500 system=yes create_home=no shell=/sbin/nologin state=present'
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "comment": "",
    "create_home": false,
    "group": 500,
    "home": "/home/apache",
    "name": "apache",
    "shell": "/sbin/nologin",
    "state": "present",
    "system": true,
[root@ansible ~]# ansible all -m service -a 'name=vsftpd enabled=yes state=started' 
web.example.com | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "enabled": true,
    "name": "vsftpd",
    "state": "started",
    "status": {
        "ActiveEnterTimestampMonotonic": "0",
        "ActiveExitTimestampMonotonic": "0",
        "ActiveState": "inactive",
        "After": "basic.target network-online.target systemd-journald.socket sysinit.target system.slice",
        "AllowIsolate": "no",
        "AllowedCPUs": "",
        "AllowedMemoryNodes": "",
        "AmbientCapabilities": "",
        "AssertResult": "no",
        "AssertTimestampMonotonic": "0",
        "Before": "shutdown.target",
        "BlockIOAccounting": "no",
        "BlockIOWeight": "[not set]",
        "CPUAccounting": "no",
        "CPUAffinity": "",
        "CPUQuotaPerSecUSec": "infinity",
        "CPUSchedulingPolicy": "0",
        "CPUSchedulingPriority": "0",
        "CPUSchedulingResetOnFork": "no",
        "CPUShares": "[not set]",
        "CPUUsageNSec": "[not set]",
        "CPUWeight": "[not set]",
        "CacheDirectoryMode": "0755",
        "CanIsolate": "no",
        "CanReload": "no",
        "CanStart": "yes",
        "CanStop": "yes",
        "CapabilityBoundingSet": "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 cap_wake_alarm cap_block_suspend",
        "CollectMode": "inactive",
        "ConditionResult": "no",
        "ConditionTimestampMonotonic": "0",
        "ConfigurationDirectoryMode": "0755",
        "Conflicts": "shutdown.target",
        "ControlPID": "0",
        "DefaultDependencies": "yes",
        "Delegate": "no",
        "Description": "Vsftpd ftp daemon",
        "DevicePolicy": "auto",
        "DynamicUser": "no",
        "EffectiveCPUs": "",
        "EffectiveMemoryNodes": "",
        "ExecMainCode": "0",
        "ExecMainExitTimestampMonotonic": "0",
        "ExecMainPID": "0",
        "ExecMainStartTimestampMonotonic": "0",
        "ExecMainStatus": "0",
        "ExecStart": "{ path=/usr/sbin/vsftpd ; argv[]=/usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf ; 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/vsftpd.service",
        "GID": "[not set]",
        "GuessMainPID": "yes",
        "IOAccounting": "no",
        "IOSchedulingClass": "0",
        "IOSchedulingPriority": "0",
        "IOWeight": "[not set]",
        "IPAccounting": "no",
        "IPEgressBytes": "18446744073709551615",
        "IPEgressPackets": "18446744073709551615",
        "IPIngressBytes": "18446744073709551615",
        "IPIngressPackets": "18446744073709551615",
        "Id": "vsftpd.service",
        "IgnoreOnIsolate": "no",
        "IgnoreSIGPIPE": "yes",
        "InactiveEnterTimestampMonotonic": "0",
        "InactiveExitTimestampMonotonic": "0",
        "JobRunningTimeoutUSec": "infinity",
        "JobTimeoutAction": "none",
        "JobTimeoutUSec": "infinity",
        "KeyringMode": "private",
        "KillMode": "control-group",
        "KillSignal": "15",
        "LimitAS": "infinity",
        "LimitASSoft": "infinity",
        "LimitCORE": "infinity",
        "LimitCORESoft": "infinity",
        "LimitCPU": "infinity",
        "LimitCPUSoft": "infinity",
        "LimitDATA": "infinity",
        "LimitDATASoft": "infinity",
        "LimitFSIZE": "infinity",
        "LimitFSIZESoft": "infinity",
        "LimitLOCKS": "infinity",
        "LimitLOCKSSoft": "infinity",
        "LimitMEMLOCK": "65536",
        "LimitMEMLOCKSoft": "65536",
        "LimitMSGQUEUE": "819200",
        "LimitMSGQUEUESoft": "819200",
        "LimitNICE": "0",
        "LimitNICESoft": "0",
        "LimitNOFILE": "262144",
        "LimitNOFILESoft": "1024",
        "LimitNPROC": "7062",
        "LimitNPROCSoft": "7062",
        "LimitRSS": "infinity",
        "LimitRSSSoft": "infinity",
        "LimitRTPRIO": "0",
        "LimitRTPRIOSoft": "0",
        "LimitRTTIME": "infinity",
        "LimitRTTIMESoft": "infinity",
        "LimitSIGPENDING": "7062",
        "LimitSIGPENDINGSoft": "7062",
        "LimitSTACK": "infinity",
        "LimitSTACKSoft": "8388608",
        "LoadState": "loaded",
        "LockPersonality": "no",
        "LogLevelMax": "-1",
        "LogRateLimitBurst": "0",
        "LogRateLimitIntervalUSec": "0",
        "LogsDirectoryMode": "0755",
        "MainPID": "0",
        "MemoryAccounting": "yes",
        "MemoryCurrent": "[not set]",
        "MemoryDenyWriteExecute": "no",
        "MemoryHigh": "infinity",
        "MemoryLimit": "infinity",
        "MemoryLow": "0",
        "MemoryMax": "infinity",
        "MemorySwapMax": "infinity",
        "MountAPIVFS": "no",
        "MountFlags": "",
        "NFileDescriptorStore": "0",
        "NRestarts": "0",
        "NUMAMask": "",
        "NUMAPolicy": "n/a",
        "Names": "vsftpd.service",
        "NeedDaemonReload": "no",
        "Nice": "0",
        "NoNewPrivileges": "no",
        "NonBlocking": "no",
        "NotifyAccess": "none",
        "OOMScoreAdjust": "0",
        "OnFailureJobMode": "replace",
        "PermissionsStartOnly": "no",
        "Perpetual": "no",
        "PrivateDevices": "no",
        "PrivateMounts": "no",
        "PrivateNetwork": "no",
        "PrivateTmp": "no",
        "PrivateUsers": "no",
        "ProtectControlGroups": "no",
        "ProtectHome": "no",
        "ProtectKernelModules": "no",
        "ProtectKernelTunables": "no",
        "ProtectSystem": "no",
        "RefuseManualStart": "no",
        "RefuseManualStop": "no",
        "RemainAfterExit": "no",
        "RemoveIPC": "no",
        "Requires": "system.slice sysinit.target",
        "Restart": "no",
        "RestartUSec": "100ms",
        "RestrictNamespaces": "no",
        "RestrictRealtime": "no",
        "RestrictSUIDSGID": "no",
        "Result": "success",
        "RootDirectoryStartOnly": "no",
        "RuntimeDirectoryMode": "0755",
        "RuntimeDirectoryPreserve": "no",
        "RuntimeMaxUSec": "infinity",
        "SameProcessGroup": "no",
        "SecureBits": "0",
        "SendSIGHUP": "no",
        "SendSIGKILL": "yes",
        "Slice": "system.slice",
        "StandardError": "inherit",
        "StandardInput": "null",
        "StandardInputData": "",
        "StandardOutput": "journal",
        "StartLimitAction": "none",
        "StartLimitBurst": "5",
        "StartLimitIntervalUSec": "10s",
        "StartupBlockIOWeight": "[not set]",
        "StartupCPUShares": "[not set]",
        "StartupCPUWeight": "[not set]",
        "StartupIOWeight": "[not set]",
        "StateChangeTimestampMonotonic": "0",
        "StateDirectoryMode": "0755",
        "StatusErrno": "0",
        "StopWhenUnneeded": "no",
        "SubState": "dead",
        "SuccessAction": "none",
        "SyslogFacility": "3",
        "SyslogLevel": "6",
        "SyslogLevelPrefix": "yes",
        "SyslogPriority": "30",
        "SystemCallErrorNumber": "0",
        "TTYReset": "no",
        "TTYVHangup": "no",
        "TTYVTDisallocate": "no",
        "TasksAccounting": "yes",
        "TasksCurrent": "[not set]",
        "TasksMax": "11300",
        "TimeoutStartUSec": "1min 30s",
        "TimeoutStopUSec": "1min 30s",
        "TimerSlackNSec": "50000",
        "Transient": "no",
        "Type": "forking",
        "UID": "[not set]",
        "UMask": "0022",
        "UnitFilePreset": "disabled",
        "UnitFileState": "disabled",
        "UtmpMode": "init",
        "WatchdogTimestampMonotonic": "0",
        "WatchdogUSec": "0"
    }
}

#受控机查看
[root@web ~]# systemctl status vsftpd
● vsftpd.service - Vsftpd ftp daemon
   Loaded: loaded (/usr/lib/systemd/system/vsftpd.service; enabled; vendor preset:>
   Active: active (running) since Wed 2022-05-25 06:49:01 EDT; 1min 6s ago
  Process: 322871 ExecStart=/usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf (code=exited,>
 Main PID: 322876 (vsftpd)
    Tasks: 1 (limit: 11300)
   Memory: 552.0K
   CGroup: /system.slice/vsftpd.service
           └─322876 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf

525 06:49:01 web.example.com systemd[1]: Starting Vsftpd ftp daemon...
525 06:49:01 web.example.com systemd[1]: Started Vsftpd ftp daemon.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值