Spaces:
Runtime error
Runtime error
import os | |
import json | |
import tempfile | |
from azure.identity import DefaultAzureCredential | |
from azure.mgmt.resource import ResourceManagementClient | |
from python_terraform import Terraform | |
import streamlit as st | |
# Set up Azure credentials | |
credential = DefaultAzureCredential() | |
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] | |
# Initialize ResourceManagementClient | |
resource_client = ResourceManagementClient(credential, subscription_id) | |
# Initialize Terraform | |
tf = Terraform(working_dir=tempfile.mkdtemp()) | |
# Streamlit app | |
st.title("Azure SDK and Terraform Demo") | |
# Get the list of resource groups | |
resource_groups = [rg.name for rg in resource_client.resource_groups.list()] | |
# Select a resource group | |
selected_rg = st.selectbox("Select a Resource Group", resource_groups) | |
if selected_rg: | |
# Display resources in the selected resource group | |
resources = resource_client.resources.list_by_resource_group(selected_rg) | |
st.subheader(f"Resources in Resource Group: {selected_rg}") | |
for resource in resources: | |
st.write(f"{resource.type}: {resource.name}") | |
# Terraform configurations | |
st.subheader("Terraform Configuration") | |
# Set up the Terraform configuration | |
terraform_config = f""" | |
provider "azurerm" {{ | |
features {{}} | |
}} | |
resource "azurerm_resource_group" "example" {{ | |
name = "{selected_rg}" | |
location = "East US" | |
}} | |
resource "azurerm_virtual_network" "example" {{ | |
name = "example-network" | |
address_space = ["10.0.0.0/16"] | |
location = azurerm_resource_group.example.location | |
resource_group_name = azurerm_resource_group.example.name | |
}} | |
resource "azurerm_subnet" "example" {{ | |
name = "internal" | |
resource_group_name = azurerm_resource_group.example.name | |
virtual_network_name = azurerm_virtual_network.example.name | |
address_prefix = "10.0.2.0/24" | |
}} | |
""" | |
# Save the Terraform configuration to a file | |
with open("main.tf", "w") as f: | |
f.write(terraform_config) | |
st.code(terraform_config, language="hcl") | |
if st.button("Apply Terraform"): | |
# Initialize and apply Terraform configuration | |
tf.init() | |
ret_code, stdout, stderr = tf.apply(skip_plan=True, capture_output=True) | |
if ret_code == 0: | |
st.success("Terraform applied successfully!") | |
st.code(stdout, language="bash") | |
else: | |
st.error("Error applying Terraform configuration") | |
st.code(stderr, language="bash") | |