使用Ansible中的模板模块附加文件 [英] Appending files with Template Module in Ansible

查看:64
本文介绍了使用Ansible中的模板模块附加文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一本使用Jinja2模板创建日志文件的Ansible剧本.每次运行剧本时,它都会从customer.yml中提取客户信息,并将完整的模板输出到"stunnel.conf"文件中.该模板可以正常工作,但是我试图找到一种方法来附加先前的"stunnel.conf",而不是使用模板"模块覆盖它.我希望手动将文本添加到"stunnel.conf"的开头,而不要覆盖它.您认为这可能吗?

So I have an ansible playbook that is using a Jinja2 template to create a log file. Everytime I run the playbook it is pulling in customer information from customers.yml and outputting the completed template into a 'stunnel.conf' file. The template works fine but I am trying to find a way to append the previous 'stunnel.conf' rather than overwriting it using the Template module. I wish to add text to the beginning of the 'stunnel.conf' manually and not have it overwritten. Do you think this would be possible?

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

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

推荐答案

您可以使用 blockinfile 模块和模板查找来管理每个客户端在您的stunnel.conf中阻止:

You can use blockinfile module and template lookup to manage per-client blocks in your 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中的内容添加/替换.

This way Ansible will look for managed block for specific client ({{ cust }} variable) and add/replace with content from templated stunnel.j2.

这篇关于使用Ansible中的模板模块附加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆