所以我有一个使用Jinja2模板创建日志文件的ansible playbook。每次我运行playbook时,它都会从customers.yml中提取客户信息,并将完成的模板输出到一个stunnel.conf'文件。该模板工作正常,但我试图找到一种方法来追加以前的stunnel.conf'而不是使用模块模块覆盖它。我想在stunnel.conf'的开头添加文字。手动而不是覆盖它。你认为这可能吗?
Stunnel.conf
; GFAM - PBSTP
[customer-GFAM-34074]
cert = /etc/stunnel/stunnel.pem
accept = 34094
connect = 35094
; GUANFABANK - FXSIM
[customer-GUANFABANK-34051]
cert = /etc/stunnel/stunnel.pem
accept = 34095
connect = 35095
; ONEZERO2 - TRADESTREAM
[customer-ONEZERO2-39124]
cert = /etc/stunnel/stunnel.pem
accept = 34096
connect = 35096
; BTG-VELOCITY - PBSTP
[customer-BTG-VELOCITY-42533]
cert = /etc/stunnel/stunnel.pem
accept = 34097
connect = 35097
Jinja2模板
{#CONTEXT: {{ customers }}#}
{% set currentport = 34093%}
{% for cust, config in customers.items() %}
; {{ cust }} - {{ config['type'] }}
[customer-{{ cust }}-{{ config['accept'] }}]
cert = {{ "/etc/stunnel/stunnel.pem" }}
{#accept = {{ config['accept'] }}#}
{#connect = {{ config['connect'] }}#}
accept = {{ currentport + 1 }}
connect = {{ currentport + 1001 }}
{% set currentport = currentport + 1 %}
{% endfor %}
playbook.yml
- include_vars:
file: /home/vagrant/stunnelSimAnsPractice/roles/ns16/vars/customers.yml
name: customers
- template:
src: /home/vagrant/stunnelSimAnsPractice/roles/ns16/templates/stunnel.j2
dest: /home/vagrant/stunnelSimAnsPractice/roles/ns16/output/stunnel.conf
owner: root
group: root
答案 0 :(得分:7)
您可以使用blockinfile模块和template查找来管理stunnel.conf中的每个客户端块:
- include_vars:
file: customers.yml
name: customers
- blockinfile:
dest: stunnel.conf
block: "{{ lookup('template', 'stunnel.j2') }}"
marker: "; {mark} ANSIBLE MANAGED BLOCK FOR {{ cust }}"
为了便于阅读,我缩短了文件路径。
这样Ansible将为特定客户端({{ cust }}
变量)查找托管块,并添加/替换模板化stunnel.j2中的内容。
答案 1 :(得分:1)
我建议这样做:
在剧本中它可能看起来像:
- include_vars:
file: /home/vagrant/stunnelSimAnsPractice/roles/ns16/vars/customers.yml
name: customers
- template:
src: /home/vagrant/stunnelSimAnsPractice/roles/ns16/templates/stunnel.j2
dest: /home/vagrant/stunnelSimAnsPractice/roles/ns16/output/temp.conf
owner: root
group: root
- name: "Append stunnel.conf with content of temporary file"
shell: cat temp.conf >> stunnel.conf
args:
chdir: "/home/vagrant/stunnelSimAnsPractice/roles/ns16/output"
- name: "Delete temporary file"
file:
path: /home/vagrant/stunnelSimAnsPractice/roles/ns16/output/temp.conf
state: absent