Ansible Generate an array of numbers
My intention is to generate a list containing numbers from 1 to 22 and for that I wrote below Ansible script.
- hosts: localhost
gather_facts: no
tasks:
- name: Generate sequance
set_fact:
mysequence: "{{ item | list }}"
with_sequence: start=1 end=22
- debug: var=mysequence
When I run the code I get this weird result
$ ansible-playbook test.yml
PLAY [localhost] **************************************************************************************************************************
TASK [Generate sequance] ******************************************************************************************************************
ok: [localhost] => (item=1)
ok: [localhost] => (item=2)
ok: [localhost] => (item=3)
ok: [localhost] => (item=4)
ok: [localhost] => (item=5)
ok: [localhost] => (item=6)
ok: [localhost] => (item=7)
ok: [localhost] => (item=8)
ok: [localhost] => (item=9)
ok: [localhost] => (item=10)
ok: [localhost] => (item=11)
ok: [localhost] => (item=12)
ok: [localhost] => (item=13)
ok: [localhost] => (item=14)
ok: [localhost] => (item=15)
ok: [localhost] => (item=16)
ok: [localhost] => (item=17)
ok: [localhost] => (item=18)
ok: [localhost] => (item=19)
ok: [localhost] => (item=20)
ok: [localhost] => (item=21)
ok: [localhost] => (item=22)
TASK [debug] ******************************************************************************************************************************
ok: [localhost] => {
"mysequence": [
"2",
"2"
]
}
PLAY RECAP ********************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
I am using latest version of Ansible. Any help is greatly appreciated!
I need this list for another task. Here is a snippet:
- name: Reboot 22 VMs
vmware_guest:
validate_certs: false
hostname: x.x.x.x
username: [email protected]
password: PASSS
datacenter: DC1
folder: "DC1/vm/Pod-{{item[1]}}"
name: "{{item[0]}}-Pod-{{item[1]}}"
state: restarted
delegate_to: localhost
with_nested:
- "{{myVarList}}"
- [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
Solution 1:
Nothing is weird in your results: you set mysequence
22 times, the values of the first 21 iterations are overwritten, the last value is a string 22
converted to a list with list
filter. In result you get two-element list with 2
and 2
.
What you wanted the task to look like is:
- name: Generate sequance
set_fact:
mysequence: "{{ mysequence | default([]) + [item | int] }}"
with_sequence: start=1 end=22
But what you really wanted is a way of generating a list of integers in a Jinja2 template:
- set_fact:
mysequence: "{{ range(1, 22 + 1) | list }}"