Home > Enterprise >  Ansible loop with hash values as one of conditions
Ansible loop with hash values as one of conditions

Time:12-04

I have two playbooks - outer.yml and inner.yml and below is the code which is not working.

outer.yml:


     - name: outer
         hosts: localhost
    
       vars:
         volume_names: ["abcd", "efgh"]
    
       tasks:
    
       - name: create hash values and call inner.yml
         set_fact:
           hash: "{{ 60000 | random(seed=item_name) }}"
         include_tasks: inner.yml
         loop: "{{ volume_names }}"
         loop_control:
           loop_var: item_name

inner.yml:

       - name: inner
         collection.snapshot:
           gateway_host: "{{IP}}"
           username: admin
           password: pass
           snapshot_name: "{{ hash }}"
           vol_name: "{{ item_name }}"

What I need is to create volume snapshots but each with unique snapshot name (that is why I used hashes) and do that for all volumes in the variable "volume_names".

Code above is not working, but I'm not sure why. Any idea?

Thanks!

CodePudding user response:

There is no need for the include, set_fact, and loop_control. For example,

 - hosts: localhost
   
   vars:
     volume_names: ["abcd", "efgh"]

   tasks:

     - debug:
         msg: |
           gateway_host: ip
           username: admin
           password: pass
           snapshot_name: "{{ 60000|random(seed=item) }}"
           vol_name: "{{ item }}"
       loop: "{{ volume_names }}"

gives

PLAY [localhost] ******************************************************************************

TASK [debug] **********************************************************************************
ok: [localhost] => (item=abcd) => 
  msg: |-
    gateway_host: ip
    username: admin
    password: pass
    snapshot_name: "20203"
    vol_name: "abcd"
ok: [localhost] => (item=efgh) => 
  msg: |-
    gateway_host: ip
    username: admin
    password: pass
    snapshot_name: "39290"
    vol_name: "efgh"

PLAY RECAP ************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Try

     - collection.snapshot:
         gateway_host: "{{ IP }}"
         username: admin
         password: pass
         snapshot_name: "{{ 60000|random(seed=item) }}"
         vol_name: "{{ item }}"
       loop: "{{ volume_names }}"
  • Related