Ansible:逐行读取 csv 文件并使用循环将其呈现到模板

Ansible:逐行读取 csv 文件并使用循环将其呈现到模板

我正在使用 csv 文件获取数据并将其呈现到模板并复制到远程服务器。我面临的问题是,CSV 文件对同一台服务器读取两次,这导致循环复制每台服务器的最后一行,而不是第一台服务器的第一行和第二台服务器的第二行,依此类推...

测试.csv文件:

Application,env,Datacenter,Hostname
Microsoft,Test,DC1,testserver1
Apple,Test,DC2,testserver2

主要.yml:

- name: read csv
  read_csv:
    path: /u00/app/monitor/test.csv
    key: Hostname
  register: newrelic

- name: Print newrelic var
  ansible.builtin.debug:
    var: newrelic.dict[inventory_hostname]

- name: copy template
  template:
    src: /u00/ansible/Playbooks/files/infra-config.yml_template
    dest: /u00/app/monitor/infra-config.yml
  loop: "{{ newrelic.list }}"

- name: Start the New Relic Service
  ansible.builtin.systemd:
    name: newrelic-infra.service
    state: started
  become: yes
  become_user: root

模板:

custom_attributes:
    application : {{ item.Application }}
    env : {{ item.env }}
    datacenter : {{ item.Datacenter }}
log:
 file: /u00/app/monitor/infra.log

预期结果是获取 testserver1 中 csv 的第一个条目和 testserver2 中的第二行

**ssh admin@testserver1 - **

cat infra-config.yml

custom_attributes:
    application : Microsoft
    env : Test
    datacenter : DC1
log:
 file: /u00/app/monitor/infra.log

**ssh admin@testserver2- **

custom_attributes:
    application : Apple
    env : Test
    datacenter : DC2
log:
 file: /u00/app/monitor/infra.log

但我得到了

**ssh admin@testserver1 -** 

cat infra-config.yml

custom_attributes:
    application : Apple
    env : Test
    datacenter : DC2
log:
 file: /u00/app/monitor/infra.log

**ssh admin@testserver2- **

custom_attributes:
    application : Apple
    env : Test
    datacenter : DC2
log:
 file: /u00/app/monitor/infra.log

答案1

终于让它工作了。更新后,main.yml 正常运行:

- name: read csv
  read_csv:
    path: /u00/app/test.csv. #present in controller
    key: Hostname
  register: newrelic

- name: Print newrelic var
  ansible.builtin.debug:
    var: newrelic.dict[inventory_hostname]

- name: copy template
  template:
    src: /u00/ansible/Playbooks/files/infra-config.yml_template
    dest: /u00/app/monitor/infra-config.yml
  vars:
    item: "{{ newrelic.dict[inventory_hostname] }}"

- name: Start the New Relic Service
  ansible.builtin.systemd:
    name: newrelic-infra.service
    state: started
  become: yes
  become_user: root

相关内容