Ansible

如何使用 Ansible 模組替換或內聯 shell 命令與 SED

  • October 14, 2019

我有帶字元串的文件:

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"}

你能幫我嗎,我的劇本哪裡有錯誤?

replace使用參數lineinfilepath標記

要修改的文件。 lineinfile模組用於

確保

$$ s $$特定行在文件中,或$$ to $$使用反向引用的正則表達式替換現有行。

採用

如果要更改多個類似的行,請使用替換模組

我相信該dest參數用於創建新文件的模組,例如templateor copy

只需替換destpath,兩個提供的範例都應按預期工作。

引用自:https://serverfault.com/questions/987722