ansible 使用playbook对文件追加及替换文本的几种方式

ansible 使用playbook对文件追加及替换文本的几种方式

使用背景:一台服务器中装有ansible工具,其他多台服务器中的程序配置文件为同一模板。通过编写playbook(ansible/roles/xx/task/main.yml)对其他多台服务器上的程序配置文件追加相同的配置文本,或替换文本。

  1. 对两个配置文件进行追加文本操作,以下为更新前后效果对比。
/opt/config/application-dev.yml(更新之前)
#this is a test str

/opt/config/application-dev.yml(更新之后)
#this is a test str
redis:
  database: 8
  host: 127.0.0.1
  port: 6379
  password:
  
----------手动分割---------------

/opt/conf/cfg.properties(更新之前)
#this is a test str

/opt/conf/cfg.properties(更新之后)
#this is a test str
Redis.DB.State.Check.Index=8

第一种方式,使用lineinfile模块:

---
 - name: add redis config to application-dev.yml
   shell: sed -i '$a\redis:\n  database:\ 8\n  host:\ 127.0.0.1\n  port:\ 6379\n  password:' /opt/config/application.yml
   ignore_errors: True
 - name: add redis config to cfg.properties
   lineinfile:
     dest: /opt/conf/cfg.properties
     line: 'Redis.DB.State.Check.Index=8'
   ignore_errors: True

第二种方式,直接shell:

---
 - name: add redis config to application-dev.yml
   shell: sed -i '$a\redis:\n  database:\ 8\n  host:\ 127.0.0.1\n  port:\ 6379\n  password:' /opt/config/application-dev.yml
   ignore_errors: True
 - name: add redis config to cfg.properties
   shell: sed -i '$a\Redis.DB.State.Check.Index=8' /opt/conf/cfg.properties
   ignore_errors: True

第三种方式,按行执行shell:

---
 - name: add redis config to application-dev.yml
   shell: sed -i '$a\redis:' /opt/config/application-dev.yml
   ignore_errors: True
 - name: add redis config to application-dev.yml
   shell: sed -i '$a\  database: 8' /opt/config/application-dev.yml
   ignore_errors: True
 - name: add redis config to application-dev.yml
   shell: sed -i '$a\  host: 127.0.0.1' /opt/config/application-dev.yml
   ignore_errors: True
 - name: add redis config to application-dev.yml
   shell: sed -i '$a\  port: 6379' >> /opt/config/application-dev.yml
   ignore_errors: True
 - name: add redis config to application-dev.yml
   shell: sed -i '$a\  password:" >> /opt/config/application-dev.yml
   ignore_errors: True
 - name: add redis config to cfg.properties
   shell: sed -i '$a\Redis.DB.State.Check.Index=8' /opt/conf/cfg.properties
   ignore_errors: True
 - name: add redis config to scfg.properties
   shell: sed -i '$a\Redis.DB.State.Check.Index=8' /opt/conf/scfg.properties
   ignore_errors: True
  1. 对文件中的文本内容进行替换。
---
 - name: add new line at 3 line in fileName
   shell: sed -i '3i newStr' /path/path/fileName
   ignore_errors: True
 - name: change oldStr to newStr in fileName
   shell: sed -i 's/oldStr/newStr/g' /path/path/fileName
   ignore_errors: True
 - name: change 5 line to new line in fileName
   shell: sed -i '5c newStr' /path/path/fileName
   ignore_errors: True
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值