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?

  • 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 May 18 '15 at 14:00
  • @shivams I fixed your edit, the dash and spacing are significant in Ansible (it's YAML). – Stephen Kitt May 19 '15 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 May 19 '15 at 8:57
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   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.