{'msg': 'AnsibleUndefinedVariable: One or more undefined variables: list object has no element 1', 'failed': True}

2,356 views
Skip to first unread message

Chanaka Samarajeewa

unread,
Apr 22, 2015, 12:48:16 PM4/22/15
to ansible...@googlegroups.com
Hello,

For some reason, when my group_vars list only has 1 item under "test2:" it get the following error. If I have more than 1 list item under "test2:" then everything works correctly. Is this an Ansible bug or do I need to do something differently?

 {'msg': 'AnsibleUndefinedVariable: One or more undefined variables: list object has no element 1', 'failed': True}

group vars:
-----------------
---
VPCRegions:
  test1:
    - vpc1
    - vpc2
  test2:
    - vpc1

template:
--------------
{
"Resources" : {
{% set list_length = item.values()|length %}
{% for index in range(list_length) %}
"TomcatManager{{ item.value[index]|replace("-", "") }}" : {
  "Type" : "AWS::EC2::SecurityGroup",
  "Properties" : {
 "GroupDescription" : "8080",
 "VpcId" : "{{ item.value[index] }}",
 "SecurityGroupIngress" : [
{
"IpProtocol" : "tcp",
"FromPort" : "8080",
"ToPort" : "8080",
"CidrIp" : "0.0.0.0/0"
}
],
 "SecurityGroupEgress" : [   
  {
 "IpProtocol" : "tcp",
 "FromPort" : "8080",
 "ToPort" : "8080",
 "CidrIp" : "0.0.0.0/0"
  }   
  ]
  }
},
{% endfor %}
{% set list_length = item.values()|length %}
{% for index in range(list_length) %}
"SSH{{ item.value[index]|replace("-", "") }}" : {
  "Type" : "AWS::EC2::SecurityGroup",
  "Properties" : {
 "GroupDescription" : "22",
 "VpcId" : "{{ item.value[index] }}",
 "SecurityGroupIngress" : [
   {% for ip in ips %}
{
"IpProtocol" : "tcp",
"FromPort" : "22",
"ToPort" : "22",
"CidrIp" : "{{ ip }}/32"
}
{% if not loop.last %}
,
{% endif %}

{% endfor %}
]
}
}
{% if not loop.last %}
,
{% endif %}
{% endfor %}

}


main.yml task
---------------------
---

# Generate Cloudformation securitygroup templates for each region
- name: create cloudformation json templates for each region
  tags:
    - cloudformation-templates
  local_action:
    module: template src=tomcat-ssh-securitygroups.j2 dest=/tmp/tomcat-ssh-securitygroups-{{ item.key }}.json
  with_dict: VPCRegions


# run each template for each region in AWS
- name: create webservers & ssh security groups in based on template for all vpcs in region list
  with_dict: VPCRegions
  cloudformation:
    stack_name: "chanaka-cloudformation"
    state: "present"
    region: "{{ item.key }}"
    disable_rollback: true
    template: "/tmp/tomcat-ssh-securitygroups-{{ item.key }}.json"

Brian Coca

unread,
Apr 22, 2015, 3:40:58 PM4/22/15
to ansible...@googlegroups.com
So lists have 0 based indices, if you try to access item '1' when the
list only has 1 item (really item '0') you will get this error.

I think this expression is the culprit:

{% set list_length = item.values()|length %}

as with_dict should return item.key and item.value, not sure what
item.values() is doing.

--
Brian Coca
Reply all
Reply to author
Forward
0 new messages