使用Ansible计算SSL证书到期日期差

42次阅读
没有评论

问题描述

在使用Ansible时,有一个需求是计算两个SSL证书到期日期之间的天数差。他已经编写了一个playbook,但是在使用set_fact任务时遇到了问题,无法得到正确的输出。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

根据用户提供的playbook,我们可以看到问题出在debug任务中的变量名上。diff这个变量名在Ansible中似乎是保留的,所以无法正确输出。解决方法是将变量名改为其他名称,比如diffa。以下是修改后的playbook示例:

- hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - name: Save the old date
      shell:
        cmd: >-
          date --date="$(openssl x509 -noout -dates -in cert1.crt
          | grep 'notAfter' | cut -d= -f2)" --utc +"%d-%m-%Y"
      ignore_errors: true
      args:
        executable: /bin/bash
      register: x1
    - name: Save the new date
      shell:
        cmd: >-
          date --date="$(openssl x509 -noout -dates -in cert2.crt
          | grep 'notAfter' | cut -d= -f2)" --utc +"%d-%m-%Y"
      ignore_errors: true
      args:
        executable: /bin/bash
      register: x2
    - name: Show mount of days with dedug module
      debug:
        var: "{{ (( x2.stdout | to_datetime('%d-%m-%Y')) - ( x1.stdout  | to_datetime('%d-%m-%Y'))).days }}"
    - set_fact:
        diffa: "{{ (( x2.stdout | to_datetime('%d-%m-%Y')) - ( x1.stdout | to_datetime('%d-%m-%Y'))).days }}"
    - name: Show mount of days with dedug module
      debug:
        var: diffa

在上面的示例中,我们将diff变量改为了diffa,并在debug任务中输出了diffa变量。这样就可以正确计算并输出两个SSL证书到期日期之间的天数差了。

方案2

使用Ansible的openssl_certificate_info模块可以更方便地获取SSL证书的信息,包括到期日期。
另一种更简单的方法是使用Ansible的openssl_certificate_info模块来获取SSL证书的信息,包括到期日期。以下是使用该模块的示例:

- hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - name: Get certificate info
      openssl_certificate_info:
        path: cert1.crt
      register: cert1_info
    - name: Get certificate info
      openssl_certificate_info:
        path: cert2.crt
      register: cert2_info
    - name: Show mount of days with dedug module
      debug:
        var: "{{ (( cert2_info.not_after | to_datetime('%Y-%m-%dT%H:%M:%S%z')) - ( cert1_info.not_after | to_datetime('%Y-%m-%dT%H:%M:%S%z'))).days }}"
    - set_fact:
        diffa: "{{ (( cert2_info.not_after | to_datetime('%Y-%m-%dT%H:%M:%S%z')) - ( cert1_info.not_after | to_datetime('%Y-%m-%dT%H:%M:%S%z'))).days }}"
    - name: Show mount of days with dedug module
      debug:
        var: diffa

在上面的示例中,我们使用openssl_certificate_info模块获取了两个SSL证书的信息,并将结果保存在cert1_infocert2_info变量中。然后,我们使用debug任务和set_fact任务计算并输出了两个SSL证书到期日期之间的天数差。这种方法更简洁,并且可以直接获取到期日期,无需手动解析和计算。

总结

通过修改变量名或使用Ansible的openssl_certificate_info模块,我们可以解决计算SSL证书到期日期差的问题。以上是两种解决方案的示例,你可以根据自己的需求选择适合的方法。

正文完