【问题标题】:Use loop to splice string, item is undefined使用循环拼接字符串,项目未定义
【发布时间】:2022-01-04 05:32:50
【问题描述】:

下面是我的任务代码:

- name: Add calculation nodes of different groups to the list
  set_fact: 
    list_of_all_calculate_node: "{{  list_of_all_calculate_node | default([]) + ['random_calculate_host' + ('{{ item }}' | string ) ]  }}"
  loop: "{{ range(1,5) }}"

- name: Print  list_of_all_calculate_node
  debug:
    var: "{{ item }}"
  loop: "{{ list_of_all_calculate_node }}"

错误类型:致命

TASK [Print  list_of_all_calculate_node]
fatal: [*.*.*.*]: FAILED! => {"msg": "['random_calculate_host2', 'random_calculate_host3', 'random_calculate_host4', 'random_calculate_host{{ item }}']: 'item' is undefined"}

预期的输出应该是: ['random_calculate_host1','random_calculate_host2', 'random_calculate_host3', 'random_calculate_host4']

【问题讨论】:

标签: ansible jinja2


【解决方案1】:

在 Ansible 中,大括号 {{ }} 不能嵌套。修正语法,例如

    - set_fact:
        l: "{{  l|d([]) + ['random_calculate_host' ~ item] }}"
      loop: "{{ range(1,5) }}"

给予

  l:
  - random_calculate_host1
  - random_calculate_host2
  - random_calculate_host3
  - random_calculate_host4

您不必迭代 范围,例如下面的任务给出了相同的结果

    - set_fact:
        l: "{{ ['random_calculate_host']|product(range(1,5))|map('join')|list }}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多