코드에도 악취가 난다. 코드 스멜이다. 중복 코드, 너무 긴 함수, 의미 없는 변수명—코드 스멜은 버그는 아니지만 버그의 온상지다. 인프라 코드에도 마찬가지다. Terraform 코드에서 하드코딩된 값, 중복 리소스, 과도한 모듈 의존성은 유지보수를 어렵게 만든다. 그런데 이걸 사람이 일일이 찾기는 쉽지 않다. 정적 분석 도구는 있지만, 맥락을 이해하지 못하는 한계가 있다.
Annual International Computer Software and Applications Conference(COMPSAC)에 발표된 연구는 대형 언어 모델(LLM)을 활용해 Terraform 코드의 코드 스멜을 탐지하는 방법을 제시한다. LLM이 코드의 맥락을 이해하고, 규칙 기반 도구가 놓치는 패턴을 찾아낼 수 있다는 가설에서 출발했다.
연구는 Terraform 코드에서 흔히 발생하는 코드 스멜 유형을 먼저 분류했다—하드코딩된 값, 중복 리소스, 과도한 변수, 누락된 태그, 불필요한 의존성 등. 이 스멜들을 LLM(GPT-4, CodeLlama 등)이 탐지하는 능력을 규칙 기반 도구(tfsec, checkov)와 비교 평가했다.
핵심 결과를 보면, LLM은 규칙 기반 도구가 탐지하지 못하는 맥락적 코드 스멜을 발견하는 데 효과적이었다. 예를 들어, 하드코딩된 포트 번호가 의도적인지 아닌지, 중복 리소스가 필연적인지 아닌지를 맥락에 따라 판단했다. tfsec과 checkov는 명확한 보안 규칙 위반은 잘 잡았지만, 설계 의도를 이해하지 못해 오탐이 발생하기도 했다. LLM의 약점은 탐지 결과의 일관성이었다—같은 코드를 두 번 질문하면 다른 결과를 낼 수 있어, 자동화된 파이프라인에 통합하려면 후처리가 필요했다. LLM과 정적 분석을 결합한 하이브리드 접근이 가장 높은 정밀도와 재현율을 달성했다.
이 연구가 의미 있는 이유는 인프라 코드의 품질 관리에 LLM이라는 새로운 도구를 도입한다는 것이다. Terraform 코드는 애플리케이션 코드만큼 테스트와 리뷰가 철저하지 않은 경우가 많다. LLM 기반 스멜 탐지는 코드 리뷰의 보조 도구로 활용될 수 있다.
한계로는 LLM 실행 비용과 지연 시간이 정적 분석보다 높고, 대규모 코드베이스에서는 토큰 제한으로 인해 전체 파일을 한 번에 분석하기 어렵다는 점이 있다. 또한 LLM의 환각—존재하지 않는 스멜을 보고하는 경우—도 완전히 해결되지 않았다.
Terraform 코드 품질을 높이려면 정적 분석 도구(tfsec, checkov)를 먼저 CI 파이프라인에 통합하라. 그 위에 LLM 기반 탐지를 보조 도구로 추가하는 것이 현실적이다. PR 리뷰 시 LLM이 코드 스멜을 자동으로 코멘트하는 워크플로우를 구성하면 코드 품질 향상 효과를 기대할 수 있다.
📖 *Harnessing the Power of LLMs for Code Smell Detection in Terraform Infrastructure as Code* |
논문 원문
※ 이 기사는 학술 논문을 바탕으로 작성되었습니다. 실제 적용 시 환경에 따라 다를 수 있으니 전문가와 상담하세요.
Code can also emit a bad odor. This is known as a code smell. Duplicated code, overly long functions, meaningless variable names—code smells are not bugs themselves, but they are breeding grounds for them. The same applies to infrastructure code. In Terraform code, hardcoded values, duplicated resources, and excessive module dependencies make maintenance difficult. However, it is not easy for humans to find these manually. While static analysis tools exist, they have limitations in understanding context.
A study presented at the Annual International Computer Software and Applications Conference (COMPSAC) proposes a method for detecting code smells in Terraform code using Large Language Models (LLMs). It started from the hypothesis that LLMs can understand the context of the code and find patterns that rule-based tools miss.
The research first categorized the types of code smells commonly found in Terraform code—hardcoded values, duplicated resources, excessive variables, missing tags, and unnecessary dependencies. It then comparatively evaluated the ability of LLMs (such as GPT-4 and CodeLlama) to detect these smells against rule-based tools (tfsec, checkov).
Looking at the key results, LLMs were effective at discovering contextual code smells that rule-based tools could not detect. For example, they judged based on context whether a hardcoded port number was intentional or not, or whether a duplicated resource was inevitable. While tfsec and checkov were good at catching clear security rule violations, they sometimes produced false positives because they could not understand the design intent. The weakness of LLMs was the consistency of their detection results—asking the same code twice could yield different results, requiring post-processing to integrate them into an automated pipeline. A hybrid approach combining LLMs and static analysis achieved the highest precision and recall.
The significance of this study lies in introducing a new tool, the LLM, for quality management of infrastructure code. Terraform code is often not tested and reviewed as thoroughly as application code. LLM-based smell detection can be utilized as an auxiliary tool for code reviews.
Limitations include the fact that LLM execution costs and latency are higher than static analysis, and token limits make it difficult to analyze entire files at once in large-scale codebases. Additionally, LLM hallucinations—reporting non-existent smells—have not been completely resolved.
To improve Terraform code quality, first integrate static analysis tools (tfsec, checkov) into your CI pipeline. It is practical to add LLM-based detection as an auxiliary tool on top of that. Configuring a workflow where the LLM automatically comments on code smells during PR reviews can be expected to improve code quality.
📖 *Harnessing the Power of LLMs for Code Smell Detection in Terraform Infrastructure as Code* | Original Paper
※ This article is based on an academic paper. Actual application may vary depending on the environment, so please consult with an expert.