3.ansible常用模块02
Ansible常用模块:
- file 模块 :file模块可以创建文件,目录,链接;修改权限和属性等。
幂等性:任意次执行所产生的影响均与一次执行的影响相同。
# 新建文件 [root@db04 ansible]# ansible test -m file -a "path=/tmp/1.txt state=touch" # 新建目录 [root@db04 ansible]# ansible test -m file -a "path=/tmp/mydir state=directory"
# 修改文件权限和属性
[root@db04 ansible]# ansible test -m file -a "path=/tmp/1.txt owner=sshd group=adm mode=777"
# 删除目录 absent是删除 [root@db04 ansible]# ansible test -m file -a "path=/tmp/2 state=absent" # 删除文件 [root@db04 ansible]# ansible test -m file -a "path=/tmp/1.txt state=absent" # 创建一个软连接 [root@db04 ansible]# ansible db01 -m file -a "src=/etc/hosts path=/tmp/host.txt state=link"
- copy模块:将文件拷贝到远程主机
backup=yes 如果目标主机有同名文件,则先备份
# 将t.sh拷贝到远程的/root目录下 [root@db04 ansible]# ansible db01 -m copy -a "src=~/ansible/t.sh dest=/root/" # 通过content可以直接提供文件内容,\n代表回车。 [root@db04 ansible]# ansible db01 -m copy -a "content='hello world\n' dest=/root/hello.txt"
- fetch模块:可以将远程主机的文件拷贝到本地(与copy功能相反)
# 将远程主机上的文件给拷贝到本地家目录 [root@db04 ansible]# ansible test -m fetch -a "src=/etc/hostname dest=~/"
- lineinfile|replace模块
在修改单个文件的单行内容时可以使用lineinfile模块
# 在/etc/issue文件中添加一行内容hello world,默认添加到最后 [root@db04 ansible]# ansible test -m lineinfile -a "path=/etc/issue line='hello world'" # 基于幂等原则,重复执行,不会创建多行内容 [root@db04 ansible]# ansible test -m lineinfile -a "path=/etc/issue line='hello world'" # 将内容插入到Kernel行的后面 [root@db04 ansible]# ansible test -m lineinfile -a "path=/etc/issue line='insert' insertafter='Kernel'"
# 用replace模块可以替换其中某个关键词
[root@db04 ansible]# ansible test -m replace -a "path=/etc/issue regexp=hello replace=nihao"
小结:
file模块: 创建文件、修改权限等
copy模块:拷贝(推送)文件
fetch模块:拉取文件
lineinfile|replace:编辑文件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?