我如何使用index_var值作为ansible列表中的索引?

问题描述 投票:0回答:1

我想用 ansible 交换几个配置文件中的单独行。 为此,我生成临时文件,在其中准备新行。 现在我想使用一个 index_var 变量作为 Ansible 列表中的索引。

不评估变量 my_idx。没有错误,但表达式似乎产生空字符串。如果我暂时将变量交换为有效索引,例如0 或 1,有效。

我想用 ansible 做的事情真的有用吗?

- name: Read temp file with color list
  slurp:
    src: /etc/{{item.name}}.tmp
  register: color_files
  with_items:
  - { name: 'blue', code: '#346eeb'}
  - { name: 'red', code: '#eb3434'}
  - { name: 'black', code: '#000000'}


- name: change config files
  ansible.builtin.lineinfile:
    path: /etc/{{ item.name }}.properties
    regexp: '^font.color='
    line: font.color={{color_files.results[my_idx].content | b64decode}}"
  with_items: 
    - { name: 'blue', code: '#346eeb'}
    - { name: 'red', code: '#eb3434'}
    - { name: 'black', code: '#000000'}
  loop_control:
    index_var: my_idx

这有效:

- name: Count our Colors
  ansible.builtin.debug:
    msg: "{{ item }} with index {{ my_idx }}"
  with_items:
    - { name: 'blue', code: '#346eeb'}
    - { name: 'red', code: '#eb3434'}
    - { name: 'black', code: '#000000'}
  loop_control:
    index_var: my_idx
ansible jinja2
1个回答
0
投票

这里似乎有几个不同的问题

我想与 Ansible 交换多个配置文件中的单独行。

由于当前给出的描述,我喜欢推荐使用

如何使用

index_var
值作为 Ansible 列表中的索引?

一个最小的示例手册

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    LIST:
      - A
      - B
      - C
      - D
      - E
      - F

  tasks:

  - debug:
      msg: "{{ item }} with index {{ my_idx }}"
    loop: "{{ LIST }}"
    loop_control:
      index_var: my_idx

  - debug:
      msg: "{{ LIST[item] }}"
    loop: [1, 2, 3]

将产生

的输出
TASK [debug] *****************
ok: [localhost] => (item=A) =>
  msg: A with index 0
ok: [localhost] => (item=B) =>
  msg: B with index 1
ok: [localhost] => (item=C) =>
  msg: C with index 2
ok: [localhost] => (item=D) =>
  msg: D with index 3
ok: [localhost] => (item=E) =>
  msg: E with index 4
ok: [localhost] => (item=F) =>
  msg: F with index 5

TASK [debug] *****************
ok: [localhost] => (item=1) =>
  msg: B
ok: [localhost] => (item=2) =>
  msg: C
ok: [localhost] => (item=3) =>
  msg: D

因此

  - debug:
      msg: "{{ LIST[my_idx] }}"
    loop: "{{ LIST }}"
    loop_control:
      index_var: my_idx

输出为

TASK [debug] *****************
ok: [localhost] => (item=A) =>
  msg: A
ok: [localhost] => (item=B) =>
  msg: B
ok: [localhost] => (item=C) =>
  msg: C
ok: [localhost] => (item=D) =>
  msg: D
ok: [localhost] => (item=E) =>
  msg: E
ok: [localhost] => (item=F) =>
  msg: F

但正如人们所看到的,这是不必要的,并且再次实现已经存在的功能。

文档

© www.soinside.com 2019 - 2024. All rights reserved.