ansible常用模块

本文详细介绍了Ansible的多个常用模块,包括ping、command、shell、raw、script、template、yum、copy、group、user和服务管理等,分别阐述了它们的功能、使用场景和区别。例如,ping模块用于检查节点连通性,command与shell模块的区别在于是否使用shell环境,yum模块用于管理软件包,而service模块则用于控制服务的启动、停止和状态检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.ansible常用模块使用详解

ansible常用模块有:

ping
yum
template
copy
user
group
service
raw
command
shell
script

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

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

2.ansible常用模块之ping

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

[root@localhost ~]# ansible all -m ping
192.168.175.132 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

3.ansible常用模块之command

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

command模块有一个缺陷就是不能使用管道符和重定向功能。

用command模块在受管主机上面添加东西
[root@localhost ~]# ansible all -a 'echo "hello world" > /root/hehe'
192.168.175.132 | CHANGED | rc=0 >>
hello world > /root/hehe
受管主机验证,发现虽然没有报错但是也并没有执行
[root@localhost ~]# ls
anaconda-ks.cfg
[root@localhost ~]# pwd
/root

用shell模块执行
[root@localhost ~]# ansible all -m shell -a 'echo "hello world" > /root/hehe'
192.168.175.132 | CHANGED | rc=0 >>
受管机验证
[root@localhost ~]# ls
anaconda-ks.cfg  hehe

4.ansible常用模块之raw

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

用raw模块执行
[root@localhost ~]# ansible all -m raw -a 'echo "hello world" > /tmp/hehe'
192.168.175.132 | CHANGED | rc=0 >>
Shared connection to 192.168.175.132 closed.
受管机验证
[root@localhost ~]# ls /tmp
hehe
ks-script-YvsG5T
systemd-private-67371fc9406f4386a4a265bfe3dd1890-vmtoolsd.service-xIynei
systemd-private-cffea14a98ba4b7a9cf78040f5c2d556-vmtoolsd.service-lumIWZ
yum.log
执行管道符
[root@localhost ~]# ansible all -m raw -a 'cat /tmp/hehe|grep -Eo hello'
192.168.175.132 | CHANGED | rc=0 >>
hello
Shared connection to 192.168.175.132 closed.

5.ansible常用模块之shell

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

[root@localhost ~]# ansible all -m shell -a 'uptime'
192.168.175.132 | CHANGED | rc=0 >>
 14:14:59 up  5:20,  2 users,  load average: 0.16, 0.05, 0.06

6.ansible常用模块之script

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

控制机上面编写一个脚本并且给执行权限
[root@localhost ~]# vim test.sh
[root@localhost ~]# cat test.sh
#!/bin/bash

echo "hello world"
[root@localhost ~]# chmod +x test.sh 
[root@localhost ~]# ls
anaconda-ks.cfg  test.sh
执行的时候直接接上文件,前提是文件有执行权限
[root@localhost ~]# ansible all -m script -a '/root/test.sh'
192.168.175.132 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.175.132 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.175.132 closed."
    ],
    "stdout": "hello world\r\n",
    "stdout_lines": [
        "hello world"
    ]
}

7.ansible常用模块之template

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

//下载一个163的yum源文件并开启此源
[root@ansible ~]# cd /etc/yum.repos.d/
[root@ansible yum.repos.d]# curl -o CentOS7-Base-163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@localhost ~]# sed -i 's/\$releasever/7/g' /etc/yum.repos.d/CentOS7-Base-163.repo
[root@localhost ~]# sed -i 's/^enabled=.*/enabled=1/g' /etc/yum.repos.d/CentOS7-Base-163.repo

//将设置好的163源传到受控主机
[root@ansible ~]# ansible 172.16.103.129 -m template -a 'src=/etc/yum.repos.d/CentOS7-Base-163.repo dest=/etc/yum.repos.d/163.repo'
192.168.175.132 | SUCCESS => {
    "changed": true,
    "checksum": "60b8868e0599489038710c45025fc11cbccf35f2",
    "dest": "/etc/yum.repos.d/163.repo",
    "gid": 0,
    "group": "root",
    "md5sum": "5a3e688854d9ceccf327b953dab55b21",
    "mode": "0644",
    "owner": "root",
    "size": 1462,
    "src": "/root/.ansible/tmp/ansible-tmp-1536311319.27-78101453778196/source",
    "state": "file",
    "uid": 0
}

//查看受控机上是否有163源
[root@localhost ~]# ls /etc/yum.repos.d/
163.repo

8.ansible常用模块之yum

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

name:要管理的包名
state:要进行的操作
state常用的值:

latest:安装最新软件
installed:安装软件
present:安装软件
removed:卸载软件
absent:卸载软件
若想使用yum来管理软件,请确保受控机上的yum源无异常。

//如果受管机是8建议用dnf,如果是7建议用yum(此时我受管机用的是centos7,控制机是rhel 8)

安装zsh
[root@localhost ~]# ansible all -m yum -a 'name=zsh state=present'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "installed": [
            "zsh"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.nju.edu.cn\n * extras: mirrors.nju.edu.cn\n * updates: mirrors.nju.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package zsh.x86_64 0:5.0.2-34.el7_8.2 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package       Arch             Version                    Repository      Size\n================================================================================\nInstalling:\n zsh           x86_64           5.0.2-34.el7_8.2           base           2.4 M\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 2.4 M\nInstalled size: 5.6 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : zsh-5.0.2-34.el7_8.2.x86_64                                  1/1 \n  Verifying  : zsh-5.0.2-34.el7_8.2.x86_64                                  1/1 \n\nInstalled:\n  zsh.x86_64 0:5.0.2-34.el7_8.2                                                 \n\nComplete!\n"
    ]
}
验证受管机是否安装zsh
[root@localhost ~]# rpm -qa |grep zsh
zsh-5.0.2-34.el7_8.2.x86_64

卸载zsh
[root@localhost ~]# ansible all -m yum -a 'name=zsh state=absent'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "removed": [
            "zsh"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package zsh.x86_64 0:5.0.2-34.el7_8.2 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package      Arch            Version                      Repository      Size\n================================================================================\nRemoving:\n zsh          x86_64          5.0.2-34.el7_8.2             @base          5.6 M\n\nTransaction Summary\n================================================================================\nRemove  1 Package\n\nInstalled size: 5.6 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Erasing    : zsh-5.0.2-34.el7_8.2.x86_64                                  1/1 \n  Verifying  : zsh-5.0.2-34.el7_8.2.x86_64                                  1/1 \n\nRemoved:\n  zsh.x86_64 0:5.0.2-34.el7_8.2                                                 \n\nComplete!\n"
    ]
}
验证是否被卸载
[root@localhost ~]# rpm -qa |grep zsh
[root@localhost ~]# 

9.ansible常用模块之copy

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

把控制机上面的文件拷贝到受管机
[root@localhost ~]# ls /tmp/
ks-script-_x0j988b           vmware-root_1088-2697008413
vmware-root_1051-4290625343
[root@localhost ~]# ansible 192.168.175.132 -m copy -a 'src=/tmp/ks-script-_x0j988b dest=/root/'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "6a51bb095194a9ba04bc884d98d44de30458b7de",
    "dest": "/root/ks-script-_x0j988b",
    "gid": 0,
    "group": "root",
    "md5sum": "5cf9efefbf790e6f21a403ce488fbcaa",
    "mode": "0644",
    "owner": "root",
    "size": 1379,
    "src": "/root/.ansible/tmp/ansible-tmp-1609830381.652375-2786-185528650481207/source",
    "state": "file",
    "uid": 0
}
验证
[root@localhost ~]# ls
anaconda-ks.cfg  hehe  ks-script-_x0j988b

10.ansible常用模块之group

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

在控制机上面执行在受管机添加runtime的组
[root@localhost ~]# ansible all -m group -a 'name=runtime state=present'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "gid": 1001,
    "name": "runtime",
    "state": "present",
    "system": false
}
受管机验证
[root@localhost ~]# grep runtime /etc/group
runtime:x:1001:

删除组
[root@localhost ~]# ansible all -m group -a 'name=runtime state=absent'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "runtime",
    "state": "absent"
}
验证
[root@localhost ~]# grep runtime /etc/group
[root@localhost ~]# 

11.ansible常用模块之user

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

添加tom的用户
[root@localhost ~]# ansible all -m user -a 'name=tom uid=5000 state=present'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 5000,
    "home": "/home/tom",
    "name": "tom",
    "shell": "/bin/bash",
    "state": "present",
    "stderr": "useradd: warning: the home directory already exists.\nNot copying any file from skel directory into it.\nCreating mailbox file: File exists\n",
    "stderr_lines": [
        "useradd: warning: the home directory already exists.",
        "Not copying any file from skel directory into it.",
        "Creating mailbox file: File exists"
    ],
    "system": false,
    "uid": 5000
}
验证
[root@localhost ~]# id tom
uid=5000(tom) gid=5000(tom) 组=5000(tom)

修改用户的uid信息,(修改不用写state状态)
[root@localhost ~]# ansible all -m user -a 'name=tom uid=2000'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "append": false,
    "changed": true,
    "comment": "",
    "group": 5000,
    "home": "/home/tom",
    "move_home": false,
    "name": "tom",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 2000
}
验证
[root@localhost ~]# id tom
uid=2000(tom) gid=5000(tom) 组=5000(tom)

删除用户
[root@localhost ~]# ansible all -m user -a 'name=tom state=absent'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "force": false,
    "name": "tom",
    "remove": false,
    "state": "absent"
}
验证
[root@localhost ~]# id tom
id: tom: no such user

12.ansible常用模块之service

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

可以发现受控机上面有一个邮箱服务并且开启
[root@localhost ~]# ss -antl
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128     *:22                  *:*                  
LISTEN      0      100    127.0.0.1:25                  *:*                  
LISTEN      0      128    :::22                 :::*                  
LISTEN      0      100       ::1:25                 :::*                  
[root@localhost ~]# systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
   Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; vendor preset: disabled)
   Active: active (running) since 二 2021-01-05 08:54:21 CST; 6h ago
 Main PID: 1549 (master)
   CGroup: /system.slice/postfix.service
           ├─1549 /usr/libexec/postfix/master -w
           ├─1571 qmgr -l -t unix -u
           └─3446 pickup -l -t unix -u

1月 05 08:54:21 localhost.localdomain systemd[1]: Starting Postfi...
1月 05 08:54:21 localhost.localdomain postfix/postfix-script[1525]: ...
1月 05 08:54:21 localhost.localdomain postfix/master[1549]: daemo...
1月 05 08:54:21 localhost.localdomain systemd[1]: Started Postfix...
Hint: Some lines were ellipsized, use -l to show in full.

停掉邮箱服务
[root@localhost ~]# ansible all -m service -a 'name=postfix state=stopped'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "postfix",
    "state": "stopped",
    "status": {
        "ActiveEnterTimestamp": "Tue 2021-01-05 08:54:21 CST",
        "ActiveEnterTimestampMonotonic": "21926620",
        "ActiveExitTimestampMonotonic": "0",
        "ActiveState": "active",
 ..........
 验证
 [root@localhost ~]# systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
   Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since 二 2021-01-05 15:22:18 CST; 3s ago
  Process: 4773 ExecStop=/usr/sbin/postfix stop (code=exited, status=0/SUCCESS)
 Main PID: 1549 (code=killed, signal=TERM)

1月 05 08:54:21 localhost.localdomain systemd[1]: Starting Postfi...
1月 05 08:54:21 localhost.localdomain postfix/postfix-script[1525]: ...
1月 05 08:54:21 localhost.localdomain postfix/master[1549]: daemo...
1月 05 08:54:21 localhost.localdomain systemd[1]: Started Postfix...
1月 05 15:22:18 localhost.localdomain systemd[1]: Stopping Postfi...
1月 05 15:22:18 localhost.localdomain postfix/postfix-script[4779]: ...
1月 05 15:22:18 localhost.localdomain postfix/master[1549]: termi...
1月 05 15:22:18 localhost.localdomain systemd[1]: Stopped Postfix...
Hint: Some lines were ellipsized, use -l to show in full.
开启
[root@localhost ~]# ansible all -m service -a 'name=postfix state=started'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "postfix",
    "state": "started",
    "status": {
        "ActiveEnterTimestamp": "Tue 2021-01-05 08:54:21 CST",
        "ActiveEnterTimestampMonotonic": "21926620",
        "ActiveExitTimestamp": "Tue 2021-01-05 15:22:18 CST",
        "ActiveExitTimestampMonotonic": "23298330250",
        "ActiveState": "inactive",
  不开启邮箱服务  把enabled改为no即可
[root@localhost ~]# ansible all -m service -a 'name=postfix enabled=no'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "enabled": false,
    "name": "postfix",
    "status": {
        "ActiveEnterTimestamp": "Tue 2021-01-05 15:23:51 CST",
        "ActiveEnterTimestampMonotonic": "23391431990",
        "ActiveExitTimestamp": "Tue 2021-01-05 15:22:18 CST",
        "ActiveExitTimestampMonotonic": "23298330250",
        "ActiveState": "active",     
 开启并重启
 [root@localhost ~]# ansible all -m service -a 'name=postfix enabled=yes state=restarted'
192.168.175.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "enabled": true,
    "name": "postfix",
    "state": "started",
    "status": {
        "ActiveEnterTimestamp": "Tue 2021-01-05 15:23:51 CST",
        "ActiveEnterTimestampMonotonic": "23391431990",
        "ActiveExitTimestamp": "Tue 2021-01-05 15:22:18 CST",
        "ActiveExitTimestampMonotonic": "23298330250",
        "ActiveState": "active",   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值