0

I have an ansible var :

site1:
- name: myName  
  value1: something1  
  value2: apple  
  value3: 14  
  ...  
  valuen: "a submarine"  

So the point is, that I don't know how many values are there.

My desired output is :

myName something1 apple 14 a submarine.

(The key with its values)

In code:

{% for item in site1 %} {% for value in item.name %} {{value}} {% endfor %} {% endfor %}

Obviously this doesn’t work, but is there a correct way of doing this?

3
  • Hello, welcome to StackExchange network. Please take a moment to read the editing help section and format your question properly : unix.stackexchange.com/editing-help
    – shivams
    Commented May 18, 2015 at 14:00
  • @shivams I fixed your edit, the dash and spacing are significant in Ansible (it's YAML). Commented May 19, 2015 at 7:41
  • @StephenKitt : Okay, thanks. I am haven't worked in ansible and thought the OP had used the dash for unnumbered list.
    – shivams
    Commented May 19, 2015 at 8:57

1 Answer 1

0

Iterate over dict keys and filter out unneeded ones.

---
- hosts: all
  gather_facts: no
  vars:
    site1:
    - name: myName
      value1: something1
      value2: apple
      value3: 14
      valuen: "a submarine"
  tasks:
  - debug:
      msg: |
        {%- for item in site1 %}
        {{item['name']}}
        {%-   for key in item.keys() | sort %}
        {%-     if key.startswith('value') %}
         {{item[key]}}
        {%-     endif %}
        {%-   endfor %}
        {%- endfor %}.

Result:

$ ansible-playbook -i localhost, playbook.yml 

PLAY [all] ******************************************************************** 

TASK: [debug ] **************************************************************** 
ok: [localhost] => {
    "msg": "myName something1 apple 14 a submarine."
}

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .