ansible 使用playbook对文件追加及替换文本的几种方式
使用背景:一台服务器中装有ansible工具,其他多台服务器中的程序配置文件为同一模板。通过编写playbook(ansible/roles/xx/task/main.yml)对其他多台服务器上的程序配置文件追加相同的配置文本,或替换文本。
- 对两个配置文件进行追加文本操作,以下为更新前后效果对比。
/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
- 对文件中的文本内容进行替换。
---
- 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