2017-09-22 638 views
0

所以我有一個使用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 

回答

1

我想建議做這樣的:

  1. 將模板的輸出保存到臨時文件。
  2. 附加Stunnel.conf文件與臨時文件的內容。
  3. 刪除臨時文件。

在劇本它可能看起來像:

- 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 
2

您可以使用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中的內容。