Ansible模块——文件内容修改

修改文件单行内容

ansible.builtin.lineinfile 可以按行修改文件内容,一次修改一行,支持正则表达式。

选项名

类型

默认值

描述

attributesstrnull

设置目标文件的 Linux 文件系统属性(attribute bits),作用类似于 chattr 命令。例如:+i 设置为不可变,+a 设置为只能追加写入等。

backrefsboolfalse

使用 regexp 和 line 时,是否启用后向引用替换。(使用正则分组时需要设置为 true)。

backupboolfalse

修改文件前是否创建备份。备份文件将带有时间戳后缀。

createboolfalse

文件不存在时是否创建新文件。

firstmatchboolfalse

如果为 true,当 regexp 匹配多行时,只对第一行执行操作。

groupstrnull

设置文件的属组。

insertafterstrEOF

在匹配到的行之后插入。如果为 EOF,则追加到末尾。

insertbeforestrnull

在匹配到的行之前插入。如果为 BOF,则追加到开头。

linestrnull

要插入或替换的行内容。

moderawnull

设置文件权限(八进制形式,或 preserve 保留现有)。

others

ansible.builtin.file

 模块接受的所有参数在这里也同样有效。

ownerstrnull

设置文件的属主。

pathpath

必需项

,目标文件的完整路径。

regexpstrnull

匹配要替换行的正则表达式。

search_stringstrnull

替代 regexp 的简易字符串匹配(不支持正则)。

selevelstrnull

SELinux context 中的 level。

serolestrnull

SELinux context 中的 role。

setypestrnull

SELinux context 中的 type。

seuserstrnull

SELinux context 中的 user。

statestrpresent

设置为 present 插入或修改行,或 absent 删除匹配行。

unsafe_writesboolfalse

是否禁用临时文件写入机制(兼容某些挂载类型如 NFS)。

validatestrnull

在写入前校验文件内容的命令(如 nginx -t -c %s)。

常用选项:

选项名

类型

默认值

描述

backrefsboolfalse

使用 regexp 和 line 时,是否启用后向引用替换。(使用正则分组时需要设置为 true)。

backupboolfalse

修改文件前是否创建备份。备份文件将带有时间戳后缀。

createboolfalse

文件不存在时是否创建新文件。

ownerstrnull

设置文件的属主。

groupstrnull

设置文件的属组。

insertafterstrEOF

在匹配到的行之后插入。如果为 EOF,则追加到末尾。

insertbeforestrnull

在匹配到的行之前插入。如果为 BOF,则追加到开头。

linestrnull

要插入或替换的行内容。

moderawnull

设置文件权限(八进制形式,或 preserve 保留现有)。

others

ansible.builtin.file

 模块接受的所有参数在这里也同样有效。

pathpath

必需项

,目标文件的完整路径。

regexpstrnull

匹配要替换行的正则表达式。

search_stringstrnull

替代 regexp 的简易字符串匹配(不支持正则)。

statestrpresent

设置为 present 插入或修改行,或 absent 删除匹配行。

validatestrnull

在写入前校验文件内容的命令(如 nginx -t -c %s)。

- name: Ensure SELinux is set to enforcing modeansible.builtin.lineinfile:path: /etc/selinux/configregexp: '^SELINUX='line: SELINUX=enforcing- name: Make sure group wheel is not in the sudoers configurationansible.builtin.lineinfile:path: /etc/sudoersstate: absentregexp: '^%wheel'- name: Replace a localhost entry with our ownansible.builtin.lineinfile:path: /etc/hostsregexp: '^127\.0\.0\.1'line: 127.0.0.1 localhostowner: rootgroup: rootmode: '0644'- name: Ensure the default Apache port is 8080ansible.builtin.lineinfile:path: /etc/httpd/conf/httpd.confregexp: '^Listen 'insertafter: '^#Listen 'line: Listen 8080- name: Add a line to a file if the file does not exist, without passing regexpansible.builtin.lineinfile:path: /tmp/testfileline: 192.168.1.99 foo.lab.net foocreate: yes- name: Ensure the JBoss memory settings are exactly as neededansible.builtin.lineinfile:path: /opt/jboss-as/bin/standalone.confregexp: '^(.*)Xms(\d+)m(.*)$'line: '\1Xms${xms}m\3'backrefs: yes- name: Validate the sudoers file before savingansible.builtin.lineinfile:path: /etc/sudoersstate: presentregexp: '^%ADMIN ALL='line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'validate: /usr/sbin/visudo -cf %s

其他的选项都好理解,一眼就能看出来,insertafter 和 insertbefore 我解释一下,上边有个例子用了 insertafter,可以看到同时也使用了 regexp,加了这个和不加是有区别的,可以看下边的例子。

有个文件,内容如下:

[root@awx-1 ansible]# cat /tmp/test
#test
#test
Listen=80
#test
#test
#test

playbook 内容如下:

---
- name: testhosts: localhosttasks:- name: Lineinfile testansible.builtin.lineinfile:line: "Listen=8080"#regexp: "^Listen="insertafter: "^#Listen="path: /tmp/test

playbook 想实现的是在 #Listen= 后添加 Listen=8080,但是有个特殊情况,文件可能不包含 #Listen=regexp 被我注释了,我们看下没有 regexp 的结果:

[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
Listen=80
#test
#test
#test
Listen=8080

可以看到,结果是在最后一行添加了 Listen=8080,恢复 /tmp/test,在演示下加了 regexp 的结果:

[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
Listen=8080
#test
#test
#test

可以看到这回是将已有的 Listen=80 修改为 Listen=8080

也就是说 regexp 和 insertafter 或 insertbefore组合使用时,能够保证文件最后只有一个 Listen 存在。

最后做两个测试:

第一个

[root@awx-1 ansible]# cat /tmp/test
#test
#test
Listen=80
#Listen=80
#test
#test
#test
[root@awx-1 ansible]# cat test.yml
---
- name: testhosts: localhosttasks:- name: Lineinfile testansible.builtin.lineinfile:line: "Listen=8080"#regexp: "^Listen="insertafter: "^#Listen="path: /tmp/test
[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
Listen=80
#Listen=80
Listen=8080
#test
#test
#test

第二个:

[root@awx-1 ansible]# cat /tmp/test
#test
#test
#test
#test
#test
[root@awx-1 ansible]# cat test.yml
---
- name: testhosts: localhosttasks:- name: Lineinfile testansible.builtin.lineinfile:line: "Listen=8080"regexp: "^Listen="insertbefore: "^#Listen="path: /tmp/test
[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
#test
#test
#test
Listen=8080

第二个例子里,我特意使用了 insertbefore 可以看到在没有任何匹配时,只会在文件的最后进行追加。

最后总结下,regexp 跟 insertafter 或 insertbefore 进行匹配时,情况如下:

  • regexp 优先匹配,会修改 regexp 匹配的行

  • regexp 没有匹配到时,按照 insertafter 或 insertbefore 的逻辑进行匹配和修改

  • 都没有匹配到时,在文件的最后一行追加

修改文件多行内容

ansible.builtin.blockinfile 用于修改文件的多行内容。

说是修改,多数时候还是添加新的多行内容,这里强调一点,ansible.builtin.blockinfile 通过标记来查找文件中已添加的多行内容。

参数名

类型

默认值

描述

append_newlineboolfalse

如果插入 block 后,新末行没有换行符,则自动加一行换行,保持标准文本格式

attributesstrnull

用于设置文件的高级属性(extended attributes),如 i(不可变)、a(只能追加)。相当于执行 chattr,仅在支持该功能的文件系统(如 ext4)中有效

backupboolfalse

在修改文件前创建备份。

blockstrnull

要插入的文本块内容(多行字符串)

createboolfalse

如果文件不存在则创建

groupstrnull

设置文件的所属组

insertafterstrEOF

插入内容到匹配行之后,或 EOF 表示文件结尾

insertbeforestrnull

插入内容到匹配行之前,或 BOF 表示文件开头

markerstr# {mark} ANSIBLE MANAGED BLOCK

控制 block 标记的格式,{mark} 会被替换为 BEGIN 或 END

marker_beginstrBEGIN

自定义起始标记,用于替代 {mark}

marker_endstrEND

自定义结束标记,用于替代 {mark}

modestrnull

设置文件权限(如 0644

ownerstrnull

设置文件所有者

pathstrnull

目标文件路径

prepend_newlineboolfalse

是否在 block 前添加换行,防止与上一行粘连

selevelstrnull

SELinux 安全级别

serolestrnull

SELinux 角色

setypestrnull

SELinux 类型

seuserstrnull

SELinux 用户

statestrpresent

是否确保 block 存在或被删除(present/absent

unsafe_writesboolfalse

绕过临时文件机制直接写入文件(有风险)

validatestrnull

应用更改前对文件进行语法验证(如 nginx -t -c %s

常用选项:

参数名

类型

默认值

描述

append_newlineboolfalse

如果插入 block 后,新末行没有换行符,则自动加一行换行,保持标准文本格式

backupboolfalse

在修改文件前创建备份。

blockstrnull

要插入的文本块内容(多行字符串)

createboolfalse

如果文件不存在则创建

groupstrnull

设置文件的所属组

insertafterstrEOF

插入内容到匹配行之后,或 EOF 表示文件结尾

insertbeforestrnull

插入内容到匹配行之前,或 BOF 表示文件开头

markerstr# {mark} ANSIBLE MANAGED BLOCK

控制 block 标记的格式,{mark} 会被替换为 BEGIN 或 END(注意标记里必须含有 {mark} 字段)

marker_beginstrBEGIN

自定义起始标记,用于替代 {mark}

marker_endstrEND

自定义结束标记,用于替代 {mark}

modestrnull

设置文件权限(如 0644

ownerstrnull

设置文件所有者

pathstrnull

目标文件路径

prepend_newlineboolfalse

是否在 block 前添加换行,防止与上一行粘连

statestrpresent

是否确保 block 存在或被删除(present/absent

validatestrnull

应用更改前对文件进行语法验证(如 nginx -t -c %s

- name: Insert/Update "Match User" configuration block in /etc/ssh/sshd_config prepending and appending a new lineansible.builtin.blockinfile:path: /etc/ssh/sshd_configappend_newline: trueprepend_newline: trueblock: |Match User ansible-agentPasswordAuthentication no- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces(it might be better to copy files into /etc/network/interfaces.d/)ansible.builtin.blockinfile:path: /etc/network/interfacesblock: |iface eth0 inet staticaddress 192.0.2.23netmask 255.255.255.0- name: Insert/Update configuration using a local file and validate itansible.builtin.blockinfile:block: "{{ lookup('ansible.builtin.file', './local/sshd_config') }}"path: /etc/ssh/sshd_configbackup: yesvalidate: /usr/sbin/sshd -T -f %s- name: Insert/Update HTML surrounded by custom markers after <body> lineansible.builtin.blockinfile:path: /var/www/html/index.htmlmarker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"insertafter: "<body>"block: |<h1>Welcome to {{ ansible_hostname }}</h1><p>Last updated on {{ ansible_date_time.iso8601 }}</p>- name: Remove HTML as well as surrounding markersansible.builtin.blockinfile:path: /var/www/html/index.htmlmarker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"block: ""- name: Add mappings to /etc/hostsansible.builtin.blockinfile:path: /etc/hostsblock: |{{ item.ip }} {{ item.name }}marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"loop:- { name: host1, ip: 10.10.1.10 }- { name: host2, ip: 10.10.1.11 }- { name: host3, ip: 10.10.1.12 }

这里举个例子来验证 ansible.builtin.blockinfile 是如何确认文本块的:

[root@awx-1 ansible]# cat /tmp/test
#test
#test
#block test
#test
#test
[root@awx-1 ansible]# cat test.yml
---
- name: testhosts: localhosttasks:- name: Lineinfile testansible.builtin.blockinfile:path: /tmp/testappend_newline: trueprepend_newline: trueblock: |address 192.168.1.1netmask 255.255.255.0gateway 192.168.1.254insertafter: "^#block"marker: "# {mark} block test"marker_begin: "one"marker_end: "two"#state: absent
[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
#block test# one block test
address 192.168.1.1netmask 255.255.255.0
gateway 192.168.1.254
# two block test#test
#test[root@awx-1 ansible]# cat test.yml
---
- name: testhosts: localhosttasks:- name: Lineinfile testansible.builtin.blockinfile:path: /tmp/testappend_newline: trueprepend_newline: trueblock: |address 192.168.1.1netmask 255.255.255.0gateway 192.168.1.254insertafter: "^#block"marker: "# {mark} block test"#marker_begin: "one"#marker_end: "two"#state: absent[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
#block test# BEGIN block test
address 192.168.1.1netmask 255.255.255.0
gateway 192.168.1.254
# END block test# one block test
address 192.168.1.1netmask 255.255.255.0
gateway 192.168.1.254
# two block test#test
#test

可以看到添加 block 的时候会在 block 的开头和结尾添加一个标记(标记一般是 # 开头,表示注释),通过 marker_begin 和 marker_end 修改标记的之后,会重新添加 block,由此可见 block 的管理依赖标记,所以在添加新的 block 的时候记得保证标记的唯一性。

还有个小问题,append_newline 可以在 block 的末尾添加一个换行符来和旧内容分隔,但是每次删除重新添加时都会多一个换行符:

[root@awx-1 ansible]# cat /tmp/test
#test
#test
#block test
#test
#test
[root@awx-1 ansible]# cat test.yml
---
- name: testhosts: localhosttasks:- name: Lineinfile testansible.builtin.blockinfile:path: /tmp/testappend_newline: trueprepend_newline: trueblock: |address 192.168.1.1netmask 255.255.255.0insertafter: "^#block"#state: absent
[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
#block test# BEGIN ANSIBLE MANAGED BLOCK
address 192.168.1.1netmask 255.255.255.0
# END ANSIBLE MANAGED BLOCK#test
#test
[root@awx-1 ansible]# cat test.yml
---
- name: testhosts: localhosttasks:- name: Lineinfile testansible.builtin.blockinfile:path: /tmp/testappend_newline: trueprepend_newline: trueblock: |address 192.168.1.1netmask 255.255.255.0insertafter: "^#block"state: absent
[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
#block test#test
#test
[root@awx-1 ansible]# ansible-playbook test.yml
...output omitted...[root@awx-1 ansible]# cat /tmp/test
#test
#test
#block test# BEGIN ANSIBLE MANAGED BLOCK
address 192.168.1.1netmask 255.255.255.0
# END ANSIBLE MANAGED BLOCK#test
#test

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/bicheng/81553.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何用PDO实现安全的数据库操作:避免SQL注入

如何用PDO实现安全的数据库操作&#xff1a;避免SQL注入 在现代Web应用程序中&#xff0c;数据库操作是核心功能之一。然而&#xff0c;SQL注入是一种常见的安全漏洞&#xff0c;攻击者可以通过恶意输入来操控数据库&#xff0c;从而获取敏感信息或破坏数据。使用PHP的PDO&…

使用大语言模型从零构建知识图谱(中)

从零到一&#xff1a;大语言模型在知识图谱构建中的实操指南 ©作者|Ninja Geek 来源|神州问学 还没有看过上篇的读者可以阅读《使用大语言模型从零构建知识图谱&#xff08;上&#xff09;》了解整个系列的内容 通过创建一个自定义流程来自动上传业务数据 在这一节&#…

pycharm连接github(详细步骤)

【前提&#xff1a;菜鸟学习的记录过程&#xff0c;如果有不足之处&#xff0c;还请各位大佬大神们指教&#xff08;感谢&#xff09;】 1.先安装git 没有安装git的小伙伴&#xff0c;看上一篇安装git的文章。 安装git&#xff0c;2.49.0版本-CSDN博客 打开cmd&#xff08;…

uniapp在APP上如何使用websocket--详解

UniApp 在 APP 端如何使用 WebSocket以及常见问题 一、WebSocket 基础概念 WebSocket 是一种在单个TCP连接上进行全双工通信的协议&#xff0c;适用于实时数据传输场景&#xff08;如聊天室、实时游戏、股票行情等&#xff09;。 与传统HTTP对比 特性WebSocketHTTP连接方式…

物联网赋能7×24H无人值守共享自习室系统设计与实践!

随着"全民学习"浪潮的兴起&#xff0c;共享自习室市场也欣欣向荣&#xff0c;今天就带大家了解下在物联网的加持下&#xff0c;无人共享自习室系统的设计与实际方法。 一、物联网系统整体架构 1.1 系统分层设计 层级技术组成核心功能用户端微信小程序/H5预约选座、…

【Linux】ELF与动静态库的“暗黑兵法”:程序是如何跑起来的?

目录 一、什么是库&#xff1f; 1. C标准库&#xff08;libc&#xff09; 2. C标准库&#xff08;libstdc&#xff09; 二、静态库 1. 静态库的生成 2. 静态库的使用 三、动态库 1. 动态库的生成 2. 动态库的使用 3. 库运行的搜索路径。 &#xff08;1&#xff09;原因…

渗透测试流程-中篇

#作者&#xff1a;允砸儿 #日期&#xff1a;乙巳青蛇年 四月廿一&#xff08;2025年5月18日&#xff09; 今天笔者带大家继续学习&#xff0c;网安的知识比较杂且知识面很广&#xff0c;这一部分会介绍很多需要使用的工具。会用各种工具是做网安的基础&#xff0c;ok咱们继续…

[创业之路-358]:从历史轮回到制度跃迁:中国共产党创业模式的超越性密码

人类文明的演进如同一条螺旋上升的阶梯&#xff0c;从原始社会的公有制到资本主义私有制的巅峰&#xff0c;再到社会主义对公有制的重构&#xff0c;每一次制度迭代都伴随着对前序文明的扬弃。中国共产党自诞生之日起&#xff0c;便以“为人类求解放”为使命&#xff0c;在革命…

NLP基础

目录 一、NLP 概述和应用 &#xff08;一&#xff09;NLP 的定义与演进历程 &#xff08;二&#xff09;NLP 的多元应用领域 二、文本预处理技术 &#xff08;一&#xff09;文本获取与编码转换 &#xff08;二&#xff09;文本清洗&#xff1a;去除杂质的精细打磨 &…

【数据结构与算法】ArrayList 与顺序表的实现

目录 一、List 接口 1.1 List 接口的简单介绍 1.1 常用方法 二、顺序表 2.1 线性表的介绍 2.2 顺序表的介绍 2.3 顺序表的实现 2.3.1 前置条件:自定义异常 2.3.2 顺序表的初始化 2.3.2 顺序表的实现 三、ArrayList 实现类 3.1 ArrayList 的两种使用方式 3.2 Array…

Linux518 YUM源仓库回顾(需查)ssh 服务配置回顾 特定任务配置回顾

计划配仓库YUM源 为什么我在/soft文件夹下 使用yum install --downloadonly --downloaddir /soft samba 为什么文件夹下看不到samba文件 exiting because “Download Only” specified 计划过 计划配SSH 参考 ok了 计划配置特定任务解决方案 code: 两端先配好网络 测试好s…

如何完美安装GPU版本的torch、torchvision----解决torch安装慢 无法安装 需要翻墙安装 安装的是GPU版本但无法使用的GPU的错误

声明&#xff1a; 本视频灵感来自b站 如何解决所述问题 如何安装对应版本的torch、torchvison 进入pytorch官网 进入历史版本 这里以cuda11.8 torch 2.1.0为例演示 根据文档找到要安装的torch、torchvison版本 但不是使用命令行直接安装 命令行直接安装可能面临着 安装慢…

【iOS(swift)笔记-9】WKWebView无法访问网络

对于iOS 在info中添加App Transport Security Settings&#xff0c;然后在App Transport Security Settings里添加Allow Arbitrary Loadstrue 对于macOS 除了上面的操作&#xff0c;还需在项目信息的App Sandbox里有个Network打钩选项

buck变换器的simulink/matlab仿真和python参数设计

什么是Buck电路? BUCK电路是一种降压斩波器&#xff0c;降压变换器输出电压平均值Uo总是小于输出电压UD。通常电感中的电流是否连续&#xff0c;取决于开关频率、滤波电感L和电容C的数值。BUCK也是DC-DC基本拓扑&#xff0c;或者称为电路结构&#xff0c;是最基本的DC-DC电路…

给个人程序加上MCP翅膀

背景 最近MCP这个词真是到处都是&#xff0c;看起来特别高大上。我平时没事的时候也一直在关注这方面的技术&#xff0c;知道它是怎么一回事&#xff0c;也懂该怎么去实现。但可惜一直抽不出时间来自己动手搞一个MCP服务。网上关于MCP的教程一搜一大把&#xff0c;但基本上都是…

AWS中国区CloudFront证书管理和应用指南

在AWS中国区使用CloudFront时,SSL/TLS证书的管理和应用是一个重要的环节。本文将详细介绍如何在AWS中国区上传、管理和应用SSL证书到CloudFront分配。 1. 准备证书文件 首先,我们需要准备好SSL证书相关的文件。通常,这包括: 私钥文件(.key)公钥证书文件(.crt)证书链文…

为什么hadoop不用Java的序列化?

Java的序列化是一个重量级序列化框架&#xff08;Serializable&#xff09;&#xff0c;一个对象被序列化后&#xff0c;会附带很多额外的信息&#xff08;各种校验信息&#xff0c;Header&#xff0c;继承体系等&#xff09;&#xff0c;不便于在网络中高效传输。所以&#xf…

Word压缩解决方案

Word压缩解决方案&#xff1a;基于图片压缩的 .docx 优化实践 &#x1f4cc; 背景 在日常科研写作或项目文档整理中&#xff0c;Word 文档&#xff08;.docx&#xff09;往往因为插入大量高清图表、扫描图像、公式图等导致文件体积过大&#xff0c;或者毕业学位论文查重要求上…

基于基金净值百分位的交易策略

策略来源&#xff1a;睿思量化小程序 基金净值百分位&#xff0c;是衡量当前基金净值在过去一段时间内的相对位置。以近一年为例&#xff0c;若某基金净值百分位为30%&#xff0c;意味着过去一年中有30%的时间基金净值低于当前值&#xff0c;70%的时间高于当前值。这一指标犹如…

数字人技术的核心:AI与动作捕捉的双引擎驱动(210)

**摘要&#xff1a;**数字人技术从静态建模迈向动态交互&#xff0c;AI与动作捕捉技术的深度融合推动其智能化发展。尽管面临表情僵硬、动作脱节、交互机械等技术瓶颈&#xff0c;但通过多模态融合技术、轻量化动捕方案等创新&#xff0c;数字人正逐步实现自然交互与情感表达。…