Infracost
Terraformのテンプレートファイルからコストを試算することができるらしい。基本的に AWS リソースは Terraform 管理しているので使えるかも(?)と思った。CI に組み込むこともできるようなので GitHub Actions で試しても良さそう。
CLI 機能をサポートするOSSやVSCodeの拡張ツールがある模様。
実際に CLI の方を使ってみる
まず、infracost を install する。
% brew install infracost
API Key を取得する。個人の GitHub でログインした。
% infracost auth login We're redirecting you to our log in page, please complete that, and return here to continue using Infracost. If the redirect doesn't work, either: - Use this URL: https://dashboard.infracost.io/login?cli_port=49740&cli_state=84677633-a7ab-4db7-a357-26e50bacd98e&cli_version=v0.10.34&os=darwin&utm_source=cli - Or log in/sign up at https://dashboard.infracost.io, copy your API key from Org Settings and run `infracost configure set api_key MY_KEY` Waiting... The API key was saved to /Users/harukin/.config/infracost/credentials.yml Your account has been authenticated. Run Infracost on your Terraform project by running: infracost breakdown --path=. % cat /Users/harukin/.config/infracost/credentials.yml version: "0.1" api_key: <api_key> pricing_api_endpoint: https://pricing.api.infracost.io
認証が完了すると、この画面表示に切り替わる。
AWS リソースで実行してみる
Amazon EC2 の t2.micro
で試す。
% pwd /Users/harukin/ghq/github.com/harukin721/aws/terraform/ec2 % cat main.tf resource "aws_instance" "ec2" { count = 1 # Amazon Linux 2023 AMI 2023.0.20230419.0 x86_64 HVM kernel-6.1 ami = "ami-01b32aa8589df6208" instance_type = "t2.micro" root_block_device { volume_type = "gp3" volume_size = 30 } }
コマンドを実行。Monthly cost
が $11
との試算が出た。
% infracost breakdown --path . Evaluating Terraform directory at . ✔ Downloading Terraform modules ✔ Evaluating Terraform directory ✔ Retrieving cloud prices to calculate costs Project: harukin721/aws/terraform/ec2 Name Monthly Qty Unit Monthly Cost aws_instance.ec2[0] ├─ Instance usage (Linux/UNIX, on-demand, t2.micro) 730 hours $8.47 └─ root_block_device └─ Storage (general purpose SSD, gp3) 30 GB $2.40 OVERALL TOTAL $10.87 ────────────────────────────────── 1 cloud resource was detected: ∙ 1 was estimated, it includes usage-based costs, see https://infracost.io/usage-file ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ ┃ Project ┃ Monthly cost ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━┫ ┃ harukin721/aws/terraform/ec2 ┃ $11 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━┛
VSCode拡張機能
自分は VSCode の拡張機能は試していないけど、classmethod さんの記事の通りにやると良さそう。
その他
軽くしか調べていないけど、リザーブドインスタンス分でのコスト削減がどのくらいか、CloudWatch,S3, Lambda ...etc、などの使用料ベースの計算もできそう。
おわり
コマンド1発でコスト試算ができるので便利。どこまでの精度なのかはまだ正直よくわかっていないです。Infracost Cloud
というものを使えば、コスト試算の他にコストを最適化するための提案もしてくれるみたいです。
参考
AWS Dev Day 2023 Tokyo
の [SA-3-2] 成長を続ける SaaS の AWS コスト管理において開発者としてできること
で知りました。