Ansible 中的幂等性和随机变量 [英] Idempotence and Random Variables in Ansible

查看:55
本文介绍了Ansible 中的幂等性和随机变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法保证使用随机生成变量的剧本的幂等性?

Is there a way to guarantee idempotence for playbooks that use randomly generated variables?

例如,我想设置我的 crontabs 以在不同时间触发多台服务器上的电子邮件,所以我使用 ansible 的 set_fact 模块创建随机整数:

For example, I want to setup my crontabs to trigger emails on multiple servers at different times, so I create random integers using ansible's set_fact module:

  tasks:
  - set_fact:
      first_run_30="{{ 30 | random }}"
    run_once: yes

然后使用 ansible 将这些生成的变量应用到我的 crontab 中,如下所示:

Then apply those generated variables to my crontab using ansible like so:

   - name: Setup cron30job
    cron: name=cron30job minute={{first_run_30}},{{first_run_30 | int + 30}} job='/bin/bash /cron30job.sh' state=present user=root
    environment:
      MAILTO: 'me@somelist.com'
      MAILFROM: 'me@somehost.com'

这很有效,但是,我相信使用这种策略会破坏 ansible 的幂等原则,因为每次播放时您都会看到变化:

This works very well, however, ansible's indempotence principle is, I believe, broken using this strategy because each time a play is made you see a change:

TASK: [Setup cron30job] ***************************************** 
changed: [127.0.0.1]

此外,在三个独立运行期间,每次都在 root 下检查 crontab:

Further, in the crontab checking under root each time during three separate runs:

[ansible]# cat /var/spool/cron/root 
#Ansible: cron30job
5,35 * * * * /bin/bash /sw/test/cron30job.sh
#Ansible: cron30job
9,39 * * * * /bin/bash /sw/test/cron30job.sh
#Ansible: cron30job
6,36 * * * * /bin/bash /sw/test/cron30job.sh

如果有解决方法,或者在我的方案中可能无法实现无幂等,我想知道.

If there is a workaround, or maybe indempotence just will not be possible in my scenario, I would like to know.

推荐答案

您可以获得与节点相关的信息,例如主机名的哈希值或 IP 地址的最后一个字节,而不是随机值.

Instead of a random value, you could get something related to the node, like an hash of the hostname or the last byte of the ip address.

这是一个例子:

- name: Get a pseudo-random minute 
  shell: expr $((16#`echo "{{inventory_hostname}}" | md5sum | cut -c 1-4`)) % 30
  register: minute
  changed_when: false

这篇关于Ansible 中的幂等性和随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆