0

I am using a csv file to get data and render it to template and copy to remote servers. I am facing issue that CSV file read twice for same server and this results in loop to copy last line in each server instead of 1st line in first server and second on second servers and so on...

test.csv file:

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

main.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

Template:

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

Expected result is to get first entry in csv in testserver1 and second line in 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

but I am getting

**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
    The answer can be found under [Ansible: Read CSV file line by line and render it to template with `loop`](https://stackoverflow.com/a/75343479/6771046). – U880D Feb 05 '23 at 01:36

1 Answers1

0

Finally got it work. Updated, working 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
Esa Jokinen
  • 46,944
  • 3
  • 83
  • 129