我有带字符串的文件:

MYAPP.db.username.DEV=MYUSERNAME

在哪里?

MYAPP mean name of applications
DEV means environment
MYUSERNAME means name of user for connection to db

我需要根据一些脚本中的变量替换这些变量。 我用这个:

- name: Replace line
  shell: sed -i "/{{ name_of_app }}.db.username.{{ name_of_environment }}/c\{{ name_of_app }}.db.username.{{ name_of_environment }}={{ name_of_user_to_db }}" /path/to/my/apps/{{ name_of_app }}/config/{{ name_of_app }}.config

它工作得很好,但是我在ansible的输出中看到了警告

 [WARNING]: Consider using the replace, lineinfile or template module rather
than running sed.  If you need to use command because replace, lineinfile or
template is insufficient you can add warn=False to this command task or set
command_warnings=False in ansible.cfg to get rid of this message.
changed:

我试过了

- name: Replace line via replace method
  replace: 
    dest: "/path/to/my/apps/{{ name_of_app }}/config/{{ name_of_app }}.config"
    regexp: "{{ name_of_app }}.db.username.{{ name_of_environment }}"
    replace: "{{ name_of_app }}.db.username.{{ name_of_environment }}={{ name_of_user_to_db }}"

还有这个

- name: Replace line via lineinfile method
  lineinfile: 
    dest: "/path/to/my/apps/{{ name_of_app }}/config/{{ name_of_app }}.config"
    regexp: "{{ name_of_app }}.db.username.{{ name_of_environment }}"
    line: "{{ name_of_app }}.db.username.{{ name_of_environment }}={{ name_of_user_to_db }}"
    backrefs: yes

每次,我都有失败的结果:

FAILED! => {"changed": false, "msg": "Unsupported parameters for (replace) module: when Supported parameters include: after, attributes, backup, before, content, delimiter, directory_mode, encoding, follow, force, group, mode, owner, path, regexp, remote_src, replace, selevel, serole, setype, seuser, src, unsafe_writes, validate"}

你能帮帮我吗,我的剧本哪里出错了?

最佳回复

您试图更改的文件是否始终具有相同的行

MYAPP.db.username.DEV=MYUSERNAME

如果是这样的话你可以试试下一个

- name: Replace line via replace method
replace:
  dest: "/path/to/my/apps/{{ name_of_app }}/config/{{ name_of_app }}.config"
  regexp: '^MYAPP\.db\.username\.DEV\=MYUSERNAME'
  replace: '{{ name_of_app }}.db.username.{{ name_of_environment }}={{ name_of_user_to_db }}'