简体   繁体   中英

Ansible - Power of 2 loop on a variable

I need:

  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

A simple loop in c++ would be sth like:

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++;
}

One more thing, how can I store the results of each iteration in a register, so that I have it available, when the playbook runs serially the 2nd, 3rd or 4th time etc.

Update: Jinja2 allows the following: Raise the left operand to the power of the right operand.

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

Now keeping this new information in mind, can we do a power of 2 loop?

The type of loop you want is not going to be possible in Ansible. The tool is limited to looping over a list, dictionary, or a sequence but the counter cannot be modified. See the ansible docs on loops .

For something like this you may want to look into writing a custom module .

One more thing, how can I store the results of each iteration in a register, so that I have it available, when the playbook runs serially the 2nd, 3rd or 4th time etc.

See the section in the Ansible docs on how to use register in a loop . If you register a var named my_content you can access the individual results in my_content.results .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM