问题描述
我想知道我是否可以使用 Ansible 模板/副本并替换文件中的多个值(例如:.properties、.xml 等),同时使用参数存储中的值将文件部署到目的地?>
Ex-file: app.properties
app.timeout.value=APP-TIMEOUT-VALUE
app.zone.value=APP-ZONE-VALUE
Ex-playbook: app.yaml
- name: Deploy app properties
template:
src: path/app_name.properties
dest: /../app_name.properties
notify:
- restart app
在上面的示例中,我想将(APP-TIMEOUT-VALUE、APP-ZONE-VALUE 等)等值替换为存储在 Parameter Store 中的实际值,键为 (APP-TIMEOUT-VALUE,APP-ZONE -VALUE 等..
如果有没有额外脚本的直接方法,请有人建议我。
非常感谢
解决方法
给定文件
shell> cat app.properties
app.timeout.value=APP_TIMEOUT_VALUE
app.zone.value=APP_ZONE_VALUE
创建模板
shell> cat app.properties.j2
app.timeout.value={{ APP_TIMEOUT_VALUE }}
app.zone.value={{ APP_ZONE_VALUE }}
如果你不能手动创建模板,下面的块会为你做
- block:
- copy:
force: false
src: app.properties
dest: app.properties.j2
- lineinfile:
backrefs: true
path: app.properties.j2
regex: '^(.*)=\s*{{ item }}\s*$'
line: '\1={{ eval_open }}{{ item }}{{ eval_close }}'
loop:
- APP_TIMEOUT_VALUE
- APP_ZONE_VALUE
delegate_to: localhost
run_once: true
vars:
eval_open: "{{ '{{ ' }}"
eval_close: "{{ ' }}' }}"
根据需要自定义路径和循环
然后,使用模板。例如
- template:
src: app.properties.j2
dest: app_name.properties
vars:
APP_TIMEOUT_VALUE: 10
APP_ZONE_VALUE: 1
给予
shell> cat app_name.properties
app.timeout.value=10
app.zone.value=1
如果您不能重命名变量的名称,请将它们放入字典中。字典的键除了唯一之外没有任何限制。例如
shell> cat app.properties.j2
app.timeout.value={{ app_conf["APP-TIMEOUT-VALUE"] }}
app.zone.value={{ app_conf["APP-ZONE-VALUE"] }}
如果你不能手动创建模板,下面的块会为你做
- block:
- copy:
force: false
src: app.properties
dest: app.properties.j2
- lineinfile:
backrefs: true
path: app.properties.j2
regex: '^(.*)=\s*{{ item }}\s*$'
line: '\1={{ eval_open }}app_conf["{{ item }}"]{{ eval_close }}'
loop:
- APP-TIMEOUT-VALUE
- APP-ZONE-VALUE
delegate_to: localhost
run_once: true
vars:
eval_open: "{{ '{{ ' }}"
eval_close: "{{ ' }}' }}"
然后,下面的模板将给出相同的结果
- template:
src: app.properties.j2
dest: app_name.properties
vars:
app_conf:
APP-TIMEOUT-VALUE: 10
APP-ZONE-VALUE: 1