DEV Community

Cover image for Building an AI-Powered Terraform Assistant
selvakumar palanisamy
selvakumar palanisamy

Posted on

Building an AI-Powered Terraform Assistant

Infrastructure as Code (IaC) has revolutionized how we manage cloud resources, and Terraform is at the forefront of this shift. However, writing, validating, and debugging HCL (HashiCorp Configuration Language) can still be a time-consuming process. What if you could simply describe your desired infrastructure in plain English and have an AI generate, validate, and even correct the code for you?
This post breaks down a powerful Streamlit application that does exactly that. This "Terraform Code Assistant" leverages the OpenAI API to create a seamless workflow for generating IaC for AWS, Azure, or Google Cloud.

Core Architecture: How It Works
The application is built with a clear, three-step workflow in mind: Generate, Validate, and Correct. It combines the user-friendly interface of Streamlit with the power of OpenAI's language models and the reliability of the Terraform CLI.

Step 1: Setting Up the Environment Automatically

Before we can do anything with Terraform, we need to have the Terraform executable available. In a local environment, this is a simple download. But for a web app deployed on a platform like Streamlit Community Cloud, we need a more robust solution.
The get_terraform_executable function handles this automatically.

Platform Detection: It first checks the user's operating system (Linux, Windows, etc.) and architecture (amd64, arm64) to determine the correct Terraform version to download.

Downloading and Unzipping: It fetches the appropriate zip file from HashiCorp's official releases page, extracts it, and makes the terraform binary executable.

Caching for Efficiency: The @st.cache_resource decorator is crucial here. It ensures that Terraform is downloaded only once when the app first starts. For all subsequent user sessions, the cached executable is used, making the app much faster and more efficient.

Step 2: The User Interface and Configuration

A good tool needs an intuitive interface. The app is divided into a sidebar for configuration and a main area for interaction.
The Sidebar

The sidebar contains all the necessary setup options:

1. Cloud Provider Selection:

A simple dropdown lets the user choose between AWS, Azure, and Google Cloud. This choice is passed to the AI to ensure it generates the correct provider-specific code.

2. API Key Management:

The app securely loads the OPENAI_API_KEY from Streamlit's secrets management. It provides clear instructions for the user if the key is not found, ensuring a smooth setup process.

3. Instructions:

A "How to use" section guides the user through the app's workflow.

Step 3: The AI-Powered Workflow in Action

This is where the magic happens. The three main buttons—Generate, Validate, and Correct—drive the entire process.

Generate with AI
When a user describes their infrastructure (e.g., "An S3 bucket for logging and a t3.small EC2 instance") and clicks this button, the app:

  1. Constructs a detailed system prompt for the OpenAI API. This prompt instructs the AI to act as a Terraform expert for the selected cloud provider and to return only a clean block of HCL code.
  2. Sends the user's request to the gpt-4o model.
  3. Parses the AI's response to extract the HCL code block and displays it in the code editor.

Validate

Once the code is generated, the user can validate it. Clicking this button triggers a background process:

  1. A temporary directory is created, and the generated Terraform code is saved to a main.tf file.
  2. The app runs terraform init to download the necessary provider plugins.
  3. It then runs terraform validate to check the syntax and configuration.
  4. The output (success or error) is captured and displayed in the results area.

Correct with AI

If the validation fails, the user doesn't have to debug the code manually. The Correct with AI button becomes active, and clicking it will:

  1. Create a new prompt for the AI that includes both the incorrect code and the specific validation error message from Terraform.
  2. Ask the AI to act as a code correction expert and fix the error.
  3. The corrected code is then returned and placed back into the editor, ready for re-validation.

This Terraform Code Assistant is a powerful example of how AI can be integrated into DevOps workflows to boost productivity and lower the barrier to entry for managing cloud infrastructure. By combining a smart, automated setup, a clean user interface, and a powerful generate-validate-correct loop, this Streamlit app transforms a complex task into a simple, conversational experience.

Try this terraform code gen ai agent app

https://terraform-codegen-selvapal-poc.streamlit.app

Repo : https://github.com/selvakumarsai/terraformcodegen

Happy Terraforming!

Top comments (0)