import os
import subprocess
from typing import Optional
from pydantic import BaseModel, Field
from langchain.tools import Tool
import shutil
class Tools:
def create_resource_group(resource_group_name: str, location: str) -> str:
""" Modify rg-main.tf file and create a Resource Group by running Terraform."""
missingRG = False
missingLocation = False
# Error handling for empty or None inputs
if not resource_group_name or resource_group_name.lower() in ["unknown", "none", "none"]:
missingRG = True
if not location or location.lower() in ["unknown", "none", "none"]:
missingLocation = True
if missingRG and missingLocation:
return "Both Resource Group name and Location are missing."
elif missingRG:
return "Resource Group name is missing."
elif missingLocation:
return "Location is missing."
try:
new_directory = os.path.expanduser(f"~/autogen/RG/{resource_group_name}")
if not os.path.exists(new_directory):
os.makedirs(new_directory)
else:
return f"Resource Group '{resource_group_name}' already exists."
original_tf_file_path = os.path.expanduser("~/autogen/RG/rg-main.tf")
new_tf_file_path = os.path.join(new_directory, "rg-main.tf")
shutil.copy(original_tf_file_path, new_tf_file_path)
with open(new_tf_file_path, "r") as file:
tf_code = file.read()
tf_code = tf_code.replace("REPLACE_WITH_RG_NAME", resource_group_name)
tf_code = tf_code.replace("REPLACE_WITH_LOCATION", location)
with open(new_tf_file_path, "w") as file:
file.write(tf_code)
subprocess.run(["terraform", "init"], check=True, cwd=new_directory)
plan_result = subprocess.run(["terraform", "plan"], capture_output=True, text=True, cwd=new_directory)
if "0 to destroy" not in plan_result.stdout:
return "There are resources to be destroyed. Please check the plan output."
subprocess.run(["terraform", "apply", "-auto-approve"], check=True, cwd=new_directory)
return f"Resource group '{resource_group_name}' in '{location}' created successfully."
except subprocess.CalledProcessError as e:
return f"Error executing Terraform code: {str(e)}"
except Exception as e:
return f"Error: {str(e)}"