@aws/cloudformation-validate

中文文档
1.15.0发布于 2026/11/04Apache-2.0TypeScriptCommonJS零依赖构建来源已验证近 30 天下载 93.2万

Fast, offline, embeddable validation for AWS CloudFormation templates

原始使用文档
文档目录15 节
  1. Installation
  2. Quick start
  3. Engine
  4. Engine interface
  5. EngineConfig
  6. CompositeEngine
  7. ValidateConfig
  8. RuleFilterConfig
  9. PseudoParameterOverrides
  10. TemplateModel
  11. SchemaValidator
  12. AWS CLI command validation
  13. Report Types
  14. ValidationReport
  15. Diagnostic

AWS CloudFormation Validate

Validate AWS CloudFormation templates from JavaScript or TypeScript and catch schema violations, semantic errors, security risks, and best-practice findings before deployment - in your editor, build, service, or CI.

  • Offline - all rules and CloudFormation resource schemas are bundled; nothing is fetched at runtime and no AWS credentials are needed.
  • Fast - engines and schemas compile once and are reused across validations; typical templates validate in under a second.
  • Self-contained - the WebAssembly module is bundled in the package; there are no native dependencies.

The package exports all public entry points and most supporting types from @aws/cloudformation-validate.

Installation

Available on npm as @aws/cloudformation-validate.

npm install @aws/cloudformation-validate

Requires Node.js 20 or later. The package has no runtime dependencies.

Quick start

Engines, models, and validators hold off-heap memory - call .free() when done with each object:

import { CompositeEngine, TemplateFile } from "@aws/cloudformation-validate";

const engine = new CompositeEngine();
try {
    const report = engine.validateTemplate(new TemplateFile("template.yaml"));
    for (const d of report.diagnostics) {
        console.log(`[${d.severity}] ${d.ruleId}: ${d.message}`);
    }
} finally {
    engine.free();
}

Each diagnostic identifies the rule, severity, affected entity and property, and source location - see Diagnostic. A complete, runnable project is in examples.

Engines are expensive to construct (rules compile once) and cheap to reuse - create one engine and validate many templates. Validation-core failures throw message strings; JavaScript argument checks and file reads retain their native error types. Handle every case with catch (error) { String(error) }. On wasm32-unknown-unknown, an internal Rust panic cannot unwind through catch_panics: it traps the WebAssembly call and surfaces as a catchable WebAssembly.RuntimeError, rather than aborting the host process. Recreate the WebAssembly instance before continuing. version() returns the bundled validation core version.

A template is passed as a Template - either a TemplateFile, which wraps a filesystem path the engine reads, or a TemplateContent, which carries template text or bytes already in memory so nothing is read from disk. The file path or the content name labels the report and its diagnostics; an omitted TemplateContent name defaults to "template" (DEFAULT_TEMPLATE_NAME).

type Template = TemplateFile | TemplateContent;

class TemplateFile {
    constructor(path: string);                                   // template read from disk
}

class TemplateContent {
    constructor(content: string | Uint8Array, name?: string);    // in-memory UTF-8 text or raw bytes
}

const fromDisk = engine.validateTemplate(new TemplateFile("template.yaml"));
const fromMemory = engine.validateTemplate(new TemplateContent("Resources: {}", "inline.yaml"));

TemplateModel and SchemaValidator.validate accept the same Template union.

Engine

RegoEngine and CelEngine both implement the Engine interface and are interchangeable - they produce identical diagnostics for the same template and config. CompositeEngine implements the same interface and layers custom Rego, CEL, and Guard rules on top of the built-in rules - see CompositeEngine.

Engine interface

interface Engine {
    validateTemplate(template: Template, config?: ValidateConfig): ValidationReport;
    validateAwsCliCommand(request: AwsCliCommand): AwsCliCommandValidation;
    listRules(): RuleInfo[];
    engineName(): string;
    free(): void;
}
MethodReturnsDescription
validateTemplate(template, config?)ValidationReportValidates the template and returns a report. config.detailLevel (default DETAILED) selects how much per-diagnostic context is populated: DETAILED adds documentation URLs, rule descriptions, phase tags, and ViolationContext; STANDARD leaves those enrichment fields absent
validateAwsCliCommand(request)AwsCliCommandValidationModels an AWS CLI command as CloudFormation resource state and validates it - see AWS CLI command validation
listRules()RuleInfo[]Returns metadata for every built-in and loaded custom rule
engineName()string"rego", "cel", or "composite"
free()voidReleases the engine's off-heap memory; the engine must not be used afterwards

EngineConfig

Passed to the constructor. All fields are optional: the rule lists default to empty and an omitted schemaValidatorConfig uses only the bundled schemas.

interface EngineConfig {
    customRules?: RuleSource[];                      // engine-native rules (Rego for RegoEngine, CEL for CelEngine)
    guardRules?: RuleSource[];                       // CloudFormation Guard DSL rules - evaluated by the Guard evaluator
    schemaValidatorConfig?: SchemaValidatorConfig;   // additional resource provider schemas
}

interface SchemaValidatorConfig {
    additionalSchemas?: SchemaSource[];   // resource provider schemas merged over the bundled schemas
}

type RuleSource = ExternalRuleSource | RuleFile;
type SchemaSource = AdditionalSchemaSource | SchemaFile;

interface ExternalRuleSource {
    name: string;     // identifier shown in diagnostics (e.g. file path)
    content: string;  // full rule source text
}

interface AdditionalSchemaSource {
    typeName?: string; // omit to use the typeName inside the schema JSON
    schema: string;    // complete resource provider schema JSON
}

class RuleFile {
    constructor(path: string);                    // rule file read from disk; the path becomes the rule source name
}

class SchemaFile {
    constructor(path: string, typeName?: string); // schema file; typeName defaults to the value inside the JSON
}
FieldDefaultDescription
customRules[]Engine-native rules: Rego source for RegoEngine, CEL JSON for CelEngine
guardRules[]CloudFormation Guard DSL rules, evaluated by the Guard evaluator identically in every engine
schemaValidatorConfigundefinedOptional SchemaValidatorConfig whose additionalSchemas are merged over the bundled schemas

Each rule is an ExternalRuleSource - name identifies the rule in diagnostics and content is the full rule source text. Pass a RuleFile to load one from disk (the same pattern as TemplateFile for templates), or an ExternalRuleSource when you already have the rule text in memory. Each additional schema is an AdditionalSchemaSource - a complete resource provider schema JSON plus an optional typeName that may be omitted when the schema JSON contains its own typeName; SchemaFile loads one from disk. Additional schemas extend the bundled schemas or register resource types CloudFormation has not published yet; a malformed, contradictory, or unsupported schema fails engine construction rather than silently weakening validation. Guard rules are evaluated by the CloudFormation Guard evaluator itself against the template as written, so every engine reports exactly what cfn-guard validate reports; a Guard file that does not parse also fails engine construction. The two forms can be mixed freely:

import { CelEngine, RuleFile, SchemaFile } from "@aws/cloudformation-validate";

const engine = new CelEngine({
    customRules: [new RuleFile("rules/s3_encryption.json")],
    guardRules: [new RuleFile("rules/compliance.guard")],
    schemaValidatorConfig: {
        additionalSchemas: [new SchemaFile("schemas/aws-lambda-function.json")],
    },
});

See Custom Rules for the Rego, CEL, and Guard rule formats and Additional Resource Provider Schemas for the schema merge model.

CompositeEngine

CompositeEngine implements the same Engine interface but takes a CompositeEngineConfig. It evaluates every built-in rule with a fixed built-in CEL evaluator and layers the caller-supplied custom rules on top: custom CEL and Guard rules run alongside that built-in engine, while custom Rego rules run in a separate external engine that is constructed only when Rego rules are supplied. With no custom rules it produces the same built-in diagnostics as RegoEngine and CelEngine, and engineName() returns "composite". Because the composite fixes which engine owns the built-ins, the config has no customRules field - it carries only the custom rules layered on top:

interface CompositeEngineConfig {
    regoRules?: RuleSource[];                        // custom Rego rules, run by the external engine
    celRules?: RuleSource[];                         // custom CEL rules, run by the built-in engine
    guardRules?: RuleSource[];                       // CloudFormation Guard DSL rules, evaluated alongside the built-in engine
    schemaValidatorConfig?: SchemaValidatorConfig;   // additional resource provider schemas, observed by both inner engines
}
FieldDefaultDescription
regoRules[]Custom Rego rules layered on top of the built-in rules, run by the external engine
celRules[]Custom CEL rules layered on top of the built-in rules, run by the built-in engine
guardRules[]CloudFormation Guard DSL rules layered on top of the built-in rules, evaluated alongside the built-in engine
schemaValidatorConfigundefinedOptional SchemaValidatorConfig, observed by both inner engines
import { CompositeEngine, RuleFile, TemplateFile } from "@aws/cloudformation-validate";

const engine = new CompositeEngine({
    regoRules: [new RuleFile("rules/s3_naming.rego")],
    guardRules: [new RuleFile("rules/compliance.guard")],
});
try {
    const report = engine.validateTemplate(new TemplateFile("template.yaml"));
} finally {
    engine.free();
}

ValidateConfig

Controls filtering, detail, severity, parameter overrides, and behavior for one validation call. All fields have defaults - omitting the config or passing {} uses them.

const report = engine.validateTemplate(new TemplateFile("template.yaml"), {
    exclude: { ids: ["I1002"] },
    severityLevel: "WARN",
});
interface ValidateConfig {
    include?: RuleFilterConfig;
    exclude?: RuleFilterConfig;
    detailLevel?: DetailLevel;
    severityLevel?: Severity;
    parameterOverrides?: Record<string, string>;
    pseudoParameterOverrides?: PseudoParameterOverrides;
    strict?: boolean;
    disableBuiltinRules?: boolean;
}
FieldDefaultDescription
include{} (all rules)When set, only matching rules produce diagnostics. Empty means include everything.
exclude{} (nothing excluded)Matching rules are suppressed. Applied after include.
detailLevel"DETAILED"Per-diagnostic context. "DETAILED" populates documentation URLs, rule descriptions, phase tags, and ViolationContext; "STANDARD" leaves those enrichment fields absent.
severityLevel"INFO"Minimum severity threshold. Diagnostics below this level are dropped. Values: DEBUG, INFO, WARN, ERROR, FATAL.
parameterOverrides{}Override template parameter values during resolution. Keys are parameter logical IDs.
pseudoParameterOverridesall undefinedOverride CloudFormation pseudo-parameters (AWS::AccountId, AWS::Region, etc.).
strictfalseWhen true, WARN-severity diagnostics are upgraded to ERROR.
disableBuiltinRulesfalseWhen true, all built-in rules (schema validation, Step Functions, Metadata Context, and engine rules) are skipped; only custom and Guard rules are evaluated.

RuleFilterConfig

Both include and exclude use this structure. All fields are additive - a rule matches if it hits any criterion.

interface RuleFilterConfig {
    ids?: string[];                       // exact rule IDs, e.g. ["E3012", "W3010"]
    categories?: string[];                // display names, e.g. ["Security", "Best Practice"]
    idRanges?: IdRange[];                 // numeric ranges, e.g. { prefix: "E", start: 3000, end: 3099 }
    idPatterns?: string[];                // regex patterns matched against rule IDs
    resourceIds?: ResourceIdFilter[];     // a rule (or every rule) on a logical resource ID
    logicalIds?: LogicalIdFilter[];       // a rule (or every rule) on a named template entity
    resourceTypes?: ResourceTypeFilter[]; // a rule (or every rule) on a resource type
    services?: ServiceFilter[];           // a rule (or every rule) on a service, e.g. "AWS::AutoScaling"
}

// resourceIds / logicalIds / resourceTypes / services each carry an optional ruleId:
// set it to scope the filter to one rule, or omit it for every rule on the target.
interface ResourceIdFilter   { ruleId?: string; resourceId: string; }
interface LogicalIdFilter    { ruleId?: string; logicalId: string; entityType?: EntityType; }
interface ResourceTypeFilter { ruleId?: string; resourceType: string; }
interface ServiceFilter      { ruleId?: string; service: string; }

The service is matched verbatim against the service-provider::service-name prefix of the resource type - its first two ::-delimited segments (e.g. AWS::AutoScaling in AWS::AutoScaling::LaunchConfiguration).

The resourceIds dimension matches only diagnostics attributed to a resource; logicalIds additionally matches diagnostics on parameters, outputs, mappings, metadata, conditions, and template rules. For resource diagnostics, the two dimensions carry the same value. An optional entityType scopes a LogicalIdFilter to entities of one type, so MyThing as a "Parameter" is matched without touching a same-named entity of another type.

PseudoParameterOverrides

Override CloudFormation pseudo-parameters used during intrinsic function resolution. All fields are optional - when undefined, the engine uses built-in defaults (e.g. region defaults to us-east-1).

interface PseudoParameterOverrides {
    accountId?: string;         // AWS::AccountId
    notificationArns?: string;  // AWS::NotificationARNs
    partition?: string;         // AWS::Partition
    region?: string;            // AWS::Region (default: "us-east-1")
    stackId?: string;           // AWS::StackId
    stackName?: string;         // AWS::StackName
    urlSuffix?: string;         // AWS::URLSuffix
}

TemplateModel

Parses a template into the resolved SemanticModel for direct inspection - the same model the engines evaluate rules against.

const model = new TemplateModel(new TemplateFile("template.yaml"));
const inMemory = new TemplateModel(new TemplateContent("Resources: {}"));
MethodReturnsDescription
resources()Record<string, ResolvedResource>All resources with resolved property values
parameters()Record<string, ParameterInfo>Parameter definitions with types, defaults, constraints
outputs()Record<string, ResolvedOutput>Outputs with resolved values and export names
conditions()string[]Condition names defined in the template
transforms()string[]Transform declarations (e.g. AWS::Serverless-2016-10-31)
formatVersion()string | undefinedAWSTemplateFormatVersion value
description()string | undefinedTemplate description
toDiagnosticModel()DiagnosticModelFull diagnostic model including reference graph, condition implications, and resolution sources
sourceLocation(path)SourceSpan | nullSource line/column span for a JSON path (e.g. Resources/MyBucket/Properties/BucketName)
free()voidReleases the model's off-heap memory; the model must not be used afterwards

SchemaValidator

Runs schema validation independently from the rule engines. Checks each resource against the compiled CloudFormation provider schemas and produces Fatal structural diagnostics plus schema-derived Error/Warn/Info findings. The optional constructor argument is the same SchemaValidatorConfig accepted by EngineConfig; omitting it uses only the bundled schemas.

const validator = new SchemaValidator();
try {
    const diagnostics = validator.validate(new TemplateFile("template.yaml"), "us-east-1");
} finally {
    validator.free();
}
MethodReturnsDescription
new SchemaValidator(config?)SchemaValidatorConstructs a validator; an omitted SchemaValidatorConfig uses only the bundled schemas
validate(template, region?)Diagnostic[]Schema diagnostics for a Template at STANDARD detail - the enrichment fields are absent. An omitted region validates against the union of all regions.
listRules()RuleInfo[]Schema rule metadata
schemaCount()numberNumber of compiled provider schemas
free()voidReleases the validator's off-heap memory; the validator must not be used afterwards

AWS CLI command validation

validateAwsCliCommand models an AWS CLI (or SDK) API call as CloudFormation resource state and validates it offline before it is sent. It classifies the operation, maps it to a CloudFormation resource type through a closed, generated adapter catalog, synthesizes a template from the supplied parameters, and runs the normal template pipeline on it. A TemplateBody parameter of a CloudFormation operation is validated as-is. Any request that cannot be modeled exactly - an unregistered operation, a parameter without a lossless property mapping, or a value outside a CloudFormation constraint the API itself does not enforce - is skipped with a reason, never guessed.

import { AwsCliCommand, CompositeEngine } from "@aws/cloudformation-validate";

const engine = new CompositeEngine();
try {
    const request = new AwsCliCommand("s3", "CreateBucket", { Bucket: "example-bucket" });
    const validation = engine.validateAwsCliCommand(request);
    if (validation.status === "VALIDATED") {
        for (const d of validation.report!.diagnostics) {
            console.log(`[${d.severity}] ${d.ruleId}: ${d.message}`);
        }
    } else {
        console.log(`skipped (${validation.operationKind}): ${validation.reason}`);
    }
} finally {
    engine.free();
}
class AwsCliCommand {
    constructor(
        serviceName: string,                 // canonical botocore service name, e.g. "s3" or "cloudformation"
        operationName: string,               // API operation name, e.g. "CreateBucket"
        parameters: Record<string, unknown>, // request parameters (a plain object with string keys)
        options?: AwsCliCommandOptions,
    );
}

interface AwsCliCommandOptions {
    servicePrefix?: string; // signing prefix; context only
    httpMethod?: string;    // classification hint ("GET"/"HEAD"/"DELETE") for unrecognized verbs
    isReadOnly?: boolean;   // true classifies the operation as READ_ONLY
}
  • serviceName is matched case-insensitively. Signing names, endpoint aliases, and ARN prefixes are never resolved; translate an SDK's service identity first.
  • parameters accepts nested plain objects and arrays; strings; numbers (integers must be safe JavaScript integers); bigint, booleans, null, Uint8Array, and Date (serialized as ISO 8601). Any other value is carried as an explicit unsupported marker, and because synthesis is all-or-nothing the request is then skipped with a reason naming the offending parameter - no parameter is ever silently dropped.

The result is an AwsCliCommandValidation:

FieldDescription
operationKindAwsCliOperationKind: "READ_ONLY", "CLOUD_FORMATION_CREATE", "CLOUD_FORMATION_UPDATE", "CLOUD_FORMATION_DELETE", "DATA_PLANE_MUTATION", or "UNMAPPED_MUTATION"
statusAwsCliCommandValidationStatus: "VALIDATED" when the modeled template ran through the pipeline, "SKIPPED" otherwise
templateSourceAwsCliTemplateSource | null: "TEMPLATE_BODY", "CLOUD_CONTROL_DESIRED_STATE", "SYNTHESIZED_CREATE", or "SYNTHESIZED_UPDATE"; null when skipped
resourceTypesstring[] - CloudFormation resource types the operation maps to
reasonstring - why the request was validated or skipped
reportValidationReport | null - present when "VALIDATED". The configuration is fixed: STANDARD detail level and a WARN severity floor
templateUint8Array | null - the exact template bytes that were validated (the caller's TemplateBody unchanged, or the synthesized JSON); null when skipped

The full contract - the adapter catalog, all-or-nothing mapping, and which rules are dropped for synthesized state - is documented in validation-engine/API.md.

Report Types

ValidationReport

validateTemplate always returns a ValidationReport - a template syntax failure is returned as a report with status "ERROR" and an F1101 diagnostic; only infrastructure or engine failures throw:

interface ValidationReport {
    filePath: string;
    status: "OK" | "ANALYSIS_INCOMPLETE" | "ERROR"; // incomplete may omit findings; error = parse failure
    version: string;
    metadata: ReportMetadata;
    performance: PerformanceMetrics;
    diagnostics: Diagnostic[];
}

Every finding is a Diagnostic (see Diagnostic). Its enrichment fields - documentationUrl, ruleDescription, phase (PARSE | SCHEMA | LINT), and context (ViolationContext with actualValue, expectedConstraint, resolutionSource, etc.) - are populated only at detailLevel "DETAILED" (the default); validating at "STANDARD" leaves them absent, keeping the base diagnostic fields.

metadata carries the summary counts, the number of suppressed diagnostics, the resources scanned, and the registered-rule count after category exclusions. It also records the strict flag, severity threshold, and optional budget-exhaustion records. Each record retains a stable machine-readable kind and also includes a human-readable description sentence, the numeric limit, and whether that specific exhaustion makes analysis incomplete. requiredPropertyCombinations is context-only, so its analysisIncomplete value is false and the report can remain "OK".

Diagnostic

interface Diagnostic {
    ruleId: string;                    // e.g. "E3012", "F1001", "W3010"
    severity: Severity;                // "FATAL" | "ERROR" | "WARN" | "INFO" | "DEBUG"
    message: string;
    source: RuleOrigin;                // "SCHEMA" | "CFN_LINT" | "ENGINE" | "CUSTOM" | "GUARD"
    entity?: Entity;                   // the named template entity the finding targets, if any
    propertyPath?: string;             // e.g. "Properties.BucketName", or section-absolute like "Parameters/MyParam/Type"
    suggestedFix?: string;
    category?: string;
    startLine?: number;
    startColumn?: number;
    endLine?: number;
    endColumn?: number;
    relatedResources?: RelatedResource[];
    conditionScenario?: Record<string, boolean>;  // condition truth assignment that triggers this diagnostic
    // Enrichment fields: populated at detailLevel "DETAILED" (the default), absent at "STANDARD".
    documentationUrl?: string;
    ruleDescription?: string;
    phase?: "PARSE" | "SCHEMA" | "LINT";           // pipeline stage that produced the finding
    context?: ViolationContext;                    // actualValue, expectedConstraint, resolutionSource, etc.
}

// The named template entity a diagnostic is attributed to. The entity type is the
// singular form of the top-level template section the entity is declared in.
interface Entity {
    logicalId: string;                 // logical ID as declared in the template
    entityType: EntityType;
    resourceType?: string;             // CloudFormation type, when the entity is a resource whose type is known
}

type EntityType = "Resource" | "Parameter" | "Output" | "Mapping" | "Metadata"
                | "Rule" | "Condition" | "Transform" | "FormatVersion" | "Description";

Severity, RuleOrigin, and DetailLevel are string-literal union types ("WARN", "GUARD", "STANDARD", ...), as is the report status ("OK", "ANALYSIS_INCOMPLETE", "ERROR").

版本与发布记录

@aws/cloudformation-validate 共发布 17 个版本,首次发布于 2026/06/12;过去 12 个月发布了 17 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.15.0latest2026/11/043 天前
1.14.02026/10/2316 天前
1.12.12026/09/251 个月前
1.12.02026/09/221 个月前
1.11.02026/09/221 个月前
1.10.02026/09/171 个月前

其他发布通道:beta → 1.9.0-beta。

关于 @aws/cloudformation-validate 的常见问题

@aws/cloudformation-validate 是什么?

Fast, offline, embeddable validation for AWS CloudFormation templates

如何安装 @aws/cloudformation-validate?

在项目目录运行 npm install @aws/cloudformation-validate,或使用 pnpm add / yarn add / bun add。

@aws/cloudformation-validate 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws/cloudformation-validate 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@aws/cloudformation-validate 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aws/cloudformation-validate 可以商用吗?

@aws/cloudformation-validate 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws/cloudformation-validate 的下载量有多少?

根据 npm 官方下载统计,@aws/cloudformation-validate 在 2026/10/08 – 2026/11/06 这 30 天内被下载 931,684 次,日均约 31,056 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws/cloudformation-validate 还在维护吗?

最新版本 1.15.0 发布于 2026/11/04(3 天前);至今共发布 17 个版本,其中过去 12 个月发布了 17 个;首次发布于 2026/06/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。