Infracost
Infracost = ดู ค่าใช้จ่าย cloud ที่ Terraform จะสร้าง — ก่อน apply
ทำไมต้องใช้ Infracost?
Terraform plan แสดงว่า จะสร้างอะไร — แต่ไม่บอกว่า เสียเงินเท่าไหร่
ปัญหา:
- 😰 Apply prod แล้วเจอบิลใหญ่จาก instance ที่เผลอเลือกผิด
- 😰 ทีมไม่รู้ว่า change ใน PR เพิ่ม cost เท่าไหร่
- 😰 Optimize cost ทำได้ยาก ไม่มี visibility
→ Infracost = preview cost in PR
Install
# macOS
brew install infracost
# Linux
curl -fsSL https://raw.githubusercontent.com/infracost/infracost/master/scripts/install.sh | sh
# Verify
infracost --version
Get API Key (Free)
infracost auth login
→ เปิด browser, sign up ฟรี, key save ใน ~/.config/infracost/credentials.yml
Basic Usage
cd my-terraform-project
infracost breakdown --path .
Output:
Project: my-project
Name Monthly Qty Unit Monthly Cost
aws_instance.web
├─ Instance usage (Linux/UNIX, t3.large) 730 hours $60.74
├─ root_block_device
│ └─ Storage (general purpose SSD, gp2) 50 GB $5.00
└─ EBS optimization 730 hours $0.00
aws_db_instance.main
├─ Database instance (db.t3.medium, on-demand) 730 hours $52.56
├─ Database storage (general purpose SSD) 100 GB $11.50
└─ Storage IO - IOPS $0.00
OVERALL TOTAL $129.80
Compare Cost (Diff)
ดูว่า change ใน Terraform เพิ่ม/ลด cost เท่าไหร่:
# 1. Save baseline
infracost breakdown --path . --format json --out-file baseline.json
# 2. Make changes to .tf
# 3. Diff
infracost diff --path . --compare-to baseline.json
Output:
~ aws_instance.web
+$45.81/mo (was $60.74, now $106.55)
~ Instance usage (Linux/UNIX, t3.xlarge)
+$45.81/mo
Comment in PR
infracost comment github \
--path infracost.json \
--pull-request 123 \
--repo myorg/myrepo \
--github-token $GITHUB_TOKEN
→ Comment ใน PR แสดง cost change
CI/CD Integration
GitHub Actions
.github/workflows/cost.yml
on:
pull_request:
paths: ["**.tf"]
jobs:
cost:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.base.ref }}
- name: Setup Infracost
uses: infracost/actions/setup@v3
with:
api-key: ${{ secrets.INFRACOST_API_KEY }}
- name: Generate baseline cost
run: |
infracost breakdown --path . \
--format json \
--out-file infracost-base.json
- uses: actions/checkout@v4
- name: Generate cost diff
run: |
infracost diff --path . \
--compare-to infracost-base.json \
--format json \
--out-file infracost.json
- name: Comment on PR
run: |
infracost comment github \
--path infracost.json \
--pull-request ${{ github.event.pull_request.number }} \
--repo ${{ github.repository }} \
--github-token ${{ secrets.GITHUB_TOKEN }} \
--behavior update
→ PR แสดง:
💰 Infracost Estimate
Project Cost change New cost
my-project +$45.81 (+35%) $174.61
Detailed:
~ aws_instance.web: t3.large → t3.xlarge (+$45.81/mo)
GitLab CI
.gitlab-ci.yml
infracost:
image: infracost/infracost:ci-latest
script:
- infracost breakdown --path . --format json --out-file /tmp/infracost.json
- infracost comment gitlab --path /tmp/infracost.json
--merge-request $CI_MERGE_REQUEST_IID
--gitlab-server-url $CI_SERVER_URL
--gitlab-token $GITLAB_TOKEN
--repo $CI_PROJECT_PATH
only:
- merge_requests
Configure Project
infracost.yml
version: 0.1
projects:
- path: dev
name: Development
usage_file: dev/infracost-usage.yml
- path: prod
name: Production
usage_file: prod/infracost-usage.yml
Usage-Based Costs
บาง resource (Lambda, S3, Data transfer) คิด cost ตาม usage, ไม่ใช่ provisioning
infracost-usage.yml
version: 0.1
resource_usage:
aws_lambda_function.api:
monthly_requests: 1000000 # 1M invocations
request_duration_ms: 200 # avg duration
aws_s3_bucket.uploads:
standard_storage_gb: 500 # 500 GB stored
standard_select_returned_gb: 100
standard_data_retrieval_gb: 50
monthly_get_requests: 100000
monthly_put_requests: 10000
aws_dynamodb_table.users:
monthly_write_request_units: 1000000
monthly_read_request_units: 5000000
storage_gb: 50
aws_data_transfer.this:
monthly_outbound_data_gb: 1000
infracost breakdown --path . --usage-file infracost-usage.yml
→ Cost estimate ที่แม่นยำกว่า
Cost Policies (Infracost Cloud)
ตั้ง policy เช่น "PR ห้ามเพิ่ม cost > $100/mo":
infracost.yml
version: 0.1
projects:
- path: .
policies:
- name: prevent-large-cost-increase
description: PR ห้ามเพิ่ม cost > $100/mo
rule: budget.cost.diff > 100
severity: high
→ PR จะ fail ถ้า cost เพิ่ม > $100
Cost Optimization Recommendations
Infracost Cloud (paid) แนะนำ:
- เปลี่ยน on-demand → reserved instances
- Right-size instance type
- Spot instances สำหรับ workload ที่ทน
- Storage class optimization
Multiple Projects
infracost breakdown --config-file infracost.yml
infracost.yml
version: 0.1
projects:
- path: dev
- path: staging
- path: prod
Output Formats
# Default (table)
infracost breakdown --path .
# JSON
infracost breakdown --path . --format json
# HTML report
infracost breakdown --path . --format html > report.html
# GitHub comment
infracost breakdown --path . --format github-comment
# Slack message
infracost breakdown --path . --format slack-message
Example: Slack Notification
infracost breakdown --path . --format slack-message > slack.json
curl -X POST $SLACK_WEBHOOK \
-H 'Content-Type: application/json' \
-d @slack.json
ตัวอย่าง: Optimization Workflow
# Current cost
$ infracost breakdown --path .
OVERALL TOTAL: $500/mo
# Edit main.tf — change instance types, enable savings plan, etc.
# New cost
$ infracost breakdown --path .
OVERALL TOTAL: $320/mo # 36% savings!
# Apply
$ terraform apply
Best Practices
✅ DO:
- Run Infracost ใน PR ทุก PR ที่แก้ infrastructure
- Set cost policy (block >$X increase)
- Track baseline cost monthly
- Use usage-based estimation สำหรับ Lambda/S3
- Comment cost diff ใน PR
❌ DON'T:
- ห้ามคิดว่า estimate = bill จริง (~ใกล้เคียง)
- ห้าม skip usage file สำหรับ cost-sensitive resources
- ห้าม approve PR ที่ cost เพิ่มเยอะโดยไม่ review
Limitations
- Estimate ไม่ใช่ exact (provider pricing เปลี่ยนได้, usage assumptions)
- บาง provider/service ไม่ support เต็มที่
- Free tier — limited features
- Some pricing tiers (volume discounts) ไม่ตรง
ทางเลือก
- AWS Cost Explorer — actual bill
- Vantage — multi-cloud cost monitoring
- Cloudability / Apptio — enterprise FinOps
- Pluralith — visualize Terraform infra + cost
สรุป
- Infracost = preview cost ก่อน apply
- ใช้ใน PR — ทีมเห็น cost change
- Setup: install + auth + run breakdown/diff
- CI integration ใน GitHub/GitLab/Atlantis
- Usage file ทำให้ estimate แม่นยำกว่า
- Set cost policies ป้องกัน surprise bills
ต่อไป → Section 18: Security