インフラテスト

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

IaCテスト

インフラテストとは

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

テストのレベル

テストのレベルを以下にまとめる。

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

cfn-lint (静的解析)

cfn-lint (静的解析) の例を示す。

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

SAM テンプレートのテスト

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');
});

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

テストピラミッド (インフラ版) を図で示す。

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

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

この記事は役に立ちましたか?

関連用語

関連する記事