首页 > 解决方案 > 从 ansible 中的 with_sequence 检索索引值

问题描述

如何检索在 ansible 的 with_sequence 循环中使用的索引“{{ item }}”值?我使用以下代码:

- name: Check if Route 53 DNS record exists
  route53:
    state: get
    zone: zone_id
    private_zone: true
    record: testrecord{{ item }}.foo.com
    type: A
  register: dns_record
  when: (dns_record is not defined) or (dns_record.set | length > 0)
  with_sequence: start=0 end=9

当此代码块退出时,我无法检索 {{ item }} 值我以后如何仍然使用此值?

标签: ansible

解决方案


当此代码块退出时,我无法检索 {{ item }} 值我以后如何仍然使用此值?

不是真的;如果你检查了你的变量register:(用类似的东西- debug: var=dns_record)你会观察到有一个results列表,它是list[dict]一个顶级键,用于item显示item每次迭代的值

  tasks:
  - debug:
      msg: item is {{ item }}
    with_sequence: start=0 end=5
    register: the_items
  - debug: var=the_items

生产

TASK [debug] ********************************************************************************************************************
ok: [localhost] => {
    "the_items": {
        "changed": false,
        "msg": "All items completed",
        "results": [
            {
                "ansible_loop_var": "item",
                "changed": false,
                "failed": false,
                "item": "0",
                "msg": "item is 0"
            },

推荐阅读