Ansible querying AWS AMIs

家住魔仙堡 提交于 2019-12-24 07:08:03

问题


I'm trying to query AWS EC2 AMIs from Ansible but keep running into an error when looping through the results:

- hosts: localhost

  tasks:
   - name: Get AMI
     ec2_ami_facts:
        owner: amazon
        filters:
           architecture: x86_64
           root-device-type: ebs
     register: amis

   - name: return filtered data
     debug:
        msg: "{{ item }}"
     loop: " {{ amis \
        | json_query( 'Images[?Description!=`null`] \
        | [?starts_with(Description,`Amazon Linux`)]' ) \
        }} "

The idea is to return the image documents, and later just the image IDs with more filtering (end goal is to get the most recent ami id for a given description). But with the current example, and anything else I try I get this error:

TASK [return filtered data] ****************************************************
fatal: [localhost]: FAILED! => {"msg": "Invalid data passed to 'loop',
 it requires a list, got this instead:   . Hint: If you passed a
 list/dict of just one element, try adding wantlist=True to your lookup
 invocation or use q/query instead of lookup."}

I can look at the 'amis' in its entirety and it looks good, but any filtering I try fails. What is the correct method?


回答1:


This works, thanks for the folks at #ansible on freenode.

- hosts: localhost

  tasks:
   - name: Get AMI
     ec2_ami_facts:
        owner: amazon
        filters:
           architecture: x86_64
           root-device-type: ebs
     register: amis

   - name: return latest AMI
     set_fact:
        my_ami: "{{ amis.images \
            | selectattr('description', 'defined') \
            | selectattr('description', 'match', '^Amazon Linux.*GP2$') \
            | selectattr('description', 'match', '[^(Candidate)]') \
            | sort(attribute='creation_date') \
            | last }} "

   - debug:
        msg: "ami = {{ my_ami | to_nice_yaml }}"

Also see here: https://bitbucket.org/its-application-delivery/ansible-aws/src/master/ansible/task_find_ami.yml?fileviewer=file-view-default



来源:https://stackoverflow.com/questions/50218486/ansible-querying-aws-amis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!