【问题标题】:Ansible - Power of 2 loop on a variableAnsible - 变量上的 2 次幂循环
【发布时间】:2014-08-21 05:23:01
【问题描述】:

我需要:

  vars_prompt:
    - name: loopvar
      prompt: Enter the loop variable
      private: False
      default: 16
- hosts: epcs
  serial:1


  gather_facts: no
  tasks:

    - name: Do some mathematics divide multiply
      #insert logic here
      register: my_content  # save logic in register
      with_sequence: count={{loopvar}}  #I need a loop sequence here
      when: inventory_hostname == "vm1"
      ignore_errors: yes

c++ 中的一个简单循环应该是这样的:

int x=0;
for (int i=1; i<loopvar; i+=pow(2,x)) //pow is a math function with pow(2,x)= 2^x                                                                
{
    cout<<hi;
    x++;
}

还有一件事,我如何将每次迭代的结果存储在寄存器中,以便在 playbook 第二次、第三次或第四次连续运行时可用。

更新: Jinja2 允许: 将左操作数提升到右操作数的幂。

 {{ 2**3 }} would return 8.

现在牢记这些新信息,我们可以做 2 次幂循环吗?

【问题讨论】:

    标签: loops variables math prompt ansible-playbook


    【解决方案1】:

    你想要的循环类型在 Ansible 中是不可能的。该工具仅限于循环遍历列表、字典或序列,但无法修改计数器。请参阅ansible docs on loops

    对于这样的事情,你可能想考虑写一个custom module

    还有一件事,我如何将每次迭代的结果存储在寄存器中,以便在 playbook 连续运行第二次、第三次或第四次等时可用。

    请参阅 Ansible 文档 on how to use register in a loop 中的部分。 如果您注册了一个名为 my_content 的 var,您可以访问 my_content.results 中的各个结果。

    【讨论】:

    • 好的,感谢您的意见。我该怎么做 my_content.results[1] 等?
    • 应该可以正常工作,如果有帮助,ansible 调试模块有助于转储 var 的值。 - debug var={{ my_content.results[1] }} 将显示循环中注册的第二个结果,
    • 将左操作数提高到右操作数的幂。 {{ 2**3 }} 将返回 8。像我刚刚做的那样 jinja 数学呢
    • 你可以这样做,但我不认为你想要完成什么,修改计数器的顺序是不可能的。任何比文档中描述的 for 循环更复杂的东西都会变得丑陋,你将努力让 ansible 让它工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    相关资源
    最近更新 更多