Skip to content

Instantly share code, notes, and snippets.

@halberom
Created March 26, 2015 09:54
Show Gist options
  • Save halberom/090c19ad01d40b22c5ad to your computer and use it in GitHub Desktop.
Save halberom/090c19ad01d40b22c5ad to your computer and use it in GitHub Desktop.
ansible - example of creating an array from sequence for later use
PLAY [*foo] *******************************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [register redis instances] **********************************************
ok: [localhost] => (item=6379) => {
"item": "6379",
"msg": "do something"
}
ok: [localhost] => (item=6380) => {
"item": "6380",
"msg": "do something"
...
TASK: [set_fact ] *************************************************************
ok: [localhost]
TASK: [debug var=mysequence] **************************************************
ok: [localhost] => {
"mysequence": [
"6379",
"6380",
"6381",
"6382",
"6383",
"6384",
"6385",
"6386",
"6387",
"6388"
]
}
...
- hosts: "*foo"
vars:
redis_instances: 10
tasks:
- name: register redis instances
debug: msg="do something"
with_sequence: start=6379 end={{ 6379 + (redis_instances - 1) }}
register: monit_redis_services
- set_fact:
mysequence: "{{ monit_redis_services.results | map(attribute='item') | list }}"
- debug: var=mysequence
@Ritesh-Sharma
Copy link

Ritesh-Sharma commented Jan 10, 2017

Hey Halberom,

Thanks for sharing this , BTW could you please share the way to process the each element of array and then printing them in a loop ;

I have created an array "path" ,

  • set_fact: path="{{ result.files|map(attribute='path')|list}}"

now i am trying to apply "dirname" filter on each element of array but its getting applied only to last element .

  • set_fact: myvar="{{ item | dirname}}"
    with_items: "{{ path }}"

  • debug: var=myvar

Kind Regards,

@arkaraung1993
Copy link

Hi Ritesh-Sharma,

I am also facing this issue too.

@beenje
Copy link

beenje commented Mar 14, 2018

You can chain several filters:

set_fact:
  myvar: "{{ result.files | map(attribute='path') | map('dirname') | list }}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment