【问题标题】:Can I use Jinja2 `map` filter in an Ansible play to get values from an array of objects?我可以在 Ansible 游戏中使用 Jinja2 `map` 过滤器从对象数组中获取值吗?
【发布时间】:2016-12-22 15:08:14
【问题描述】:

我有一本用于创建一些 EC2 实例然后用它们做一些事情的剧本。相关部分大致如下:

- name: create ec2 instances
  ec2:
    id: '{{ item.name }}'
    instance_type: '{{ item.type }}'
  register: ec2
  with_items: '{{ my_instance_defs }}'
- name: wait for SSH
  wait_for:
    host: '{{ item.instances[0].private_ip }}'
    port: 22
  with_items: '{{ ec2.results }}'

这按预期工作,但我对item.instances[0].private_ip 表达式并不特别满意,部分原因是它在播放摘要中显示了非常大的对象。我希望with_items 部分只是一个 IP 地址数组,而不是一个对象数组,其中包含对象数组。在 Python 中,我会执行以下操作:

ips = [r['instances'][0]['private_ip'] for r in ec2['results']]

然后我会在第二个任务中使用with_items: '{{ ips }}'

有没有办法在剧本的 YAML 中使用 J2 过滤器来做同样的事情?似乎http://docs.ansible.com/ansible/playbooks_filters.html#extracting-values-from-containers 可能会有所帮助,但我认为前提是我有一组键/索引/任何东西。

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    map 在这里过滤你的朋友。

    类似这样的:

    with_items: "{{ ec2.results | map(attribute='instances') | map('first') | map(attribute='private_ip') | list }}"
    

    以上代码未经测试。
    您可能想先尝试使用debug,然后逐渐添加maps 以​​获得所需的结果。
    不要忘记将| list 放在末尾以使您的地图可读。

    【讨论】:

    • 像魅力一样工作!在阅读您的示例和jinja.pocoo.org/docs/dev/templates/#builtin-filters 的文档之前,我不太明白map 应该如何工作。也可以为list 建议 +1。
    • 由于我在多个地方使用 IP 数组,我决定使用set_fact: ec2_ips={{ ec2.results | map(attribute="instances") | map("first") | map(attribute="private_ip") | list }}
    【解决方案2】:

    我的示例是从我的剧本中提取的,删除了一个自动缩放的 ecs 集群。我修改了上述答案以使我的工作正常。

    - name: get list of instances in ASG
      ec2_instance_facts:
        filters:
          "tag:aws:autoscaling:groupName": "{{item.name}}-{{stack}}-scalinggroup"
      register: asg_host_list
    
    - name: list ecs info
      debug:
        msg: "{{asg_host_list}}"
    
    - name: get just hosts id's
      set_fact:
        hostlist: "{{ asg_host_list.instances | map(attribute='instance_id') | list }}"
    

    对于我来说,hostlist 可以直接输入到 ecs_instance,因为它需要一个实例 ID 列表来处理。

    所以,这是经过测试并且有效的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多