首页 > 解决方案 > Ansible 查询 AWS AMI

问题描述

我正在尝试从 Ansible 查询 AWS EC2 AMI,但在遍历结果时不断遇到错误:

- 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`)]' ) \
        }} "

这个想法是返回图像文档,然后只返回经过更多过滤的图像 ID(最终目标是获取给定描述的最新 ami id)。但是对于当前的示例,以及我尝试的其他任何方法,我都会收到此错误:

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."}

我可以完整地查看“amis”,它看起来不错,但是我尝试的任何过滤都失败了。什么是正确的方法?

标签: amazon-web-servicesamazon-ec2ansible

解决方案


这很有效,感谢 freenode 上#ansible 的人们。

- 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 }}"

另请参见此处:https ://bitbucket.org/its-application-delivery/ansible-aws/src/master/ansible/task_find_ami.yml?fileviewer=file-view-default


推荐阅读