Ansible查询AWS AMI

时间:2018-05-07 16:16:35

标签: amazon-web-services amazon-ec2 ansible

我试图从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'整体看起来不错,但我试过的任何过滤都失败了。什么是正确的方法?

2 个答案:

答案 0 :(得分:1)

这很有效,感谢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

答案 1 :(得分:0)

使用以下命令动态获取最新的AMI。

---
- name: Find latest AMI  
  ec2_ami_facts:
    owners: 099720109477
    region: "{{ AWS_REGION }}"
    filters:
      name: "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*"
  register: findami  
- name: Sort the latest AMI 
  set_fact:
    latest_ami: >
      {{ findami.images | sort(attribute='creation_date') | last }} 
      
- name: Launch Instance with latest AMI
  ec2:
    instance_type: "{{ INSTANCE_TYPE }}"
    image: "{{ latest_ami.image_id }}"
    key_name: "{{ KEY_NAME }}"
    region: "{{ AWS_REGION }}"    
    group_id: "{{ sg.group_id }}"
    wait: yes
    count: "{{ INSTANCES_COUNT }}"
    vpc_subnet_id: "{{ subnet.subnet.id }}"
    assign_public_ip: no