File size: 10,669 Bytes
f7f94f6
 
9d94cf5
 
8bcd745
 
f7f94f6
9d94cf5
f7f94f6
 
 
 
9d94cf5
 
 
 
f7f94f6
 
 
9d94cf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bcd745
 
9d94cf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bcd745
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33960b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f94f6
 
 
 
9d94cf5
 
 
33960b7
9d94cf5
 
 
 
f7f94f6
 
 
9d94cf5
f7f94f6
9d94cf5
f7f94f6
 
 
9d94cf5
f7f94f6
 
9d94cf5
 
 
 
f7f94f6
 
9d94cf5
f7f94f6
 
 
9d94cf5
 
 
 
33960b7
 
9d94cf5
 
f7f94f6
9d94cf5
f7f94f6
 
8bcd745
 
 
 
 
 
 
 
 
33960b7
 
 
 
f7f94f6
33960b7
f7f94f6
 
8bcd745
f7f94f6
 
 
 
 
 
 
 
33960b7
f7f94f6
9d94cf5
 
f7f94f6
9d94cf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f94f6
9d94cf5
 
 
 
 
 
 
 
8bcd745
 
 
 
 
 
 
 
 
 
33960b7
 
 
 
 
 
8bcd745
 
 
 
 
 
f7f94f6
9d94cf5
f7f94f6
9d94cf5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import streamlit as st
import json
from jsonschema import validate, ValidationError
import re
import networkx as nx
import matplotlib.pyplot as plt

# Mock existing resources (customizable)
existing_resources = {
    "storageAccount1": {
        "type": "Microsoft.Storage/storageAccounts",
        "location": "East US",
        "status": "existing",
        "properties": {
            "accountType": "Standard_LRS"
        }
    }
}

# ARM template schema (simplified version)
arm_schema = {
    "type": "object",
    "properties": {
        "$schema": {"type": "string"},
        "contentVersion": {"type": "string"},
        "parameters": {"type": "object"},
        "variables": {"type": "object"},
        "resources": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["type", "name", "location"],
                "properties": {
                    "type": {"type": "string"},
                    "name": {"type": "string"},
                    "location": {"type": "string"},
                    "properties": {"type": "object"},
                    "dependsOn": {"type": "array", "items": {"type": "string"}}
                }
            }
        },
        "outputs": {"type": "object"}
    },
    "required": ["$schema", "contentVersion", "resources"]
}

def validate_template(template):
    try:
        validate(instance=template, schema=arm_schema)
        return True, "Template is valid."
    except ValidationError as e:
        return False, f"Template validation error: {e.message}"

def resolve_template_expressions(template):
    def resolve_expression(match):
        expr = match.group(1)
        parts = expr.split('.')
        if parts[0] == 'parameters':
            return str(template.get('parameters', {}).get(parts[1], {}).get('defaultValue', ''))
        elif parts[0] == 'variables':
            return str(template.get('variables', {}).get(parts[1], ''))
        return match.group(0)

    template_str = json.dumps(template)
    resolved_str = re.sub(r'\[(\w+\.\w+)\]', resolve_expression, template_str)
    return json.loads(resolved_str)

def estimate_cost(resources):
    # This is a simplified cost estimation. In a real scenario, you'd need to
    # integrate with Azure's pricing API or use a more comprehensive pricing model.
    cost_estimates = {
        "Microsoft.Storage/storageAccounts": 10,  # $10 per month
        "Microsoft.Compute/virtualMachines": 50,  # $50 per month
        "Microsoft.Web/sites": 30,  # $30 per month
        "Microsoft.Sql/servers": 40,  # $40 per month
        # Add more resource types and their estimated costs
    }
    
    total_cost = 0
    for resource in resources:
        resource_type = resource.get('type')
        if resource_type in cost_estimates:
            total_cost += cost_estimates[resource_type]
        else:
            total_cost += 5  # Default cost for unknown resource types
    
    return total_cost

def create_dependency_graph(resources):
    G = nx.DiGraph()
    for resource in resources:
        resource_name = resource.get('name')
        G.add_node(resource_name)
        dependencies = resource.get('dependsOn', [])
        for dep in dependencies:
            G.add_edge(dep, resource_name)
    return G

def plot_dependency_graph(G):
    plt.figure(figsize=(12, 8))
    pos = nx.spring_layout(G)
    nx.draw(G, pos, with_labels=True, node_color='lightblue', 
            node_size=3000, font_size=8, font_weight='bold')
    edge_labels = nx.get_edge_attributes(G, 'weight')
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
    plt.title("Resource Dependency Graph")
    return plt

def lint_template(template):
    lint_results = []
    
    # Check 1: Ensure all resources have tags
    for resource in template.get('resources', []):
        if 'tags' not in resource:
            lint_results.append(f"Warning: Resource '{resource.get('name')}' does not have any tags.")
    
    # Check 2: Ensure parameters have descriptions
    for param_name, param_value in template.get('parameters', {}).items():
        if 'metadata' not in param_value or 'description' not in param_value['metadata']:
            lint_results.append(f"Warning: Parameter '{param_name}' does not have a description.")
    
    # Check 3: Warn about hardcoded values in resource properties
    for resource in template.get('resources', []):
        for prop, value in resource.get('properties', {}).items():
            if isinstance(value, (str, int, float)) and not isinstance(value, bool):
                lint_results.append(f"Info: Consider using a parameter for the hardcoded value in resource '{resource.get('name')}', property '{prop}'.")
    
    return lint_results

def generate_system_diagram(resources):
    diagram = ["graph TD"]
    resource_nodes = {}
    
    # Create nodes for each resource
    for i, resource in enumerate(resources):
        resource_type = resource['type'].split('/')[-1]
        node_id = f"R{i}"
        resource_nodes[resource['name']] = node_id
        diagram.append(f"{node_id}[{resource_type}<br/>{resource['name']}]")
    
    # Create connections based on dependencies
    for resource in resources:
        if 'dependsOn' in resource:
            for dependency in resource['dependsOn']:
                if dependency in resource_nodes:
                    diagram.append(f"{resource_nodes[dependency]} --> {resource_nodes[resource['name']]}")
    
    return "\n".join(diagram)

def simulate_deployment(arm_template):
    try:
        template = json.loads(arm_template)
        
        # Validate template
        is_valid, validation_message = validate_template(template)
        if not is_valid:
            return [], [], [], [], 0, None, [], "", validation_message

        # Resolve expressions
        resolved_template = resolve_template_expressions(template)

        resources_to_create = []
        resources_to_update = []
        resources_to_delete = []
        resource_details = []

        for resource in resolved_template.get('resources', []):
            resource_name = resource.get('name')
            resource_type = resource.get('type')
            location = resource.get('location')
            properties = resource.get('properties', {})

            if resource_name in existing_resources:
                existing = existing_resources[resource_name]
                if (existing['type'] == resource_type and
                    existing['location'] == location and
                    existing['properties'] == properties):
                    resources_to_update.append(resource_name)
                else:
                    resources_to_create.append(resource_name)
            else:
                resources_to_create.append(resource_name)

            resource_details.append({
                "name": resource_name,
                "type": resource_type,
                "location": location,
                "properties": properties,
                "dependsOn": resource.get('dependsOn', [])
            })

        for resource_name in existing_resources:
            if resource_name not in [r.get('name') for r in resolved_template.get('resources', [])]:
                resources_to_delete.append(resource_name)

        # Estimate cost
        estimated_cost = estimate_cost(resource_details)

        # Create dependency graph
        dependency_graph = create_dependency_graph(resolved_template.get('resources', []))

        # Lint template
        lint_results = lint_template(template)

        # Generate system diagram
        system_diagram = generate_system_diagram(resource_details)

        return resources_to_create, resources_to_update, resources_to_delete, resource_details, estimated_cost, dependency_graph, lint_results, system_diagram, "Simulation completed successfully."
    except json.JSONDecodeError:
        return [], [], [], [], 0, None, [], "", "Invalid JSON format. Please check your ARM template."

# Streamlit UI
st.title("Comprehensive ARM Template Simulator")
st.subheader("Paste your ARM template below to simulate its deployment.")

# Input box for ARM template
template_input = st.text_area("Paste ARM Template JSON here:", height=300)

# Button to simulate the evaluation
if st.button("Simulate Template"):
    if template_input:
        resources_to_create, resources_to_update, resources_to_delete, resource_details, estimated_cost, dependency_graph, lint_results, system_diagram, message = simulate_deployment(template_input)
        
        st.subheader("Simulation Results:")
        st.write(message)

        if resources_to_create or resources_to_update or resources_to_delete:
            st.write("### Resources to be Created:")
            if resources_to_create:
                st.write(resources_to_create)
            else:
                st.write("No new resources will be created.")

            st.write("### Resources to be Updated:")
            if resources_to_update:
                st.write(resources_to_update)
            else:
                st.write("No resources will be updated.")

            st.write("### Resources to be Deleted:")
            if resources_to_delete:
                st.write(resources_to_delete)
            else:
                st.write("No resources will be deleted.")

            st.write("### Detailed Resource Information:")
            for resource in resource_details:
                st.write(f"**Name:** {resource['name']}")
                st.write(f"**Type:** {resource['type']}")
                st.write(f"**Location:** {resource['location']}")
                st.write("**Properties:**")
                st.json(resource['properties'])
                st.write("---")

            st.write(f"### Estimated Monthly Cost: ${estimated_cost}")

            st.write("### Resource Dependency Graph:")
            if dependency_graph:
                fig = plot_dependency_graph(dependency_graph)
                st.pyplot(fig)
            else:
                st.write("No dependencies found between resources.")

            st.write("### System Diagram:")
            if system_diagram:
                st.mermaid(system_diagram)
            else:
                st.write("Unable to generate system diagram.")

            st.write("### Template Lint Results:")
            if lint_results:
                for result in lint_results:
                    st.write(result)
            else:
                st.write("No linting issues found.")
        else:
            st.write("No changes detected in the simulation.")
    else:
        st.error("Please paste an ARM template to simulate.")