Riya Achkarpohre, Author at Perficient Blogs https://blogs.perficient.com/author/rachkarpohre/ Expert Digital Insights Thu, 25 Sep 2025 10:34:59 +0000 en-US hourly 1 https://blogs.perficient.com/files/favicon-194x194-1-150x150.png Riya Achkarpohre, Author at Perficient Blogs https://blogs.perficient.com/author/rachkarpohre/ 32 32 30508587 Terraform Code Generator Using Ollama and CodeGemma https://blogs.perficient.com/2025/09/25/terraform-code-generator-using-ollama-and-codegemma/ https://blogs.perficient.com/2025/09/25/terraform-code-generator-using-ollama-and-codegemma/#comments Thu, 25 Sep 2025 10:34:37 +0000 https://blogs.perficient.com/?p=387185

In modern cloud infrastructure development, writing Terraform code manually can be time-consuming and error-prone—especially for teams that frequently deploy modular and scalable environments. There’s a growing need for tools that:

  • Allow natural language input to describe infrastructure requirements.
  • Automatically generate clean, modular Terraform code.
  • Integrate with cloud authentication mechanisms.
  • Save and organize code into execution-ready files.

This model bridges the gap between human-readable Infrastructure descriptions and machine-executable Terraform scripts, making infrastructure-as-code more accessible and efficient. To build this model, we utilize CodeGemma, a lightweight AI model optimized for coding tasks, which runs locally via Ollama.

Qadkyxzvpwpsnkuajbujylwozlw36aeyw Mos4qgcxocvikd9fqwlwi18nu1eejv9khrb52r Ak3lastherfdzlfuhwfzzf4kelmucdplzzkdezh90a

In this blog, we explore how to build a Terraform code generator web app using:

  • Flask for the web interface
  • Ollama’s CodeGemma model for AI-powered code generation
  • Azure CLI authentication using service principal credentials
  • Modular Terraform file creation based on user queries

This tool empowers developers to describe infrastructure needs in natural language and receive clean, modular Terraform code ready for deployment.

Technologies Used

CodeGemma

CodeGemma is a family of lightweight, open-source models optimized for coding tasks. It supports code generation from natural language.

Running CodeGemma locally via Ollama means:

  • No cloud dependency: You don’t need to send data to external APIs.
  • Faster response times: Ideal for iterative development.
  • Privacy and control: Your infrastructure queries and generated code stay on your machine.
  • Offline capability: Ideal for use in restricted or secure environments.
  • Zero cost: Since the model runs locally, there’s no usage fee or subscription required—unlike cloud-based AI services.

Flask

We chose Flask as the web framework for this project because of its:

  • Simplicity and flexibility: Flask is a lightweight and easy-to-set-up framework, making it ideal for quick prototyping.

Initial Setup

  • Install Python.
winget install Python.Python.3
ollama pull codegemma:7b
ollama run codegemma:7b
  • Install the Ollama Python library to use Gemma 3 in your Python projects.
pip install ollama

Folder Structure

Folder Structure

 

Code

from flask import Flask, jsonify, request, render_template_string
from ollama import generate
import subprocess
import re
import os

app = Flask(__name__)
# Azure credentials
CLIENT_ID = "Enter your credentials here."
CLIENT_SECRET = "Enter your credentials here."
TENANT_ID = "Enter your credentials here."

auth_status = {"status": "not_authenticated", "details": ""}
input_fields_html = ""
def authenticate_with_azure():
    try:
        result = subprocess.run(
            ["cmd.exe", "/c", "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd",
             "login", "--service-principal", "-u", CLIENT_ID, "-p", CLIENT_SECRET, "--tenant", TENANT_ID],
            capture_output=True, text=True, check=True
        )
        auth_status["status"] = "success"
        auth_status["details"] = result.stdout
    except subprocess.CalledProcessError as e:
        auth_status["status"] = "failed"
        auth_status["details"] = e.stderr
    except Exception as ex:
        auth_status["status"] = "terminated"
        auth_status["details"] = str(ex)

@app.route('/', methods=['GET', 'POST'])
def home():
    terraform_code = ""
    user_query = ""
    input_fields_html = ""

    if request.method == 'POST':
        user_query = request.form.get('query', '')

        base_prompt = (
            "Generate modular Terraform code using best practices. "
            "Create separate files for main.tf, vm.tf, vars.tf, terraform.tfvars, subnet.tf, kubernetes_cluster etc. "
            "Ensure the code is clean and execution-ready. "
            "Use markdown headers like ## Main.tf: followed by code blocks."
        )

        full_prompt = base_prompt + "\n" + user_query
        try:
            response_cleaned = generate(model='codegemma:7b', prompt=full_prompt)
            terraform_code = response_cleaned.get('response', '').strip()
        except Exception as e:
            terraform_code = f"# Error generating code: {str(e)}"

            provider_block = f"""
              provider "azurerm" {{
              features {{}}
              subscription_id = "Enter your credentials here."
              client_id       = "{CLIENT_ID}"
              client_secret   = "{CLIENT_SECRET}"
              tenant_id       = "{TENANT_ID}"
            }}"""
            terraform_code = provider_block + "\n\n" + terraform_code

        with open('main.tf', 'w', encoding='utf-8') as f:
            f.write(terraform_code)


        # Create output directory
        output_dir = r"C:\Users\riya.achkarpohre\Desktop\AI\test7\terraform_output"
        os.makedirs(output_dir, exist_ok=True)

        # Define output paths
        paths = {
            "main.tf": os.path.join(output_dir, "Main.tf"),
            "vm.tf": os.path.join(output_dir, "VM.tf"),
            "subnet.tf": os.path.join(output_dir, "Subnet.tf"),
            "vpc.tf": os.path.join(output_dir, "VPC.tf"),
            "vars.tf": os.path.join(output_dir, "Vars.tf"),
            "terraform.tfvars": os.path.join(output_dir, "Terraform.tfvars"),
            "kubernetes_cluster.tf": os.path.join(output_dir, "kubernetes_cluster.tf")
        }

        # Split response using markdown headers
        sections = re.split(r'##\s*(.*?)\.tf:\s*\n+```(?:terraform)?\n', terraform_code)

        # sections = ['', 'Main', '<code>', 'VM', '<code>', ...]
        for i in range(1, len(sections), 2):
            filename = sections[i].strip().lower() + '.tf'
            code_block = sections[i + 1].strip()

            # Remove closing backticks if present
            code_block = re.sub(r'```$', '', code_block)

            # Save to file if path is defined
            if filename in paths:
                with open(paths[filename], 'w', encoding='utf-8') as f:
                    f.write(code_block)
                    print(f"\n--- Written: {filename} ---")
                    print(code_block)
            else:
                print(f"\n--- Skipped unknown file: {filename} ---")

        return render_template_string(f"""
        <html>
        <head><title>Terraform Generator</title></head>
        <body>
            <form method="post">
                <center>
                    <label>Enter your query:</label><br>
                    <textarea name="query" rows="6" cols="80" placeholder="Describe your infrastructure requirement here..."></textarea><br><br>
                    <input type="submit" value="Generate Terraform">
                </center>
            </form>
            <hr>
            <h2>Generated Terraform Code:</h2>
            <pre>{terraform_code}</pre>
            <h2>Enter values for the required variables:</h2>
            <h2>Authentication Status:</h2>
            <pre>Status: {auth_status['status']}\n{auth_status['details']}</pre>
        </body>
        </html>
        """)

    # Initial GET request
    return render_template_string('''
    <html>
    <head><title>Terraform Generator</title></head>
    <body>
        <form method="post">
            <center>
                <label>Enter your query:</label><br>
                <textarea name="query" rows="6" cols="80" placeholder="Describe your infrastructure requirement here..."></textarea><br><br>
                <input type="submit" value="Generate Terraform">
            </center>
        </form>
    </body>
    </html>
    ''')

authenticate_with_azure()
@app.route('/authenticate', methods=['POST'])
def authenticate():
    authenticate_with_azure()
    return jsonify(auth_status)

if __name__ == '__main__':
    app.run(debug=True)

Open Visual Studio, create a new file named file.py, and paste the code into it. Then, open the terminal and run the script by typing:

python file.py

Flask Development Server

Out1

Code Structure Explanation

  • Azure Authentication
    • The app uses the Azure CLI (az.cmd) via Python’s subprocess.run() to authenticate with Azure using a service principal. This ensures secure access to Azure resources before generating Terraform code.
  • User Query Handling
    • When a user submits a query through the web form, it is captured using:
user_query = request.form.get('query', '')
  • Prompt Construction
    • The query is appended to a base prompt that instructs CodeGemma to generate modular Terraform code using best practices. This prompt includes instructions to split the code into files, such as main.tf, vm.tf, subnet.tf, etc.
  • Code Generation via CodeGemma
    • The prompt is sent to the CodeGemma:7b model using:
response_cleaned = generate(model='codegemma:7b', prompt=full_prompt)
  • Saving the Full Response
    • The entire generated Terraform code is first saved to a main.tf file as a backup.
  • Output Directory Setup
    • A specific output directory is created using os.makedirs() to store the split .tf files:
output_dir = r"C:\Users\riya.achkarpohre\Desktop\AI\test7\terraform_output"
  • File Path Mapping
    • A dictionary maps expected filenames (such as main.tf and vm.tf) to their respective output paths. This ensures each section of the generated code is saved correctly.
  • Code Splitting Logic
    • The response is split using a regex-based approach, based on markdown headers like ## main.tf: followed by Terraform code blocks. This helps isolate each module.
  • Conditional File Writing
    • For each split section, the code checks if the filename exists in the predefined path dictionary:
      • If defined, the code block is written to the corresponding file.
      • If not defined, the section is skipped and logged as  “unknown file”.
  • Web Output Rendering
    • The generated code and authentication status are displayed on the webpage using render_template_string().

Terminal

Term1

The Power of AI in Infrastructure Automation

This project demonstrates how combining AI models, such as CodeGemma, with simple tools like Flask and Terraform can revolutionize the way we approach cloud infrastructure provisioning. By allowing developers to describe their infrastructure in natural language and instantly receive clean, modular Terraform code, we eliminate the need for repetitive manual scripting and reduce the chances of human error.

Running CodeGemma locally via Ollama ensures:

  • Full control over data
  • Zero cost for code generation
  • Fast and private execution
  • Seamless integration with existing workflows

The use of Azure CLI authentication adds a layer of real-world applicability, making the generated code deployable in enterprise environments.

Whether you’re a cloud engineer, DevOps practitioner, or technical consultant, this tool empowers you to move faster, prototype smarter, and deploy infrastructure with confidence.

As AI continues to evolve, tools like this will become essential in bridging the gap between human intent and machine execution, making infrastructure-as-code not only powerful but also intuitive.

]]>
https://blogs.perficient.com/2025/09/25/terraform-code-generator-using-ollama-and-codegemma/feed/ 3 387185
A Comprehensive Guide to Azure Firewall https://blogs.perficient.com/2025/06/03/a-comprehensive-guide-to-azure-firewall/ https://blogs.perficient.com/2025/06/03/a-comprehensive-guide-to-azure-firewall/#respond Tue, 03 Jun 2025 10:09:38 +0000 https://blogs.perficient.com/?p=380960

Azure Firewall, a managed, cloud-based network security service, is an essential component of Azure’s security offerings. It comes in three different versions – Basic, Standard, and Premium – each designed to cater to a wide range of customer use cases and preferences. This blog post will provide a comprehensive comparison of these versions, discuss best practices for their use, and delve into their application in hub-spoke and Azure Virtual WAN with Secure Hub architectures.

What is Azure Firewall?

Azure Firewall is a cloud-native, intelligent network firewall security service designed to protect your Azure cloud workloads. It offers top-tier threat protection and is fully stateful, meaning it can track the state of network connections and make decisions based on the context of the traffic.

Key Features of Azure Firewall

  • High Availability: Built-in high availability ensures that your firewall remains operational at all times.
  • Scalability: Unlimited cloud scalability to handle varying workloads.
  • Traffic Inspection: Inspects both east-west (within the same network) and north-south (between different networks) traffic.
  • Threat Intelligence: Uses advanced threat intelligence to block malicious IP addresses and domains.
  • Centralized Management: Allows you to centrally create, enforce, and log application and network connectivity policies across multiple subscriptions and virtual networks.
  • Compliance: Helps organizations meet regulatory and compliance requirements by providing detailed logging and monitoring capabilities.
  • Cost Efficiency: By deploying Azure Firewall in a central virtual network, you can achieve cost savings by avoiding the need to deploy multiple firewalls across different networks.

    Firewall Architecture

Why Azure Firewall is Essential

Enhanced Security

In today’s digital landscape, cyber threats are becoming increasingly sophisticated. Organizations need robust security measures to protect their data and applications. Azure Firewall provides enhanced security by inspecting both inbound and outbound traffic, using advanced threat intelligence to block malicious IP addresses and domains. This ensures that your network is protected against a wide range of threats, including malware, phishing, and other cyberattacks.

Centralized Management

Managing network security across multiple subscriptions and virtual networks can be a complex and time-consuming process. Azure Firewall simplifies this process by allowing you to centrally create, enforce, and log application and network connectivity policies. This centralized management ensures consistent security policies across your organization, making it easier to maintain and monitor your network security.

Scalability

Businesses often experience fluctuating traffic volumes, which can strain network resources. Azure Firewall offers unlimited cloud scalability, meaning it can handle varying workloads without compromising performance. This scalability is crucial for businesses that need to accommodate peak traffic periods and ensure continuous protection.

High Availability

Downtime can be costly for businesses, both in terms of lost revenue and damage to reputation. Azure Firewall’s built-in high availability ensures that your firewall is always operational, minimizing downtime and maintaining continuous protection

Compliance

Many industries have strict data protection regulations that organizations must comply with. Azure Firewall helps organizations meet these regulatory and compliance requirements by providing detailed logging and monitoring capabilities. This is particularly vital for industries such as finance, healthcare, and government, where data security is of paramount importance.

Cost Efficiency

Deploying multiple firewalls across different networks can be expensive. By deploying Azure Firewall in a central virtual network, organizations can achieve cost savings. This centralized approach reduces the need for multiple firewalls, lowering overall costs while maintaining robust security.

Azure Firewall Versions: Basic, Standard, and Premium

Azure Firewall Basic

Azure Firewall Basic is recommended for small to medium-sized business (SMB) customers with throughput needs of up to 250 Mbps. It’s a cost-effective solution for businesses that require fundamental network protection.

Azure Firewall Standard

Azure Firewall Standard is recommended for customers looking for a Layer 3–Layer 7 firewall and need autoscaling to handle peak traffic periods of up to 30 Gbps. It supports enterprise features like threat intelligence, DNS proxy, custom DNS, and web categories.

Azure Firewall Premium

Azure Firewall Premium is recommended for securing highly sensitive applications, such as those involved in payment processing. It supports advanced threat protection capabilities like malware and TLS inspection. Azure Firewall Premium utilizes advanced hardware and features a higher-performing underlying engine, making it ideal for handling heavier workloads and higher traffic volumes.

Azure Firewall Features Comparison

Here’s a comparison of the features available in each version of Azure Firewall:

Feature Basic Standard Premium
Stateful firewall (Layer 3/Layer 4) Yes Yes Yes
Application FQDN filtering Yes Yes Yes
Network traffic filtering rules Yes Yes Yes
Outbound SNAT support Yes Yes Yes
Threat intelligence-based filtering No Yes Yes
Web categories No Yes Yes
Intrusion Detection and Prevention System (IDPS) No No Yes
TLS Inspection No No Yes
URL Filtering No No Yes

Azure Firewall Architecture

Azure Firewall plays a crucial role in the hub-spoke network architecture pattern in Azure. The hub is a virtual network (VNet) in Azure that acts as a central point of connectivity to your on-premises network. The spokes are VNets that peer with the hub and can be used to isolate workloads. Azure Firewall secures and inspects network traffic, but it also routes traffic between VNets .

A secured hub is an Azure Virtual WAN Hub with associated security and routing policies configured by Azure Firewall Manager. Use secured virtual hubs to easily create hub-and-spoke and transitive architectures with native security services for traffic governance and protection.

Spoke Spoke Routing

How Azure Firewall Works

Azure Firewall operates by using rules and rule collections to manage and filter network traffic. Here are some key concepts:

  • Rule Collections: A set of rules with the same order and priority. Rule collections are executed in priority order.
  • Application Rules: Configure fully qualified domain names (FQDNs) that can be accessed from a virtual network.
  • Network Rules: Configure rules with source addresses, protocols, destination ports, and destination addresses.
  • NAT Rules: Configure DNAT rules to allow incoming Internet or intranet connections.

Azure Firewall integrates with Azure Monitor for viewing and analyzing logs. Logs can be sent to Log Analytics, Azure Storage, or Event Hubs and analyzed using tools like Log Analytics, Excel, or Power BI.

Steps to Deploy and Configure Azure Firewall

Step 1: Set Up the Network

Create a Resource Group
Sign in to the Azure portal:

  • Navigate to Azure Portal.
    • Use your credentials to sign in.
  • Create a Resource Group:
    • On the Azure portal menu, select Resource groups or search for and select Resource groups from any page.
    • Click Create.
    • Enter the following values:
      • Subscription: Select your Azure subscription.
      • Resource group: Enter Test-FW-RG.
      • Region: Select a region (ensure all resources you create are in the same region).
    • Click Review + create and then Create.
  • Create a Virtual Network (VNet)
    • On the Azure portal menu or from the Home page, select Create a resource.
    • Select Networking and search for Virtual network, then click Create.
    • Enter the following values:
      • Subscription: Select your Azure subscription.
      • Resource group: Select Test-FW-RG.
      • Name: Enter Test-FW-VN.
      • Region: Select the same region as the resource group.
  • Click Next: IP Addresses.
    • Configure IP Addresses:
    • Set the Address space to 10.0.0.0/16.
      • Create two subnets:
      • AzureFirewallSubnet: Enter 10.0.1.0/26.
      • Workload-SN: Enter 10.0.2.0/24.
  • Click Next: Security.
    • Configure Security Settings:
    • Leave the default settings for Security.
  • Click Next: Tags.
    • Add Tags (Optional):
    • Tags are useful for organizing resources. Add any tags if needed.
  • Click Next: Review + create.
    • Review and Create:
    • Review the settings and click Create.

 

Vnet

Step 2: Deploy the Firewall

Create the Firewall:

  • On the Azure portal menu, select Create a resource.
    • Search for Firewall and select Create.
    • Enter the following values:
      • Subscription: Select your Azure subscription.
      • Resource group: Select Test-FW-RG.
      • Name: Enter Test-FW.
      • Region: Select the same region as the resource group.
      • Virtual network: Select Test-FW-VN.
      • Subnet: Select AzureFirewallSubnet.
  • Click Next: IP Addresses.
    • Configure IP Addresses:
    • Assign a Public IP Address:
      • Click Add new.
      • Enter a name for the public IP address, e.g., Test-FW-PIP.Click OK.
  • Click Next: Tags.
    • Add Tags (Optional):
    • Add any tags if needed.
  • Click Next: Review + create.
    • Review and Create:
    • Review the settings and click Create.

Deploy Firewall

Step 3: Configure Firewall Rules

Create Application Rules

  • Navigate to the Firewall:
    • Go to the Resource groups and select Test-FW-RG.
    • Click on Test-FW.
  • Configure Application Rules:
    • Select Rules from the left-hand menu.
    • Click Add application rule collection.
      • Enter the following values:Name: Enter AppRuleCollection.
      • Priority: Enter 100.
      • Action: Select Allow.
      • Rules: Click Add rule.
      • Name: Enter AllowGoogle.
      • Source IP addresses: Enter *.
      • Protocol: Select http, https.
      • Target FQDNs: Enter www.google.com.
    • Click Add.
  • Create Network Rules
  • Configure Network Rules:
    • Select Rules from the left-hand menu.
    • Click Add network rule collection.
    • Enter the following values:
      • Name: Enter NetRuleCollection.
      • Priority: Enter 200.
      • Action: Select Allow.
      • Rules: Click Add rule.
      • Name: Enter AllowDNS.
      • Source IP addresses: Enter *.
      • Protocol: Select UDP.
      • Destination IP addresses: Enter 8.8.8.8, 8.8.4.4.Destination ports: Enter 53.
    • Click Add.
  • Create NAT Rules
    • Configure NAT Rules:
      • Select Rules from the left-hand menu.
      • Click Add NAT rule collection.
      • Enter the following values:
        • Name: Enter NATRuleCollection.
        • Priority: Enter 300.
        • Action: Select DNAT.
        • Rules: Click Add rule.
        • Name: Enter AllowRDP.
        • Source IP addresses: Enter *.Protocol: Select TCP.
        • Destination IP addresses: Enter the public IP address of the firewall.
        • Destination ports: Enter 3389.
        • Translated address: Enter the private IP address of the workload server.
        • Translated port: Enter 3389.
      • Click Add.

Rdp

Step 4: Test the Firewall

  • Deploy a Test VM:
    • Create a virtual machine in the Workload-SN subnet.
    • Ensure it has a private IP address within the 10.0.2.0/24 range.
  • Test Connectivity:
    • Attempt to access www.google.com from the test VM to verify the application rule.
    • Attempt to resolve DNS queries to 8.8.8.8 and 8.8.4.4 to verify the network rule.
    • Attempt to connect via RDP to the test VM using the public IP address of the firewall to verify the NAT rule.
  • Monitoring and Managing Azure Firewall
    • Integrate with Azure Monitor:
      • Navigate to the firewall resource.
        • Select Logs from the left-hand menu.
        • Configure diagnostic settings to send logs to Azure Monitor, Log Analytics, or Event Hubs.
  • Analyze Logs:
    • Use Azure Monitor to view and analyze firewall logs.
    • Create alerts and dashboards to monitor firewall activity and performance.

Test Firewall

Best Practices for Azure Firewall

To maximize the performance of your Azure Firewall, it’s important to follow best practices. Here are some recommendations:

  • Optimize Rule Configuration and Processing: Organize rules using firewall policy into Rule Collection Groups and Rule Collections, prioritizing them based on their frequency of use.
  • Use or Migrate to Azure Firewall Premium: Azure Firewall Premium offers a higher-performing underlying engine and includes built-in accelerated networking software.
  • Add Multiple Public IP Addresses to the Firewall: Consider adding multiple public IP addresses (PIPs) to your firewall to prevent SNAT port exhaustion.
]]>
https://blogs.perficient.com/2025/06/03/a-comprehensive-guide-to-azure-firewall/feed/ 0 380960