如何在Ansible中使信息检索具有幂等性?

时间:2016-11-08 15:50:53

标签: ansible-playbook idempotent

我试图在服务器上获取有关证书的信息,以便在证书即将到期时我可以采取行动。我采取的步骤是:

# Does the certificate already exist?
- name: certbot | does cert already exist
  stat:
    path: "/etc/letsencrypt/live/{{certbot_domain}}//cert.pem"
  register: certbot_certificate

# Get the expiration date for the certificate in ISO format.
- name: certbot | get cert expiration date
  shell: "date --date=\"$(openssl x509 -in /etc/letsencrypt/live/{{certbot_domain}}/cert.pem -noout -enddate | cut -d= -f 2)\" --iso-8601"
  register: certbot_expiration_date
  when: certbot_certificate.stat.exists == True

# Convert the expiration date into the number of seconds from today.
- name: certbot | calculating expiration in seconds
  shell: "echo $(($(date --date={{certbot_expiration_date.stdout}} +%s) - $(date +%s)))"
  register: certbot_expires_in
  when: certbot_certificate.stat.exists == True

我的问题是两个shell命令总是被标记为"更改"在Ansible,这意味着这本剧本不能是幂等的。

我明白为什么会这样,因为Ansible无法真正理解shell命令的作用,所以通过说" Changed"来保证安全,但我想知道是否有一种实现相同结果的幂等方式吗?

没有写一个扩展,那就是......:)

感谢。

1 个答案:

答案 0 :(得分:0)

事实证明,答案是在任务中添加changed_when语句,例如:

- name: certbot | get cert expiration date
  shell: "date --date=\"$(openssl x509 -in /etc/letsencrypt/live/{{certbot_domain}}/cert.pem -noout -enddate | cut -d= -f 2)\" --iso-8601"
  register: certbot_expiration_date
  changed_when: False
  when: certbot_certificate.stat.exists == True

由于我知道shell命令没有改变任何东西,我可以安全地将changed_when设置为false,这可以确保最终的Tally显示Changed = 0,从而使playbook成为幂等的。

相关问题