使用Ansible查询AWS EC2 AMI时遍历结果报错求助
Let's walk through fixing your playbook step by step. I see a couple of key issues that are causing the loop error:
1. Replace Deprecated Module
The ec2_ami_facts module is deprecated and no longer actively maintained. You should switch to the newer amazon.aws.ec2_ami_info module from the Amazon AWS collection. First, make sure you have the collection installed if you haven't already:
ansible-galaxy collection install amazon.aws
2. Fix Loop Syntax & JSON Query
Your loop has unnecessary extra spaces around the Jinja2 expression, which causes Ansible to treat the result as a string instead of a list. Additionally, we can simplify the JSON query to combine your two filters into one for better readability and efficiency.
Here's the corrected playbook:
- hosts: localhost tasks: - name: Get Amazon Linux AMIs amazon.aws.ec2_ami_info: owner: amazon filters: architecture: x86_64 root-device-type: ebs register: amis - name: Return filtered AMI data debug: msg: "{{ item }}" loop: "{{ amis | json_query('Images[?Description!=`null` && starts_with(Description, `Amazon Linux`)]') }}"
Key Fixes Explained:
- Removed extra spaces in the
loopvalue: The original had" {{ ... }} "which added unnecessary whitespace. Now it's{{ ... }}directly, ensuring Ansible interprets it as a list of AMI objects. - Combined JSON query filters: Instead of two separate pipe-separated filters, we use
&&to check both conditions (non-null description and starts with "Amazon Linux") in one go. - Updated module:
amazon.aws.ec2_ami_infois the officially supported replacement for the oldec2_ami_factsmodule.
3. Extracting Just Image IDs
Once the loop works correctly, you can modify the task to return only the image IDs by adjusting the msg field:
- name: Return filtered AMI IDs debug: msg: "{{ item.ImageId }}" loop: "{{ amis | json_query('Images[?Description!=`null` && starts_with(Description, `Amazon Linux`)]') }}"
Alternatively, you can use JSON query to extract the IDs directly in the loop, making the debug task simpler:
- name: Return filtered AMI IDs debug: msg: "{{ item }}" loop: "{{ amis | json_query('Images[?Description!=`null` && starts_with(Description, `Amazon Linux`)].ImageId') }}"
Testing the Query
If you want to verify the JSON query returns the expected list before looping, add a debug task to print the raw query result:
- name: Print filtered AMIs list debug: var: amis | json_query('Images[?Description!=`null` && starts_with(Description, `Amazon Linux`)]')
This should resolve your loop error and give you the filtered AMI data you need.
内容的提问来源于stack exchange,提问作者Neil H Watson

