当jenkins重写其配置时,如何使这个ansible jenkins脚本具有幂等性?

gui*_*ido 2 idempotent jenkins ansible ansible-template

我有一个ansible playbook来部署jenkins,其中jenkins config.xmljinja2模板文件包含这个用于AD身份验证的代码段:

<securityRealm class="hudson.plugins.active_directory.ActiveDirectorySecurityRealm" plugin="active-directory@1.39">
    <domain>{{ ldap_hostname }}/domain>
    <bindName>{{ ldap_bind_user }}</bindName>
    <bindPassword>{{ ldap_password }}</bindPassword>
    <server>{{ ldap_hostname }}:{{ ldap_port }}</server>
    <groupLookupStrategy>RECURSIVE</groupLookupStrategy>
    <removeIrrelevantGroups>false</removeIrrelevantGroups>
</securityRealm>
Run Code Online (Sandbox Code Playgroud)

{{ ldap_password }} 是来自保险库的明文密码.

问题是当jenkins在部署config.xml之后启动时,它会通过用密码哈希替换明文密码来重写它.(哈希似乎依赖于目标主机,因为我们在不同的虚拟机上获得不同的哈希值).虽然这通常是一件好事,但它会使每个playbook的执行都将模板操作标记为已更改.

如何使这个播放脚本具有幂等性?

yda*_*coR 5

我真的想不出一个干净利落的方式,所以这可能会有点折磨.

你有几个选择取决于你想要的"正确".

首先,您可以简单地告诉Ansible您不关心是否对此文件进行任何更改,因此始终标记不变(绿色).您可以changed_when: False在任务上执行此操作.

或者你可以说你只想在第一次运行时模拟这个文件,之后它就是Ansible的手.这种方法对于引导那些想要管理自己文件的东西的安装非常有用,你永远不会考虑再次更改它们.为此你可以逃脱:

- name: check if jenkins config.xml file is there
  stat:
    path: path/to/config.xml
  register: config-xml_stat

- name: template jenkins config.xml if not already there
  template:
    src: path/to/config.xml.j2
    dest: path/to/config.xml
  when: config-xml_stat.exists == false
Run Code Online (Sandbox Code Playgroud)

思考这个问题,你正在模仿某些东西,然后积极地期望从Ansible的控制之外改变一条特定的线.这里的另一个选择是将文件模板放到一个不同的文件路径,而不是詹金斯所期望的(这可能是正常的幂等),与詹金斯正在使用的文件差异,然后如果除了那条线以外的任何东西是不同的复制Jenkins文件的顶部.你可以使用这样的东西来做到这一点:

- name: template jenkins config.xml.template
  template:
    src: path/to/config.xml.j2
    dest: path/to/config.xml.template

# We are expecting bindPassword to have changed so we can exclude this from the diff line count
- name: diff jenkins config.xml and config.xml.template
  shell: diff path/to/config.xml.template path/to/config.xml | grep -v bindPassword | wc -l
  register: config-xml_diff

# Diff will also output 2 extra lines that we don't care about. If there's more lines than this then we need to retemplate the config.xml
- name: template jenkins config.xml
  template:
    src: path/to/config.xml.j2
    dest: path/to/config.xml
  when: config-xml_diff.stdout != 2
Run Code Online (Sandbox Code Playgroud)

最后一个有点笨拙和笨拙,但是"更正确",因为它正在积极检查文件是否发生了超出我们预期的变化,如果重新模板化它.

如果您决定沿着第三条路线行驶,那么我建议将检查结合起来,看看它是否存在于第二个选项中,以使其在事情正在发生的事情中更加明显.没有它,如果config.xml文件不存在那么你的diff任务将输出一行(diff: config.xml: No such file or directory),这仍然意味着你的第三个任务的条件评估没问题,但它有点误导.