Ansible
如何使用 Ansible 模組替換或內聯 shell 命令與 SED
我有帶字元串的文件:
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
使用參數lineinfile
來path
標記要修改的文件。
lineinfile
模組用於確保
$$ s $$特定行在文件中,或$$ to $$使用反向引用的正則表達式替換現有行。
採用
如果要更改多個類似的行,請使用替換模組
我相信該
dest
參數用於創建新文件的模組,例如template
orcopy
。只需替換
dest
為path
,兩個提供的範例都應按預期工作。