ansible下使用blockinfile添加配置信息到xml

#发文福利#

一、前言

1、目标:批量修改服务器上的xml配置文件
2、原配置文件的最后一部分内容如下
复制代码
[root@s40 tmp]# tail kahn.conf
  <value>nginx</value>
  <description>my nginx config!</description>
</property>

<property>
  <name>address</name>
  <value>shanghai.china</value>
</property>

</configuration>
3、要求:在倒数第二行的位置插入新的配置信息
复制代码
            <property1>
              <name1>kahn.config</name>
              <value1>hahahaha.hello world!</value>
            </property1>

二、ansible-playbook的写法

复制代码
---

- hosts: all
  gather_facts: no
  ignore_unreachable: yes
  tasks:
    - name: debug 1
      debug:
        msg: "hello , newgroup"

    - name: 往xml里插入一段配置信息
      blockinfile:
          path: /opt/tmp/hdfs-site.xml
          insertbefore: "</configuration>"
          block: |
            <property1>
              <name1>kahn.config</name>
              <value1>hahahaha.hello world!</value>
            </property1>
          marker: "#{mark} my marker kahn..."
		  state: present
      notify:
        - handler1

  handlers:
    - name: handler1
      command: /bin/bash -c "/usr/bin/sed -ie 's/<\/configuration>/\n<\/configuration>/g' /opt/tmp/kahn.conf"

说明:

1、insertbefore: "</configuration>" 指定在 </configuration>一行的前面插入新配置信息

2、marker: "#{mark} my marker kahn..." 指定自定义标记,注意#是linux下的注释,{mark}是固定写法,必须写。到时候再你的配置信息上下放会有标记开始和结束的信息,如#BEGIN my marker kahn...和#END my marker kahn...。为啥要加{mark},有这个标记,才能以后使用state: absent去删除块。

3、state: present 增加块。反之是state: absent,如果要删除块state: absent的前提是在增加的时候必须有marker: "#{mark}"是必不可少的。

4、notify: - handler1 是本次的拓展,自定义动作标签,当我们修改了配置文件后,就会触发将最后一行的</configuration>替换掉为</configuration>上面增加一个空行。(注意这是个迂回的方法,没能在ansible中找到给指定行增加空白行的方法。如果我们反反复复的这样弄的话,会在最后一行</configuration>前产生多条空行)

执行结果如下:

复制代码
[root@s40 tmp]# tail kahn.conf
  <value>nginx</value>
  <description>my nginx config!</description>
</property>

<property>
  <name>address</name>
  <value>shanghai.china</value>
</property>

<property1>
  <name1>kahn.config</name>
  <value1>hahahaha.hello world!</value>
</property1>

</configuration>
相关推荐
比老马还六15 分钟前
Bipes项目二次开发/硬件编程-设备连接(七)
前端·javascript
掘金一周19 分钟前
前端一行代码生成数千页PDF,dompdf.js新增分页功能| 掘金一周 12.25
前端·javascript·后端
张就是我10659225 分钟前
漏洞复现指南:利用 phpinfo() 绕过 HttpOnly Cookie 保护
前端
Kagol30 分钟前
🎉TinyVue v3.27.0 正式发布:增加 Space 新组件,ColorPicker 组件支持线性渐变
前端·vue.js·typescript
潍坊老登30 分钟前
大前端框架汇总/产品交互参考UE
前端
方安乐37 分钟前
获取URL参数如何避免XSS攻击
前端·xss
十二AI编程1 小时前
MiniMax M2.1 实测,多语言编程能力表现出色!
前端
鹿野素材屋1 小时前
技术闲聊:为什么网游会在固定时间点,刷出固定的道具?
前端·网络·unity
同学807961 小时前
🔥🔥高效易用的 Vue3 公告滚动组件:打造丝滑的内容滚动体验(附源码)
前端·vue.js