amazon-ec2 - Ansible jinja 过滤掉属性不等于或属性缺失的元素

标签 amazon-ec2 ansible jinja2

我有一些这样的任务:

- ec2_asg_facts:
    region: us-west-2
    tags:
      Name: my-asg
  register: asg
- set_fact:
    current_lc: "{{ asg.results | map(attribute='launch_configuration_name') | first }}"
    instances: "{{ asg.results | map(attribute='instances') | flatten | list }}"
- set_fact:
    instances_to_rotate: "{{ instances | rejectattr('launch_configuration_name', 'equalto', current_lc) | list }}"

问题是,如果实例的启动配置被删除(当我将 ASG 的启动配置更新为新配置但尚未终止旧实例时,通常会出现这种情况)launch_configuration_name 属性丢失,因此第三个任务失败,并显示消息'dict object' has no attribute 'launch_configuration_name'。如何过滤掉 instances 列表中 launch_configuration_name 属性不等于 current_lc 或具有 launch_configuration_name 的项目> 属性缺失?

最佳答案

答案是分两遍进行过滤;首先过滤掉属性未定义的项目,然后过滤掉属性不等于current_lc的项目。

- set_fact:
    instances_to_rotate: "{{ instances | rejectattr('launch_configuration_name', 'undefined') | rejectattr('launch_configuration_name', 'equalto', current_lc) | list }}"

关于amazon-ec2 - Ansible jinja 过滤掉属性不等于或属性缺失的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54081464/

相关文章:

python - 使用 Flask 使用外部 XML API(带有模型等)

templates - 如何将选定的命名参数传递给 Jinja2 的包含上下文?

amazon-web-services - 查找AWS实例是否正在运行Amazon Linux 1或2?

php - 无法将 Laravel 应用程序部署到 EC2

linux - 如何杀死 env 正在使用的端口节点

ansible - 如何让 Ansible 多行 > 忽略行中的空格?

jinja2 - 在 Ansible 中将变量连接到自身

sqlalchemy - 将 SQLAlchemy 查询传递给基本 Jinja 模板

amazon-web-services - 托管数据库(例如 Amazon RDS)的访问速度是否比 Web 服务器位于同一计算机 (EC2) 上的数据库慢

variables - 在Ansible中使用动态键名设置事实