在Ansible中用模板模块追加文件
问题描述:
所以我有一个使用Jinja2模板创建日志文件的可靠剧本。每次我运行剧本时,它都会从customers.yml中提取客户信息,并将完成的模板输出到“stunnel.conf”文件中。该模板工作正常,但我试图找到一种方法来追加以前的'stunnel.conf',而不是使用模板模块覆盖它。我希望手动添加文本到'stunnel.conf'的开头,而不是覆盖它。你认为这可能吗?在Ansible中用模板模块追加文件
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
答
我想建议做这样的:
- 将模板的输出保存到临时文件。
- 附加Stunnel.conf文件与临时文件的内容。
- 删除临时文件。
在剧本它可能看起来像:
- 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
答
您可以使用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中的内容。