• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

?️ Secure, Lint, and Validate Your Terraform Like a Pro

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
“It works, ship it!” — a phrase we’ve all heard. But when it comes to Infrastructure as Code (IaC), that mindset can lead to serious security and compliance issues.
? Introduction: Terraform Isn’t Just Code — It’s Infrastructure


In today’s cloud-native environments, Infrastructure as Code (IaC) has become the backbone of scalable, consistent deployments. But with great power comes great responsibility.

A single misconfigured security group or a public S3 bucket can:


  • Expose sensitive data


  • Introduce downtime


  • Violate compliance standards


  • Lead to audit failures or breaches
? Terraform = Real Code + Real Risk


As DevOps, SRE, and Platform Engineers, we know Terraform is code. But it’s not just code — it builds cloud infrastructure.

? One security group open to the world?
? One IAM policy with *:*?
? One public S3 bucket?

⚠ Real-World Pitfalls You Want to Avoid

? Scenario 1: “Oops, S3 Bucket Left Public”


resource "aws_s3_bucket" "data" {
bucket = "my-sensitive-logs"
acl = "public-read"
}

  • Risk: Unencrypted, public bucket


  • Tool that catches it: tfsec, checkov
? Scenario 2: Overly Permissive Security Group


resource "aws_security_group" "ssh_access" {
ingress {
from_port = 22
to_port = 22
cidr_blocks = ["0.0.0.0/0"]
}
}

  • Risk: Open SSH to the entire internet


  • Tool that flags it: tfsec, checkov
? Scenario 3: IAM Wildcard Permissions


resource "aws_iam_policy" "admin_policy" {
policy = jsonencode({
Version = "2012-10-17",
Statement = [{
Action = "*",
Effect = "Allow",
Resource = "*"
}]
})
}

  • Risk: Full access, violates least privilege


  • Tool that blocks it: checkov with CIS/NIST rules

➡ That’s how breaches happen.
➡ That’s why I never deploy Terraform code without this golden trio:

✅ I never merge a PR without these:

? tflint – Lint for quality
? tfsec – Security misconfig scan
?️ checkov – Compliance & governance
Let’s dive deep into what they are, how they help, and how to automate them in CI/CD ?

✅ Tool 1: tflint — The Terraform Linter


? What is tflint?


tflint is a static analysis linter for Terraform that catches bugs, anti-patterns, and style violations before you run terraform plan or apply.

? Why it Matters


  • Finds unused variables, typos, and invalid resource attributes


  • Helps you write clean, readable, and consistent Terraform code


  • Enforces provider-specific best practices (AWS, Azure, GCP)
? Common Issues Caught by tflint:


  • Using deprecated or invalid arguments


  • Misspelled variable or resource names


  • Misconfigured provider blocks


  • Poorly structured modules

tflint --init # Downloads plugins
tflint # Runs all checks
? Real-World Example:


Imagine a module with a typo like vpc_securty_group_ids. Terraform will silently skip it unless caught. tflint prevents these bugs early.

? More Info:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



? Tool 2: tfsec — Secure Terraform from the Start

? What is tfsec?


tfsec performs static analysis on your Terraform code to detect security vulnerabilities and misconfigurations.

It analyzes HCL files for patterns that can lead to:


  • Data leaks


  • Unintended access


  • Infrastructure exposure
? Example Findings:

IssueSeverityExample
S3 Bucket ACL set to publicHigh"acl" = "public-read"
SG open to the world on any portCritical"cidr_blocks = 0.0.0.0/0"
EBS volume not encryptedHighencrypted = false
Secrets in user_dataMediumInline secrets in EC2 config
? Command to Run:


tfsec .

You create a quick EC2 setup:


resource "aws_security_group" "example" {
ingress {
from_port = 22
to_port = 22
cidr_blocks = ["0.0.0.0/0"] # Dangerous
}
}

tfsec will immediately flag this as a high-risk issue.

?️ Tool 3: checkov — Policy-as-Code & Compliance Gate

? What is checkov?


checkov validates Terraform against security benchmarks and industry standards.

It enforces rules from:


  • ? CIS AWS Foundations Benchmark


  • ?️ NIST 800-53


  • ? SOC 2, GDPR, HIPAA


  • ? Custom YAML/Python-based policies
? Output includes:


  • Passed checks


  • Failed checks (with severity)


  • Skipped (manually ignored) checks


  • Suggestions and remediation tips
? Command to Run:


checkov -d .
? Sample Check:


resource "aws_s3_bucket" "public_logs" {
bucket = "my-bucket"
acl = "public-read" # checkov will flag this!
}
? Bonus:


  • Shows passed ✅, failed ❌, skipped ⚠


  • Works with multiple IaC formats: Terraform, CloudFormation, K8s YAML
? GitHub Actions Workflow – Plug & Play


Add to .github/workflows/terraform-checks.yml:


name: Terraform Static Checks

on: [push, pull_request]

jobs:
terraform-lint-secure:
runs-on: ubuntu-latest

steps:
- name: Checkout Code
uses: actions/checkout@v3

- name: Setup Terraform
uses: hashicorp/setup-terraform@v2

- name: Install Security Tools
run: |
curl -s

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

| bash
curl -s

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

| bash
pip install checkov

- name: Run tflint
run: |
tflint --init
tflint

- name: Run tfsec
run: tfsec .

- name: Run checkov
run: checkov -d .

? You can make these blocking steps by using GitHub's branch protection rules!

✅ Optional: Add continue-on-error: false to fail the PR if checks don’t pass.

? Example of tfsec scanning output:


Run aquasecurity/tfsec-action@v1.0.0
/usr/bin/docker run --name febf3299d148674848491e8a8d0b99f8e1aeba_ab881b --label febf32 --workdir /github/workspace --rm -e "AWS_ACCESS_KEY_ID" -e "AWS_SECRET_ACCESS_KEY" -e "TERRAFORM_CLI_PATH" -e "INPUT_WORKING_DIRECTORY" -e "INPUT_VERSION" -e "INPUT_FORMAT" -e "INPUT_ADDITIONAL_ARGS" -e "INPUT_SOFT_FAIL" -e "HOME" -e "GITHUB_JOB" -e "GITHUB_REF" -e "GITHUB_SHA" -e "GITHUB_REPOSITORY" -e "GITHUB_REPOSITORY_OWNER" -e "GITHUB_REPOSITORY_OWNER_ID" -e "GITHUB_RUN_ID" -e "GITHUB_RUN_NUMBER" -e "GITHUB_RETENTION_DAYS" -e "GITHUB_RUN_ATTEMPT" -e "GITHUB_ACTOR_ID" -e "GITHUB_ACTOR" -e "GITHUB_WORKFLOW" -e "GITHUB_HEAD_REF" -e "GITHUB_BASE_REF" -e "GITHUB_EVENT_NAME" -e "GITHUB_SERVER_URL" -e "GITHUB_API_URL" -e "GITHUB_GRAPHQL_URL" -e "GITHUB_REF_NAME" -e "GITHUB_REF_PROTECTED" -e "GITHUB_REF_TYPE" -e "GITHUB_WORKFLOW_REF" -e "GITHUB_WORKFLOW_SHA" -e "GITHUB_REPOSITORY_ID" -e "GITHUB_TRIGGERING_ACTOR" -e "GITHUB_WORKSPACE" -e "GITHUB_ACTION" -e "GITHUB_EVENT_PATH" -e "GITHUB_ACTION_REPOSITORY" -e "GITHUB_ACTION_REF" -e "GITHUB_PATH" -e "GITHUB_ENV" -e "GITHUB_STEP_SUMMARY" -e "GITHUB_STATE" -e "GITHUB_OUTPUT" -e "RUNNER_OS" -e "RUNNER_ARCH" -e "RUNNER_NAME" -e "RUNNER_ENVIRONMENT" -e "RUNNER_TOOL_CACHE" -e "RUNNER_TEMP" -e "RUNNER_WORKSPACE" -e "ACTIONS_RUNTIME_URL" -e "ACTIONS_RUNTIME_TOKEN" -e "ACTIONS_CACHE_URL" -e "ACTIONS_RESULTS_URL" -e GITHUB_ACTIONS=true -e CI=true -v "/var/run/docker.sock":"/var/run/docker.sock" -v "/home/runner/work/_temp/_github_home":"/github/home" -v "/home/runner/work/_temp/_github_workflow":"/github/workflow" -v "/home/runner/work/_temp/_runner_file_commands":"/github/file_commands" -v "/home/runner/work/tictocgame-app/tictocgame-app":"/github/workspace" febf32:99d148674848491e8a8d0b99f8e1aeba
+ TFSEC_VERSION=latest
+ '[' latest '!=' latest ']'
++ wget -q

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

-O -
++ grep -o -E 'https://.+?tfsec-linux-amd64'
++ head -n1
+ wget -O - -q

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


+ install tfsec /usr/local/bin/
+ '[' -n /github/workspace ']'
+ cd /github/workspace
+ '[' -n '' ']'
+ '[' -n '' ']'
+ FORMAT=default
+ tfsec --format=default .

======================================================
tfsec is joining the Trivy family

tfsec will continue to remain available
for the time being, although our engineering
attention will be directed at Trivy going forward.

You can read more here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

======================================================
timings
──────────────────────────────────────────
disk i/o 14.317µs
parsing 154.272µs
adaptation 81.464µs
checks 2.895977ms
total 3.14603ms

counts
──────────────────────────────────────────
modules downloaded 0
modules processed 1
blocks processed 3
files read 1

results
──────────────────────────────────────────
passed 1
ignored 0
critical 0
high 0
medium 0
low 0


No problems detected!
? Sample main.tf to Try Locally


provider "aws" {
region = "us-east-1"
}

resource "aws_s3_bucket" "my_bucket" {
bucket = "public-test-bucket"
acl = "public-read"
}

resource "aws_security_group" "bad_sg" {
ingress {
from_port = 22
to_port = 22
cidr_blocks = ["0.0.0.0/0"]
}
}

Run all tools:


tflint
tfsec .
checkov -d .
? Why This Workflow Matters - 3 Layers of Protection

ToolRoleKey Value
✅ tflintLinting & Best PracticesClean, typo-free code
? tfsecSecurity Vulnerability ScansDetects open/public resources
? checkovCompliance & Policy ChecksEnforces standards like CIS/NIST

Together, they:

✅ Prevent misconfigurations
? Shift security left
? Ensure compliance by design


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



? Real-World Wins After Adding These Tools


✔ Fewer post-merge hotfixes
✔ Better security posture out-of-the-box
✔ Faster reviews: Devs catch issues before PR
✔ Happier security & compliance teams
✔ Infrastructure that’s ready for audit

? Closing Thoughts


Every terraform plan should feel like a final step, not a gamble.

Start treating your infrastructure as real production code — because it is.

? Use tflint, tfsec, and checkov in every PR.

? How do you secure your Terraform deployments?Let’s share tips in the comments ?


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу