find_volumes.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import os
  2. import yaml
  3. import csv
  4. def parse_docker_compose(file_path):
  5. """Parse a docker-compose.yml file and extract volume information."""
  6. with open(file_path, 'r') as file:
  7. compose_data = yaml.safe_load(file)
  8. volumes = []
  9. if compose_data and 'services' in compose_data:
  10. for service_name, service_config in compose_data['services'].items():
  11. if 'volumes' in service_config:
  12. for volume in service_config['volumes']:
  13. if isinstance(volume, str):
  14. # Handle string format: "host_path:container_path"
  15. parts = volume.split(':')
  16. if len(parts) == 2:
  17. host_path, container_path = parts
  18. volumes.append((host_path, container_path))
  19. elif len(parts) == 3:
  20. # Handle cases like "host_path:container_path:ro"
  21. host_path, container_path, _ = parts
  22. volumes.append((host_path, container_path))
  23. elif isinstance(volume, dict):
  24. # Handle dictionary format: { 'source': 'host_path', 'target': 'container_path' }
  25. if 'source' in volume and 'target' in volume:
  26. volumes.append((volume['source'], volume['target']))
  27. return volumes
  28. def traverse_directory(root_dir):
  29. """Traverse the directory and find all docker-compose.yml files."""
  30. results = []
  31. for dirpath, _, filenames in os.walk(root_dir):
  32. if 'docker-compose.yml' in filenames:
  33. compose_file = os.path.join(dirpath, 'docker-compose.yml')
  34. volumes = parse_docker_compose(compose_file)
  35. for host_path, container_path in volumes:
  36. results.append((dirpath, host_path, container_path))
  37. return results
  38. def write_to_csv(data, output_file):
  39. """Write the volume data to a CSV file."""
  40. headers = ["Directory", "Volume (Host Path)", "Bind Point (Container Path)"]
  41. with open(output_file, mode='w', newline='') as file:
  42. writer = csv.writer(file)
  43. writer.writerow(headers) # Write the header row
  44. writer.writerows(data) # Write the data rows
  45. def main():
  46. root_directory = input("Enter the root directory to traverse: ")
  47. if not os.path.isdir(root_directory):
  48. print("Invalid directory path.")
  49. return
  50. output_csv = input("Enter the output CSV file path (e.g., output.csv): ")
  51. # Traverse the directory and get volume information
  52. volume_data = traverse_directory(root_directory)
  53. # Write the results to a CSV file
  54. if volume_data:
  55. write_to_csv(volume_data, output_csv)
  56. print(f"Volume data has been written to {output_csv}")
  57. else:
  58. print("No docker-compose.yml files with volumes found.")
  59. if __name__ == "__main__":
  60. main()