ansible module

文章介绍了如何使用Ansible的几个核心模块,包括查看版本、复制文件(copy和fetch)、执行命令(shell和command)、管理文件(file)、定时任务(cron)、软件包管理(yum)和服务管理(service)。这些操作展示了Ansible在自动化运维中的基本功能。
摘要由CSDN通过智能技术生成

查看ansible的版本

[root@ansible ansible]# ansible-doc --version
ansible-doc 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible-doc
  python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]

查看ansible的模块

[root@ansible ansible]# ansible-doc -l
fortios_router_community_list                                 Configure community list...
azure_rm_devtestlab_info                                      Get Azure DevTest Lab fa...
ecs_taskdefinition                                            register a task definiti...
avi_alertscriptconfig                                         Module for setup of Aler...
tower_receive                                                 Receive assets from Ansi...
netapp_e_iscsi_target                                         NetApp E-Series manage i...
azure_rm_acs                                                  Manage an Azure Containe...
fortios_log_syslogd2_filter                                   Filters for remote syste...
junos_rpc                                                     Runs an arbitrary RPC ov...
na_elementsw_vlan                                             NetApp Element Software ...
pn_ospf                                                       CLI command to add/remov...
pn_snmp_vacm                                                  CLI command to create/mo...
cp_mgmt_service_sctp                                          Manages service-sctp obj...
onyx_ospf                                                     Manage OSPF protocol on ...
icx_command                                                   Run arbitrary commands o...
cs_snapshot_policy                                            Manages volume snapshot ...
nxos_install_os                                               Set boot options like bo...
cnos_static_route                                             Manage static IP routes ...
win_eventlog                                                  Manage Windows event log...
vmware_category                                               Manage VMware categories
vmware_host_feature_info                                      Gathers info about an ES...
avi_cluster                                                   Module for setup of Clus...
na_ontap_user                                                 NetApp ONTAP user config...
aci_l3out                                                     Manage Layer 3 Outside (...
memset_server_info                                            Retrieve server informat...
gcp_compute_subnetwork_info                                   Gather info for GCP Subn...
azure_rm_virtualmachinescalesetextension                      Manage Azure Virtual Mac...
fortios_report_dataset                                        Report dataset configura...
avi_api_session                                               Avi API Module          
avi_networkprofile                                            Module for setup of Netw...
avi_backup                                                    Module for setup of Back...
aci_interface_policy_cdp                                      Manage CDP interface pol...
fortios_firewall_vip                                          Configure virtual IP for...
gcp_compute_backend_service                                   Creates a GCP BackendSer...
iam_policy                                                    Manage IAM policies for ...
......

统计所有模块个数
[root@ansible ansible]# ansible-doc -l|wc -l
3387

常用模块

copy 模块复制文件到每台机器上

支持的参数:

src    被复制到远程主机的本地文件。绝对路径或者是相对路径

content  用于替换"src",可以直接指定文件的内容

dest    将源文件复制到远程主机的绝对路径

backup  当文件内容发生改变后,在覆盖之前把源文件备份

force   当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制(默认为"yes")。

[root@ansible ~]# ansible web -m copy -a "src=/root/playbook.sh dest=/tmp mode=700"
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "558e05c0be04edb8afbff83cfa18dd95a8d104ec", 
    "dest": "/tmp/playbook.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4b5f59a8fe96fbf8e036304faad2ace0", 
    "mode": "0700", 
    "owner": "root", 
    "size": 51, 
    "src": "/root/.ansible/tmp/ansible-tmp-1681053247.62-7595-218379975599304/source", 
    "state": "file", 
    "uid": 0
}
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "558e05c0be04edb8afbff83cfa18dd95a8d104ec", 
    "dest": "/tmp/playbook.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4b5f59a8fe96fbf8e036304faad2ace0", 
    "mode": "0700", 
    "owner": "root", 
    "size": 51, 
    "src": "/root/.ansible/tmp/ansible-tmp-1681053249.64-7593-241143583622164/source", 
    "state": "file", 
    "uid": 0
}

[root@web-1 ~]# cd /tmp
[root@web-1 tmp]# ls
playbook.sh

[root@web-2 ~]# cd /tmp
[root@web-2 tmp]# ls
playbook.sh

fetch 模块:从远程主机拉取文件到本地

dest:用来存放文件的目录
src:在远程拉取的文件,并且必须是一个file,不能是目录

[root@ansible test]# ansible web -m fetch -a "src=/etc/passwd dest=/test"
192.168.102.139 | CHANGED => {
    "changed": true, 
    "checksum": "6b57f2976c0a452bffe74bc4e7dee2b464e3225a", 
    "dest": "/test/192.168.102.139/etc/passwd", 
    "md5sum": "01a59a257efbc1922d8aac180f9df71d", 
    "remote_checksum": "6b57f2976c0a452bffe74bc4e7dee2b464e3225a", 
    "remote_md5sum": null
}
192.168.102.140 | CHANGED => {
    "changed": true, 
    "checksum": "6b57f2976c0a452bffe74bc4e7dee2b464e3225a", 
    "dest": "/test/192.168.102.140/etc/passwd", 
    "md5sum": "01a59a257efbc1922d8aac180f9df71d", 
    "remote_checksum": "6b57f2976c0a452bffe74bc4e7dee2b464e3225a", 
    "remote_md5sum": null
}

[root@ansible test]# ls
192.168.102.139  192.168.102.140

[root@ansible test]# cd 192.168.102.139
[root@ansible 192.168.102.139]# cd etc
[root@ansible etc]# ls
passwd

command、shell 模块: 执行命令

shell模块比command模块更好,能够识别管道符号

[root@ansible ~]# ansible all -m command -a 'ip a|grep ens33'
192.168.102.139 | FAILED | rc=1 >>
Object "a|grep" is unknown, try "ip help".non-zero return code
192.168.102.140 | FAILED | rc=1 >>
Object "a|grep" is unknown, try "ip help".non-zero return code

[root@ansible ~]# ansible all -m shell -a 'ip a|grep ens33'
192.168.102.139 | CHANGED | rc=0 >>
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.102.139/24 brd 192.168.102.255 scope global noprefixroute dynamic ens33
192.168.102.140 | CHANGED | rc=0 >>
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.102.140/24 brd 192.168.102.255 scope global noprefixroute dynamic ens33

file 模块:建文件和文件夹

支持的参数:
group  定义文件/目录的所属组
owner    定义文件/目录的所属用户。后面必须跟上path:定义文件/目录的路径
dest    被链接到的路径,只应用于state=link的情况
state   状态,有以下选项:
    directory:如果目录不存在,就创建目录
    file:即使文件不存在,也不会被创建
    link:创建软链接
    hard:创建硬链接
    touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
    absent:删除目录、文件或者取消链接文件

[root@ansible ~]# ansible all -m file -a "path=/sc_ansible state=directory"
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/sc_ansible", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/sc_ansible", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}

[root@web-1 /]# ls
bin   dev  home  lib64  mnt  proc  run   sc_ansible  sys  usr
boot  etc  lib   media  opt  root  sbin  srv         tmp  var

[root@web-1 /]# cd sc_ansible/
[root@web-2 /]# ls
bin   dev  home  lib64  mnt  proc  run   sc_ansible  sys  usr
boot  etc  lib   media  opt  root  sbin  srv         tmp  var
[root@web-2 /]# cd sc_ansible/


[root@ansible ~]# ansible all -m file -a "path=/sc_ansible/liuhc.txt state=touch"
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/sc_ansible/liuhc.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/sc_ansible/liuhc.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}

[root@web-1 sc_ansible]# ls
liuhc.txt

[root@ansible ~]# ansible all -m file -a "src=/sc_ansible/liuhc.txt path=/sc_ansible/liuhc.link  state=link"
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/sc_ansible/liuhc.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 21, 
    "src": "/sc_ansible/liuhc.txt", 
    "state": "link", 
    "uid": 0
}
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/sc_ansible/liuhc.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 21, 
    "src": "/sc_ansible/liuhc.txt", 
    "state": "link", 
    "uid": 0
}

[root@web-1 sc_ansible]# ll
总用量 0
lrwxrwxrwx 1 root root 21 4月   9 23:28 liuhc.link -> /sc_ansible/liuhc.txt
-rw-r--r-- 1 root root  0 4月   9 23:26 liuhc.txt

corn 模块

day:  每天应该运行的工作( 1-31)
hour: 每小时 ( 0-23 )
minute:每分钟( 0-59 )
month:每月( 1-12 )
weekday:每周 ( 0-6 for Sunda y-Saturday)
job:指明运行的命令
name:定时任务描述
reboot :任务在重启时运行,不建议使用,建议使用special_time
special_time :特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
state:指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务
user :以哪个用户的身份执行

[root@web-1 sc_ansible]# vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed


[root@ansible ~]# ansible all -m cron -a "minute=0 hour=8-18 month=5 weekday=1-5 job='bash /root/iptables.sh' name=runiptables2"
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "runiptables2"
    ]
}
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "runiptables2"
    ]
}

[root@web-1 ~]# crontab -l
#Ansible: runiptables2
0 8-18 * 5 1-5 bash /root/iptables.sh

[root@ansible ~]# ansible all -m cron -a "name=runiptables2 state=absent"
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}

[root@web-1 ~]# crontab -l
[root@web-1 ~]# 

yum 模块

支持的参数:
name:安装包名称
state:
    present:安装
    installed:安装
    latest:安装最新的
    absent: 卸载软件

[root@ansible ~]# ansible all -m yum -a "name=tree state=absent"
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "removed": [
            "tree"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 tree.x86_64.0.1.6.0-10.el7 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package        架构             版本                     源               大小\n================================================================================\n正在删除:\n tree           x86_64           1.6.0-10.el7             @base            87 k\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:87 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : tree-1.6.0-10.el7.x86_64                                    1/1 \n  验证中      : tree-1.6.0-10.el7.x86_64                                    1/1 \n\n删除:\n  tree.x86_64 0:1.6.0-10.el7                                                    \n\n完毕!\n"
    ]
}
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "removed": [
            "tree"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 tree.x86_64.0.1.6.0-10.el7 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package        架构             版本                     源               大小\n================================================================================\n正在删除:\n tree           x86_64           1.6.0-10.el7             @base            87 k\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:87 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : tree-1.6.0-10.el7.x86_64                                    1/1 \n  验证中      : tree-1.6.0-10.el7.x86_64                                    1/1 \n\n删除:\n  tree.x86_64 0:1.6.0-10.el7                                                    \n\n完毕!\n"
    ]
}

[root@web-1 ~]# tree
-bash: /usr/bin/tree: 没有那个文件或目录

[root@ansible ~]# ansible all -m yum -a "name=tree state=installed"
[root@web-1 ~]# tree
.
├── anaconda-ks.cfg
└── sc

1 directory, 1 file

service 模块

支持的参数:
enabled :设置开机启动。
name : 服务名称
state :四种状态
     started:启动服务        stopped:停止服务
     restarted:重启服务     reloaded:重载配置

[root@ansible ~]# ansible all -m service -a "name=sshd state=stopped enabled=true"
192.168.102.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 


[root@ansible ~]# ansible all -m service -a "name=sshd state=restart enabled=true"
192.168.102.140 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.102.140 port 22: Connection refused", 
    "unreachable": true
}
192.168.102.139 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.102.139 port 22: Connection refused", 
    "unreachable": true
}

[root@web-1 ~]# service sshd restart
Redirecting to /bin/systemctl restart sshd.service

[root@web-2 ~]# service sshd restart
Redirecting to /bin/systemctl restart sshd.service

[root@ansible ~]# ansible all -m service -a "name=sshd state=restarted enabled=true"
192.168.102.140 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 

script 模块

该模块用于将本地的一个脚本文件在管理设备上执行,脚本文件需有可执行权限

[root@ansible ~]# ansible all -m script -a "/root/playbook.sh"
192.168.102.140 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.102.140 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.102.140 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.102.139 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.102.139 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.102.139 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

[root@web-1 ~]# ls
sc9723  sc_ip.txt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩未零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值