#!/usr/bin/env python3 """ Upload Terraform files to server This script uploads all .tf files from the terraform directory to a remote server via SSH """ import os import sys from pathlib import Path import paramiko from scp import SCPClient def upload_tf_files(server_ip, username, password, local_dir="./", remote_dir="/tmp/terraform"): """ Upload the entire tfs folder to remote server Args: server_ip (str): Remote server IP address username (str): Username for SSH connection password (str): Password for SSH connection local_dir (str): Local directory containing the tfs folder remote_dir (str): Remote directory to upload files to """ try: # Create SSH client ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to server print(f"Connecting to {server_ip}...") ssh_client.connect(hostname=server_ip, username=username, password=password) # Create SCP client with SCPClient(ssh_client.get_transport()) as scp_client: # Upload the entire tfs folder local_path = Path(local_dir) if not local_path.exists(): print(f"Local directory {local_dir} does not exist") return print(f"Uploading directory: {local_dir}") # Create remote directory if it doesn't exist stdin, stdout, stderr = ssh_client.exec_command(f'mkdir -p {remote_dir}') stdout.channel.recv_exit_status() # Wait for command to complete # Upload the entire directory print(f"Uploading {local_dir} to {server_ip}:{remote_dir}/...") scp_client.put(str(local_path), remote_dir, recursive=True) print(f" [SUCCESS] Directory uploaded successfully") print(f"\nDirectory uploaded to {server_ip}:{remote_dir}/") except Exception as e: print(f"Error uploading directory: {str(e)}") raise finally: if 'ssh_client' in locals(): ssh_client.close() def main(): # Configuration SERVER_IP = "47.113.186.215" # Pre-set server IP USERNAME = "root" # Pre-set username PASSWORD = "Xs261617" # Pre-set password LOCAL_DIR = r"E:\myaliyun\cicd_yamls\terraform\tfs" # Directory containing the tfs folder REMOTE_DIR = "/root/cicd_yamls/terraform" # Remote directory to upload files to print(f"\nUploading tfs folder from {LOCAL_DIR} to {SERVER_IP}:{REMOTE_DIR}\n") upload_tf_files(SERVER_IP, USERNAME, PASSWORD, LOCAL_DIR, REMOTE_DIR) if __name__ == "__main__": main()