mirror of
https://gitlab.sectorq.eu/home/docker-compose.git
synced 2025-12-14 18:34:53 +01:00
build
This commit is contained in:
58
copu_to_volume.py
Normal file
58
copu_to_volume.py
Normal file
@@ -0,0 +1,58 @@
|
||||
import docker
|
||||
import os
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Portainer helper - use env vars or pass credentials.")
|
||||
|
||||
parser.add_argument("--volume_name","-v", type=str, default=None, help="Volume name")
|
||||
parser.add_argument("--source_dir","-s", type=str, default=None, help="Source directory to copy from")
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
def copy_to_volume(volume_name, source_dir, container_path="/data", image="busybox:latest"):
|
||||
"""
|
||||
Copy all files from source_dir into a Docker volume using a temporary container.
|
||||
Creates the volume if it does not exist.
|
||||
|
||||
:param volume_name: Name of the Docker volume
|
||||
:param source_dir: Local directory to copy
|
||||
:param container_path: Path inside the container where volume is mounted
|
||||
:param image: Temporary container image
|
||||
"""
|
||||
client = docker.from_env()
|
||||
|
||||
if not os.path.isdir(source_dir):
|
||||
raise ValueError(f"Source directory {source_dir} does not exist")
|
||||
|
||||
# Check if volume exists
|
||||
try:
|
||||
volume = client.volumes.get(volume_name)
|
||||
print(f"Volume '{volume_name}' exists.")
|
||||
except docker.errors.NotFound:
|
||||
print(f"Volume '{volume_name}' does not exist. Creating...")
|
||||
volume = client.volumes.create(name=volume_name)
|
||||
print(f"Volume '{volume_name}' created.")
|
||||
|
||||
print(f"Copying files from {source_dir} to volume '{volume_name}'...")
|
||||
|
||||
# Run temporary container to copy files
|
||||
client.containers.run(
|
||||
image,
|
||||
command=f"sh -c 'cp -r /tmp/* {container_path}/'",
|
||||
volumes={
|
||||
volume_name: {"bind": container_path, "mode": "rw"},
|
||||
os.path.abspath(source_dir): {"bind": "/tmp", "mode": "ro"}
|
||||
},
|
||||
remove=True,
|
||||
detach=False
|
||||
)
|
||||
|
||||
print("Files copied successfully.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage
|
||||
copy_to_volume(
|
||||
volume_name=args.volume_name,
|
||||
source_dir=args.source_dir,
|
||||
container_path="/data"
|
||||
)
|
||||
Reference in New Issue
Block a user