PZY
PZY

Reputation: 151

How to copy log file from multi hosts to a host directory, file named by source host ip using ansible?

I need to analyze nginx log file from multi hosts.

First, i want to copy them to a host directory. For example, i want to copy nginx error log file from 6 hosts to a destination host directory.

The 6 hosts ips are 192.168.0.2 - 192.168.0.7. The nginx error log path is /var/log/nginx/nginx_error.log. I want to copy them to /var/log/nginx_error directory in destination host 192.168.0.10. Every file is named by source host ip. How can i write playbook using ansible?

[serverB]
192.168.0.10
[serverA]
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5

- hosts: serverB
  tasks:    
   - name: Copy Remote-To-Remote (from serverA to serverB)
     synchronize: src=/var/log/nginx/nginx_error.log dest=/var/log/nginx_error/
     delegate_to: serverA

The problem is that i can't know how to name dest file using source ip address?

Upvotes: 0

Views: 560

Answers (1)

Ada Pongaya
Ada Pongaya

Reputation: 415

I don't have an elegant solution. some workaround here. to name dest file using source ip you can use ansible_hostname or inventory_hostname variable defined by ansible. Make sure that you've created the /tmp/nginx_logs/ directory in ansible controller before executing.

---
- name : Copy Remote
  hosts: serverA, serverB
  tasks:
  - name: Copy the files from the Source Machine(serverA) to Ansible Controller
    synchronize:
      mode: pull
      src: /var/log/nginx/nginx_error.log
      dest: "/tmp/nginx_logs/test_{{ ansible_hostname }}.txt"
    when: "inventory_hostname in groups['serverA']"

  - name: Copy log files to the destination server
    copy:
      src: /tmp/nginx_logs/
      dest: /var/log/nginx_error/
    when: "inventory_hostname in groups['serverB']"

Upvotes: 1

Related Questions