Ansible - 用jinja模板

时间:2017-06-18 15:01:59

标签: ansible jinja2

我想用ansible替换jenkins config.xml的特定标记。该文件看起来像:

<?xml version='1.0' encoding='UTF-8'?>
<hudson>
  <disabledAdministrativeMonitors/>
  <version>1.0</version>
  <numExecutors>2</numExecutors>
  <mode>NORMAL</mode>
  <useSecurity>true</useSecurity>
  <authorizationStrategy class="hudson.security.AuthorizationStrategy$Unsecured"/>
  <securityRealm class="hudson.security.SecurityRealm$None"/>
  <disableRememberMe>false</disableRememberMe>
  ...
</hudson>

替换内容是一个jinja模板,应该替换标记<securityRealm .../>,即使等效表单存在<securityRealm>...</<securityRealm>

编辑:有关我想要做的详细说明。

我有一个jinja模板,代表了一部分XML配置。让我们说这是模板:

<securityRealm class="hudson.security.SecurityRealm$Specific"/>
  <customTag1>{{ valueOne }}</customTag1>
  <customTag2>{{ valueTwo }}</customTag2>
</securityRealm>

所以最终结果如下:

<?xml version='1.0' encoding='UTF-8'?>
<hudson>
  <disabledAdministrativeMonitors/>
  <version>1.0</version>
  <numExecutors>2</numExecutors>
  <mode>NORMAL</mode>
  <useSecurity>true</useSecurity>
  <authorizationStrategy class="hudson.security.AuthorizationStrategy$Unsecured"/>
  <securityRealm class="hudson.security.SecurityRealm$Specific"/>
    <customTag1>anyConfig</customTag1>
    <customTag2>anotherValue</customTag2>
  </securityRealm>
  <disableRememberMe>false</disableRememberMe>
  ...
</hudson>

1 个答案:

答案 0 :(得分:-1)

需要分三步完成。首先,将模板复制到目标主机。然后将文件的内容复制到config.xml,替换目标行。这是一个示例:

---

- hosts: all
  tasks:

    - template:
        src: templatefile
        dest: /tmp/templatefile

    - shell: cat /tmp/templatefile
      register: data

    - replace:
        dest: /path/to/config.xml
        regexp: '<securityRealm class=.*/>'
        replace: "{{ data }}"

...