我试图使用一个模板,生成包含信息的配置文件,如主机,端口,用户名,密码,…
我想使用一个模板并在模板任务中传递标签,因此模板将选择在相应标签中定义的变量,即:
- name: generate config
template:
src: /test/debezium_oracle_cdc_source.j2
dest: "/config/debz-oracle-test_1.json"
vars:
tags: "{{ oracle['tag1'] }}"
bootstrap_servers: "kafka:9092"
- name: generate config
template:
src: /test/debezium_oracle_cdc_source.j2
dest: "/config/debz-oracle-test_2.json"
vars:
tags: "{{ oracle['tag2'] }}"
bootstrap_servers: "kafka:9092"
变量文件
oracle:
tag1:
tables:
- DEPT
- EMPLOYEE
db_host: localhost
db_name: root
db_user: root
db_port: 1521
tag2:
tables:
- SALES
- SALES_ITEM
db_host: localhost
db_name: root
db_user: root
db_port: 1521
debezium_oracle_cdc_source.j2:
{
"database.hostname": "{{ db_host }}",
"database.port": "{{ db_port }}"
}
基本上,我想让我的变量文件更可读。
您的问题来自tags
是Ansible中的保留词,因为它是一个现有的关键字。
这可以通过一个简单的任务来复制和确认:
- debug:
msg: "{{ tags }}"
vars:
tags: I guess I am buggy?
出错:
fatal: [localhost]: FAILED! =>
msg: |-
The task includes an option with an undefined variable.
The error was: 'tags' is undefined. 'tags' is undefined
The error appears to be in '/usr/local/ansible/play.yml':
line 7, column 7, but may be elsewhere in the file
depending on the exact syntax problem.
The offending line appears to be:
tasks:
- debug:
^ here
这可以很容易地修复,例如,通过在变量前面加上下划线:
- debug:
msg: "{{ _tags }}"
vars:
_tags: I guess I am buggy?
这将产生预期的:
ok: [localhost] =>
msg: I guess I am buggy?
所以在模板debezium_oracle_cdc_source的情况下。包含:j2
{
"database.hostname": "{{ _tags.db_host }}",
"database.port": "{{ _tags.db_port }}"
}
和任务:
- template:
src: debezium_oracle_cdc_source.j2
dest: "/config/debz-oracle-test_{{ item }}.json"
loop: "{{ range(1, 3) }}"
vars:
_tags: "{{ oracle['tag' ~ item] }}"
oracle:
tag1:
db_host: host1.localhost
db_port: 1234
tag2:
db_host: host2.localhost
db_port: 5678
我们得到了两个预期的JSON:
- /config/debz-oracle-test_1.json:
{ "database.hostname": "host1.localhost", "database.port": "1234" }
- /config/debz-oracle-test_2.json:
{ "database.hostname": "host2.localhost", "database.port": "5678" }
在模板中使用字典标签
{
"database.hostname": "{{ tags.db_host }}",
"database.port": "{{ tags.db_port }}"
}