I haven't blogged in a very long time, but felt this was something that should be shared. Sometimes tools deal with the same type of information inconsistently and that can cause you serious headaches and a lot of effort to resolve. In this particular case, Ansible requires AWS tags to be in list format for autoscaling groups (ASGs) and to be in dict format for elastic load balancers (ELBs) and security groups (SGs). If you try to use a list of tags for ELBs or SGs, you'll get the following error:
"argument tags is of type <type 'list'> and we were unable to convert to dict: <type 'list'> cannot be converted to a dict"
Of course, you'll get a similar but opposite error if you try to use tags in dict form for ASGs.
"argument tags is of type <type 'dict'> and we were unable to convert to list: <type 'dict'> cannot be converted to a list"
If you're like me, you want to define your config data once and manipulate it as needed. In our case we have a few hashes/lists of hashes of AWS tags that need to be combined to be useful with the various Ansible ec2 modules. You can see here https://gist.github.com/ITBlogger/a5b1ac1ab7ac2f12c4d7f6f77be359e7 that I've setup a gist of what I'm talking about You can go here https://gist.github.com/ITBlogger/a5b1ac1ab7ac2f12c4d7f6f77be359e7#file-aws_role_sample-L27 and see from line 27 to line 71 how we're manipulating the lists to combine them for one use and recreate them into dicts for the other usages.
- name: change native_tags list to dict
set_fact:
merged_tags: '{{ merged_tags | combine( item ) }}'
with_items: '{{ native_tags }}'
The above shows how we're using the jinja2 combine filter and with_items loop to go over the list of tags and add them to the merged_tags dict which is used later. https://gist.github.com/ITBlogger/a5b1ac1ab7ac2f12c4d7f6f77be359e7#file-aws_role_sample-L41
You can also see in the playbook vars that we've initialized merged_tags as an empty dict `merged_tags: {}` https://gist.github.com/ITBlogger/a5b1ac1ab7ac2f12c4d7f6f77be359e7#file-aws_playbook_sample-L16 Hope this makes sense given the gist examples
To create the list of tags from the multiple sources, we use the + operand: `merged_asg_tags: '{{ native_tags }} + {{ asg_native_tags }} + {{ asg_extra_tags }}'` https://gist.github.com/ITBlogger/a5b1ac1ab7ac2f12c4d7f6f77be359e7#file-aws_role_sample-L65
Also hope you understand that we're talking about AWS tags here and not Ansible tags, although the gist example does use Ansible tags as well.
Recent Comments