All checks were successful
		
		
	
	Build And Test / build-and-push (push) Successful in 3m17s
				
			
		
			
				
	
	
		
			58 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			58 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
# msa-django-ansible/services.py
 | 
						|
import os
 | 
						|
import requests
 | 
						|
import tempfile
 | 
						|
import subprocess
 | 
						|
from django.conf import settings
 | 
						|
from .models import AnsibleTask
 | 
						|
 | 
						|
 | 
						|
def get_ssh_key_from_auth_server(access_token: str) -> str:
 | 
						|
    url = settings.AUTH_APP_URL + "/api/auth/ssh-key/view/"
 | 
						|
    print(url)
 | 
						|
    headers = {"Authorization": f"Bearer {access_token}"}
 | 
						|
    response = requests.get(url, headers=headers)
 | 
						|
    if response.status_code != 200:
 | 
						|
        raise Exception("🔐 Auth 서버에서 SSH 키 조회 실패")
 | 
						|
    return response.json().get("ssh_key")
 | 
						|
 | 
						|
 | 
						|
def run_ansible_job(task: AnsibleTask, ssh_key: str):
 | 
						|
    task.status = "running"
 | 
						|
    task.save()
 | 
						|
 | 
						|
    try:
 | 
						|
        with tempfile.NamedTemporaryFile(delete=False, mode="w") as playbook_file, \
 | 
						|
             tempfile.NamedTemporaryFile(delete=False, mode="w") as inventory_file, \
 | 
						|
             tempfile.NamedTemporaryFile(delete=False, mode="w") as private_key_file:
 | 
						|
 | 
						|
            playbook_file.write(task.playbook_content.strip())
 | 
						|
            inventory_file.write(task.inventory_content.strip())
 | 
						|
            private_key_file.write(ssh_key.strip() + "\n")
 | 
						|
 | 
						|
            playbook_file.close()
 | 
						|
            inventory_file.close()
 | 
						|
            private_key_file.close()
 | 
						|
            os.chmod(private_key_file.name, 0o600)
 | 
						|
 | 
						|
            command = [
 | 
						|
                "ansible-playbook",
 | 
						|
                playbook_file.name,
 | 
						|
                "-i", inventory_file.name,
 | 
						|
                "--private-key", private_key_file.name,
 | 
						|
                "-u", "ubuntu",
 | 
						|
            ]
 | 
						|
 | 
						|
            result = subprocess.run(command, capture_output=True, text=True)
 | 
						|
            task.status = "success" if result.returncode == 0 else "failed"
 | 
						|
            task.output = result.stdout + "\n" + result.stderr
 | 
						|
 | 
						|
    except Exception as e:
 | 
						|
        task.status = "error"
 | 
						|
        task.output = f"\u274c 실행 중 예외 발생: {str(e)}"
 | 
						|
 | 
						|
    finally:
 | 
						|
        for f in [playbook_file.name, inventory_file.name, private_key_file.name]:
 | 
						|
            if os.path.exists(f):
 | 
						|
                os.remove(f)
 | 
						|
        task.save() |