インフラテスト

IaC テンプレートやデプロイ済みインフラの正当性を自動テストで検証する手法

IaCテスト

インフラテストとは

インフラテストは、IaC テンプレート (CloudFormation, SAM, CDK) やデプロイ済みインフラの正当性を自動テストで検証する手法である。「インフラもコードなら、テストも書くべき」という考え方。

テストのレベル

レベル 対象 ツール
静的解析 テンプレートの構文・ベストプラクティス cfn-lint, checkov
ユニットテスト CDK のコンストラクト Jest + CDK assertions
スナップショットテスト テンプレートの差分検出 Jest snapshot
統合テスト デプロイ済みリソースの検証 AWS SDK
セキュリティスキャン 設定ミス、過剰な権限 checkov, cfn-nag

cfn-lint (静的解析)

cfn-lint template.yaml
# E3012 Property Resources/MyFunction/Properties/Runtime not valid
# W2001 Parameter Environment not used

SAM テンプレートのテスト

import { readFileSync } from 'fs';
import { load } from 'js-yaml';

const template = load(readFileSync('template.yaml', 'utf8')) as any;

test('Lambda のメモリサイズが適切', () => {
  const fn = template.Resources.MyFunction.Properties;
  expect(fn.MemorySize).toBeLessThanOrEqual(512);
});

test('DynamoDB がオンデマンドモード', () => {
  const table = template.Resources.MyTable.Properties;
  expect(table.BillingMode).toBe('PAY_PER_REQUEST');
});

test('全 Lambda に Tracing が有効', () => {
  const functions = Object.entries(template.Resources)
    .filter(([, r]: any) => r.Type === 'AWS::Serverless::Function');
  for (const [name, fn] of functions) {
    expect((fn as any).Properties.Tracing).toBe('Active');
  }
});

セキュリティテスト

test('Lambda に過剰な権限がない', () => {
  const policies = template.Resources.MyFunction.Properties.Policies;
  const hasWildcard = JSON.stringify(policies).includes('"*"');
  expect(hasWildcard).toBe(false);
});

test('S3 バケットがパブリックでない', () => {
  const config = template.Resources.MyBucket.Properties;
  expect(config.PublicAccessBlockConfiguration).toBeDefined();
});

デプロイ後の統合テスト

import { DynamoDBClient, DescribeTableCommand } from '@aws-sdk/client-dynamodb';

test('DynamoDB テーブルが存在する', async () => {
  const client = new DynamoDBClient({});
  const result = await client.send(
    new DescribeTableCommand({ TableName: 'my-table-dev' })
  );
  expect(result.Table?.TableStatus).toBe('ACTIVE');
});

テストピラミッド (インフラ版)

        /  統合テスト  \     ← 少数、遅い、高コスト
       / スナップショット \
      /   ユニットテスト   \  ← 多数、速い、低コスト
     /     静的解析        \

現場での応用を知るには関連書籍も役立つ。

関連用語