cloudformation-validate 1.10.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cloudformation_validate/README.md +436 -0
- cloudformation_validate/__init__.py +444 -0
- cloudformation_validate/_native.py +58 -0
- cloudformation_validate/bindings_python.py +2305 -0
- cloudformation_validate/data_source.py +674 -0
- cloudformation_validate/diagnostics.py +1954 -0
- cloudformation_validate/natives/win32-x86-64/bindings_python.dll +0 -0
- cloudformation_validate/rules.py +1353 -0
- cloudformation_validate/schema_validator.py +666 -0
- cloudformation_validate/template_model.py +4470 -0
- cloudformation_validate/validation_engine.py +1902 -0
- cloudformation_validate-1.10.0.dist-info/METADATA +467 -0
- cloudformation_validate-1.10.0.dist-info/RECORD +18 -0
- cloudformation_validate-1.10.0.dist-info/WHEEL +5 -0
- cloudformation_validate-1.10.0.dist-info/licenses/LICENSE +175 -0
- cloudformation_validate-1.10.0.dist-info/licenses/NOTICE +8 -0
- cloudformation_validate-1.10.0.dist-info/licenses/THIRD-PARTY-LICENSES.txt +20522 -0
- cloudformation_validate-1.10.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
# CloudFormation Validate for Python
|
|
2
|
+
|
|
3
|
+
Validate AWS CloudFormation templates from Python and catch schema violations, semantic errors, security risks, and
|
|
4
|
+
best-practice findings before deployment - in your editor, build, service, or CI.
|
|
5
|
+
|
|
6
|
+
- **Offline** - all rules and CloudFormation resource schemas are bundled; nothing is fetched at runtime and no AWS
|
|
7
|
+
credentials are needed.
|
|
8
|
+
- **Fast** - engines and schemas compile once and are reused across validations; typical templates validate in under a
|
|
9
|
+
second.
|
|
10
|
+
- **Self-contained** - each platform wheel bundles its matching native library.
|
|
11
|
+
|
|
12
|
+
All types are importable from the top-level `cloudformation_validate` package.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
Available on [PyPI](https://pypi.org/project/cloudformation-validate/) as `cloudformation-validate`.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install cloudformation-validate
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Requires Python 3.9 or later. The package has no runtime dependencies. PyPI publishes a separate wheel for every
|
|
23
|
+
supported native target; each wheel carries exactly one native library and an accurate platform tag, so pip downloads
|
|
24
|
+
only the artifact compatible with the installing host.
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from cloudformation_validate import RegoEngine
|
|
30
|
+
|
|
31
|
+
engine = RegoEngine()
|
|
32
|
+
report = engine.validate_template("template.yaml")
|
|
33
|
+
for d in report.diagnostics:
|
|
34
|
+
print(f"[{d.severity.name}] {d.rule_id}: {d.message}")
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Each diagnostic identifies the rule, severity, affected entity and property, and source location - see
|
|
38
|
+
[Diagnostic](#diagnostic).
|
|
39
|
+
|
|
40
|
+
Engines are expensive to construct (rules compile once) and cheap to reuse - create one engine and validate many
|
|
41
|
+
templates. Every fallible call raises `ValidationError` on failure; internal panics are caught at the FFI boundary and
|
|
42
|
+
surface as the same exception, never a process abort. `version()` returns the version of the bundled validation core.
|
|
43
|
+
|
|
44
|
+
A template is passed either as a file path (`str` or `os.PathLike`, read from disk; the path is used for diagnostic
|
|
45
|
+
source locations) or as raw `bytes`:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
report = engine.validate_template(b"Resources: {}")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Engine
|
|
52
|
+
|
|
53
|
+
`RegoEngine` and `CelEngine` both subclass `Engine` and are interchangeable - they produce identical diagnostics for
|
|
54
|
+
the same template and config. `CompositeEngine` also subclasses `Engine` and layers custom Rego, CEL, and Guard rules
|
|
55
|
+
on top of the built-in rules - see [CompositeEngine](#compositeengine).
|
|
56
|
+
|
|
57
|
+
### `Engine` base class
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
class Engine:
|
|
61
|
+
def validate_template(self, template: str | os.PathLike | bytes, config: ValidateConfig | None = None) -> ValidationReport: ...
|
|
62
|
+
def validate_aws_cli_command(self, request: AwsCliCommand) -> AwsCliCommandValidation: ...
|
|
63
|
+
def list_rules(self) -> list[RuleInfo]: ...
|
|
64
|
+
def engine_name(self) -> str: ...
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
| Method | Returns | Description |
|
|
68
|
+
|--------------------------------------------|---------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
69
|
+
| `validate_template(template, config=None)` | `ValidationReport` | Validates the template and returns a report. `config.detail_level` (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 |
|
|
70
|
+
| `validate_aws_cli_command(request)` | `AwsCliCommandValidation` | Models an AWS CLI command as CloudFormation resource state and validates it - see [AWS CLI command validation](#aws-cli-command-validation) |
|
|
71
|
+
| `list_rules()` | `list[RuleInfo]` | Returns metadata for every built-in and loaded custom rule |
|
|
72
|
+
| `engine_name()` | `str` | `"rego"`, `"cel"`, or `"composite"` |
|
|
73
|
+
|
|
74
|
+
### `EngineConfig`
|
|
75
|
+
|
|
76
|
+
Passed to the constructor. All fields are optional: the rule lists default to empty and a `None`
|
|
77
|
+
`schema_validator_config` uses only the bundled schemas.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
@dataclass
|
|
81
|
+
class EngineConfig:
|
|
82
|
+
custom_rules: list[ExternalRuleSource] = [] # engine-native rules (Rego for RegoEngine, CEL for CelEngine)
|
|
83
|
+
guard_rules: list[ExternalRuleSource] = [] # CloudFormation Guard DSL rules - evaluated by the Guard evaluator
|
|
84
|
+
schema_validator_config: SchemaValidatorConfig | None = None # additional resource provider schemas
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class SchemaValidatorConfig:
|
|
88
|
+
additional_schemas: list[AdditionalSchemaSource] = [] # resource provider schemas merged over the bundled schemas
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class ExternalRuleSource:
|
|
92
|
+
name: str # identifier shown in diagnostics (e.g. file path)
|
|
93
|
+
content: str # full rule source text
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class AdditionalSchemaSource:
|
|
97
|
+
type_name: str | None = None # None to use the typeName inside the schema JSON
|
|
98
|
+
schema: str # complete resource provider schema JSON
|
|
99
|
+
|
|
100
|
+
def file_to_external_rule_source(path) -> ExternalRuleSource: ... # rule file read from disk; the path becomes the rule source name
|
|
101
|
+
def file_to_additional_schema_source(path, type_name=None) -> AdditionalSchemaSource: ... # schema file; type_name defaults to the value inside the JSON
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
| Field | Default | Description |
|
|
105
|
+
|---------------------------|---------|------------------------------------------------------------------------------------------------|
|
|
106
|
+
| `custom_rules` | `[]` | Engine-native rules: Rego source for `RegoEngine`, CEL JSON for `CelEngine` |
|
|
107
|
+
| `guard_rules` | `[]` | CloudFormation Guard DSL rules, evaluated by the Guard evaluator identically in every engine |
|
|
108
|
+
| `schema_validator_config` | `None` | Optional `SchemaValidatorConfig` whose `additional_schemas` are merged over the bundled schemas |
|
|
109
|
+
|
|
110
|
+
Each rule is an `ExternalRuleSource` - `name` identifies the rule in diagnostics and `content` is the full rule source
|
|
111
|
+
text. Use `file_to_external_rule_source(path)` to load one from disk (the same pattern as passing a template path to
|
|
112
|
+
`validate_template`), or construct an `ExternalRuleSource(name, content)` when you already have the rule text in memory.
|
|
113
|
+
Each additional schema is an `AdditionalSchemaSource` - a complete resource provider schema JSON plus an optional
|
|
114
|
+
`type_name` that may be omitted when the schema JSON contains its own `typeName`;
|
|
115
|
+
`file_to_additional_schema_source(path)` loads one from disk. Additional schemas extend the bundled schemas or register
|
|
116
|
+
resource types CloudFormation has not published yet; a malformed, contradictory, or unsupported schema fails engine
|
|
117
|
+
construction rather than silently weakening validation. Guard rules are evaluated by the CloudFormation Guard evaluator
|
|
118
|
+
itself against the template as written, so every engine reports exactly what `cfn-guard validate` reports; a Guard file
|
|
119
|
+
that does not parse also fails engine construction. The two forms can be mixed freely:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from cloudformation_validate import (
|
|
123
|
+
CelEngine, EngineConfig, SchemaValidatorConfig, file_to_additional_schema_source, file_to_external_rule_source,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
engine = CelEngine(
|
|
127
|
+
EngineConfig(
|
|
128
|
+
custom_rules=[file_to_external_rule_source("rules/s3_encryption.json")],
|
|
129
|
+
guard_rules=[file_to_external_rule_source("rules/compliance.guard")],
|
|
130
|
+
schema_validator_config=SchemaValidatorConfig(
|
|
131
|
+
additional_schemas=[file_to_additional_schema_source("schemas/aws-lambda-function.json")],
|
|
132
|
+
),
|
|
133
|
+
),
|
|
134
|
+
)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
See [Custom Rules](../CUSTOM_RULES.md) for the Rego, CEL, and Guard rule formats and
|
|
138
|
+
[Additional Resource Provider Schemas](../validation-engine/API.md#additional-resource-provider-schemas) for the schema
|
|
139
|
+
merge model.
|
|
140
|
+
|
|
141
|
+
### `CompositeEngine`
|
|
142
|
+
|
|
143
|
+
`CompositeEngine` also subclasses `Engine` but takes a `CompositeEngineConfig`. It evaluates every built-in rule with a
|
|
144
|
+
fixed built-in CEL evaluator and layers the caller-supplied custom rules on top: custom CEL and Guard rules run
|
|
145
|
+
alongside that built-in engine, while custom Rego rules run in a separate external engine that is constructed only when
|
|
146
|
+
Rego rules are supplied. With no custom rules it produces the same built-in diagnostics as `RegoEngine` and `CelEngine`,
|
|
147
|
+
and `engine_name()` returns `"composite"`. Because the composite fixes which engine owns the built-ins, the config has
|
|
148
|
+
no `custom_rules` field - it carries only the custom rules layered on top:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
@dataclass
|
|
152
|
+
class CompositeEngineConfig:
|
|
153
|
+
rego_rules: list[ExternalRuleSource] = [] # custom Rego rules, run by the external engine
|
|
154
|
+
cel_rules: list[ExternalRuleSource] = [] # custom CEL rules, run by the built-in engine
|
|
155
|
+
guard_rules: list[ExternalRuleSource] = [] # CloudFormation Guard DSL rules, evaluated alongside the built-in engine
|
|
156
|
+
schema_validator_config: SchemaValidatorConfig | None = None # additional resource provider schemas, observed by both inner engines
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
| Field | Default | Description |
|
|
160
|
+
|---------------------------|---------|--------------------------------------------------------------------------------------------------|
|
|
161
|
+
| `rego_rules` | `[]` | Custom Rego rules layered on top of the built-in rules, run by the external engine |
|
|
162
|
+
| `cel_rules` | `[]` | Custom CEL rules layered on top of the built-in rules, run by the built-in engine |
|
|
163
|
+
| `guard_rules` | `[]` | CloudFormation Guard DSL rules layered on top of the built-in rules, evaluated alongside the built-in engine |
|
|
164
|
+
| `schema_validator_config` | `None` | Optional `SchemaValidatorConfig`, observed by both inner engines |
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
from cloudformation_validate import CompositeEngine, CompositeEngineConfig, file_to_external_rule_source
|
|
168
|
+
|
|
169
|
+
engine = CompositeEngine(
|
|
170
|
+
CompositeEngineConfig(
|
|
171
|
+
rego_rules=[file_to_external_rule_source("rules/s3_naming.rego")],
|
|
172
|
+
guard_rules=[file_to_external_rule_source("rules/compliance.guard")],
|
|
173
|
+
),
|
|
174
|
+
)
|
|
175
|
+
report = engine.validate_template("template.yaml")
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## ValidateConfig
|
|
179
|
+
|
|
180
|
+
Controls filtering, detail, severity, parameter overrides, and behavior for one validation call. All fields have
|
|
181
|
+
defaults - omitting the config or passing `ValidateConfig()` uses them.
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
from cloudformation_validate import RuleFilterConfig, Severity, ValidateConfig
|
|
185
|
+
|
|
186
|
+
report = engine.validate_template(
|
|
187
|
+
"template.yaml",
|
|
188
|
+
ValidateConfig(
|
|
189
|
+
exclude=RuleFilterConfig(ids=["I1002"]),
|
|
190
|
+
severity_level=Severity.WARN,
|
|
191
|
+
),
|
|
192
|
+
)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
@dataclass
|
|
197
|
+
class ValidateConfig:
|
|
198
|
+
include: RuleFilterConfig = RuleFilterConfig()
|
|
199
|
+
exclude: RuleFilterConfig = RuleFilterConfig()
|
|
200
|
+
detail_level: DetailLevel | None = None # None = DETAILED
|
|
201
|
+
severity_level: Severity | None = None # None = INFO
|
|
202
|
+
parameter_overrides: dict[str, str] = {}
|
|
203
|
+
pseudo_parameter_overrides: PseudoParameterOverrides = PseudoParameterOverrides()
|
|
204
|
+
strict: bool | None = None # None = False
|
|
205
|
+
disable_builtin_rules: bool | None = None # None = False
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
| Field | Default | Description |
|
|
209
|
+
|------------------------------|--------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
210
|
+
| `include` | empty (all rules) | When set, only matching rules produce diagnostics. Empty means include everything. |
|
|
211
|
+
| `exclude` | empty (nothing excluded) | Matching rules are suppressed. Applied after `include`. |
|
|
212
|
+
| `detail_level` | `DETAILED` | Per-diagnostic context. `DETAILED` populates documentation URLs, rule descriptions, phase tags, and `ViolationContext`; `STANDARD` leaves those enrichment fields absent. |
|
|
213
|
+
| `severity_level` | `INFO` | Minimum severity threshold. Diagnostics below this level are dropped. Values: `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`. |
|
|
214
|
+
| `parameter_overrides` | `{}` | Override template parameter values during resolution. Keys are parameter logical IDs. |
|
|
215
|
+
| `pseudo_parameter_overrides` | all `None` | Override CloudFormation pseudo-parameters (`AWS::AccountId`, `AWS::Region`, etc.). |
|
|
216
|
+
| `strict` | `False` | When `True`, `WARN`-severity diagnostics are upgraded to `ERROR`. |
|
|
217
|
+
| `disable_builtin_rules` | `False` | When `True`, all built-in rules (schema validation, Step Functions, engine rules) are skipped; only custom and Guard rules are evaluated. |
|
|
218
|
+
|
|
219
|
+
### RuleFilterConfig
|
|
220
|
+
|
|
221
|
+
Both `include` and `exclude` use this structure. All fields are additive - a rule matches if it hits any criterion.
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
@dataclass
|
|
225
|
+
class RuleFilterConfig:
|
|
226
|
+
ids: list[str] = [] # exact rule IDs, e.g. ["E3012", "W3010"]
|
|
227
|
+
categories: list[str] = [] # category names, e.g. ["security", "best_practices"]
|
|
228
|
+
id_ranges: list[IdRange] = [] # numeric ranges, e.g. IdRange(prefix="E", start=3000, end=3099)
|
|
229
|
+
id_patterns: list[str] = [] # regex patterns matched against rule IDs
|
|
230
|
+
resource_ids: list[ResourceIdFilter] = [] # a rule (or every rule) on a logical resource ID
|
|
231
|
+
logical_ids: list[LogicalIdFilter] = [] # a rule (or every rule) on a named template entity
|
|
232
|
+
resource_types: list[ResourceTypeFilter] = [] # a rule (or every rule) on a resource type
|
|
233
|
+
services: list[ServiceFilter] = [] # a rule (or every rule) on a service, e.g. "AWS::AutoScaling"
|
|
234
|
+
|
|
235
|
+
# resource_ids / logical_ids / resource_types / services each carry an optional rule_id:
|
|
236
|
+
# set it to scope the filter to one rule, or leave it None for every rule on the target.
|
|
237
|
+
@dataclass
|
|
238
|
+
class ResourceIdFilter: rule_id: str | None = None; resource_id: str
|
|
239
|
+
@dataclass
|
|
240
|
+
class LogicalIdFilter: rule_id: str | None = None; logical_id: str; entity_type: EntityType | None = None
|
|
241
|
+
@dataclass
|
|
242
|
+
class ResourceTypeFilter: rule_id: str | None = None; resource_type: str
|
|
243
|
+
@dataclass
|
|
244
|
+
class ServiceFilter: rule_id: str | None = None; service: str
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
The `service` is matched verbatim against the `service-provider::service-name` prefix of the resource type - its first
|
|
248
|
+
two `::`-delimited segments (e.g. `AWS::AutoScaling` in `AWS::AutoScaling::LaunchConfiguration`).
|
|
249
|
+
|
|
250
|
+
The `resource_ids` dimension matches only diagnostics attributed to a resource; `logical_ids` additionally matches
|
|
251
|
+
diagnostics on parameters, outputs, mappings, conditions, and template rules (for resource diagnostics the two carry
|
|
252
|
+
the same value). A non-`None` `entity_type` scopes a `LogicalIdFilter` to entities of one type, so `MyThing` as a
|
|
253
|
+
`PARAMETER` is matched without touching a same-named entity of another type.
|
|
254
|
+
|
|
255
|
+
### PseudoParameterOverrides
|
|
256
|
+
|
|
257
|
+
Override CloudFormation pseudo-parameters used during intrinsic function resolution. All fields are optional - when
|
|
258
|
+
`None`, the engine uses built-in defaults (e.g. region defaults to `us-east-1`).
|
|
259
|
+
|
|
260
|
+
```python
|
|
261
|
+
@dataclass
|
|
262
|
+
class PseudoParameterOverrides:
|
|
263
|
+
account_id: str | None = None # AWS::AccountId
|
|
264
|
+
notification_arns: str | None = None # AWS::NotificationARNs
|
|
265
|
+
partition: str | None = None # AWS::Partition
|
|
266
|
+
region: str | None = None # AWS::Region (default: "us-east-1")
|
|
267
|
+
stack_id: str | None = None # AWS::StackId
|
|
268
|
+
stack_name: str | None = None # AWS::StackName
|
|
269
|
+
url_suffix: str | None = None # AWS::URLSuffix
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
## TemplateModel
|
|
273
|
+
|
|
274
|
+
Parses a template into the resolved `SemanticModel` for direct inspection - the same model the engines evaluate rules
|
|
275
|
+
against.
|
|
276
|
+
|
|
277
|
+
```python
|
|
278
|
+
model = TemplateModel("template.yaml") # a path or bytes, like the engines
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
| Method | Returns | Description |
|
|
282
|
+
|-------------------------|-------------------------------|-------------------------------------------------------------------------------------------------|
|
|
283
|
+
| `resources()` | `dict[str, ResolvedResource]` | All resources with resolved property values |
|
|
284
|
+
| `parameters()` | `dict[str, ParameterInfo]` | Parameter definitions with types, defaults, constraints |
|
|
285
|
+
| `outputs()` | `dict[str, ResolvedOutput]` | Outputs with resolved values and export names |
|
|
286
|
+
| `conditions()` | `list[str]` | Condition names defined in the template |
|
|
287
|
+
| `transforms()` | `list[str]` | Transform declarations (e.g. `AWS::Serverless-2016-10-31`) |
|
|
288
|
+
| `format_version()` | `str \| None` | `AWSTemplateFormatVersion` value |
|
|
289
|
+
| `description()` | `str \| None` | Template description |
|
|
290
|
+
| `to_diagnostic_model()` | `DiagnosticModel` | Full diagnostic model including reference graph, condition implications, and resolution sources |
|
|
291
|
+
| `source_location(path)` | `SourceSpan \| None` | Source line/column span for a JSON path (e.g. `Resources/MyBucket/Properties/BucketName`) |
|
|
292
|
+
|
|
293
|
+
## SchemaValidator
|
|
294
|
+
|
|
295
|
+
Runs schema validation independently from the rule engines. Checks each resource against the compiled CloudFormation
|
|
296
|
+
provider schemas and produces `FATAL`-severity diagnostics for structural violations. The optional constructor argument
|
|
297
|
+
is the same `SchemaValidatorConfig` accepted by `EngineConfig`; omitting it uses only the bundled schemas.
|
|
298
|
+
|
|
299
|
+
```python
|
|
300
|
+
validator = SchemaValidator()
|
|
301
|
+
diagnostics = validator.validate("template.yaml")
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
| Method | Returns | Description |
|
|
305
|
+
|---------------------------------------|--------------------|-----------------------------------------------------------------------------------------------------------------|
|
|
306
|
+
| `SchemaValidator(schema_config=None)` | `SchemaValidator` | Constructs a validator; `None` uses only the bundled schemas |
|
|
307
|
+
| `validate(template, region=None)` | `list[Diagnostic]` | Schema diagnostics at `STANDARD` detail - the enrichment fields are absent. `region` defaults to `"us-east-1"`. |
|
|
308
|
+
| `list_rules()` | `list[RuleInfo]` | Schema rule metadata |
|
|
309
|
+
| `schema_count()` | `int` | Number of compiled provider schemas |
|
|
310
|
+
|
|
311
|
+
## AWS CLI command validation
|
|
312
|
+
|
|
313
|
+
`validate_aws_cli_command` models an AWS CLI (or SDK) API call as CloudFormation resource state and validates it
|
|
314
|
+
offline before it is sent. It classifies the operation, maps it to a CloudFormation resource type through a closed,
|
|
315
|
+
generated adapter catalog, synthesizes a template from the supplied parameters, and runs the normal template pipeline
|
|
316
|
+
on it. A `TemplateBody` parameter of a CloudFormation operation is validated as-is. Any request that cannot be modeled
|
|
317
|
+
exactly - an unregistered operation, a parameter without a lossless property mapping, or a value outside a
|
|
318
|
+
CloudFormation constraint the API itself does not enforce - is skipped with a reason, never guessed.
|
|
319
|
+
|
|
320
|
+
```python
|
|
321
|
+
from cloudformation_validate import AwsCliCommand, AwsCliCommandValidationStatus, RegoEngine
|
|
322
|
+
|
|
323
|
+
engine = RegoEngine()
|
|
324
|
+
request = AwsCliCommand("s3", "CreateBucket", {"Bucket": "example-bucket"})
|
|
325
|
+
validation = engine.validate_aws_cli_command(request)
|
|
326
|
+
if validation.status == AwsCliCommandValidationStatus.VALIDATED:
|
|
327
|
+
for d in validation.report.diagnostics:
|
|
328
|
+
print(f"[{d.severity.name}] {d.rule_id}: {d.message}")
|
|
329
|
+
else:
|
|
330
|
+
print(f"skipped ({validation.operation_kind.name}): {validation.reason}")
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
```python
|
|
334
|
+
class AwsCliCommand:
|
|
335
|
+
def __init__(
|
|
336
|
+
self,
|
|
337
|
+
service_name: str, # canonical botocore service name, e.g. "s3" or "cloudformation"
|
|
338
|
+
operation_name: str, # API operation name, e.g. "CreateBucket"
|
|
339
|
+
parameters: Mapping[str, object], # request parameters
|
|
340
|
+
*,
|
|
341
|
+
service_prefix: str | None = None, # signing prefix; context only
|
|
342
|
+
http_method: str | None = None, # classification hint ("GET"/"HEAD"/"DELETE") for unrecognized verbs
|
|
343
|
+
is_read_only: bool | None = None, # True classifies the operation as READ_ONLY
|
|
344
|
+
): ...
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
- `service_name` is matched case-insensitively. Signing names, endpoint aliases, and ARN prefixes are never resolved;
|
|
348
|
+
translate an SDK's service identity first.
|
|
349
|
+
- `parameters` accepts nested mappings and sequences, `str`, `int`, `float`, `bool`, `None`, `bytes`, and
|
|
350
|
+
`datetime.datetime` (serialized as ISO 8601) - the same values used by botocore request dictionaries. Any other value
|
|
351
|
+
is carried as an explicit unsupported marker, and because synthesis is all-or-nothing the request is then skipped
|
|
352
|
+
with a reason naming the offending parameter - no parameter is ever silently dropped.
|
|
353
|
+
|
|
354
|
+
The result is an `AwsCliCommandValidation`:
|
|
355
|
+
|
|
356
|
+
| Field | Description |
|
|
357
|
+
|-------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
358
|
+
| `operation_kind` | `AwsCliOperationKind`: `READ_ONLY`, `CLOUD_FORMATION_CREATE`, `CLOUD_FORMATION_UPDATE`, `CLOUD_FORMATION_DELETE`, `DATA_PLANE_MUTATION`, or `UNMAPPED_MUTATION` |
|
|
359
|
+
| `status` | `AwsCliCommandValidationStatus`: `VALIDATED` when the modeled template ran through the pipeline, `SKIPPED` otherwise |
|
|
360
|
+
| `template_source` | `AwsCliTemplateSource \| None`: `TEMPLATE_BODY`, `CLOUD_CONTROL_DESIRED_STATE`, `SYNTHESIZED_CREATE`, or `SYNTHESIZED_UPDATE`; `None` when skipped |
|
|
361
|
+
| `resource_types` | `list[str]` - CloudFormation resource types the operation maps to |
|
|
362
|
+
| `reason` | `str` - why the request was validated or skipped |
|
|
363
|
+
| `report` | `ValidationReport \| None` - present when `VALIDATED`. The configuration is fixed: `STANDARD` detail level and a `WARN` severity floor |
|
|
364
|
+
| `template` | `bytes \| None` - the exact template bytes that were validated (the caller's `TemplateBody` unchanged, or the synthesized JSON); `None` when skipped |
|
|
365
|
+
|
|
366
|
+
The full contract - the adapter catalog, all-or-nothing mapping, and which rules are dropped for synthesized state -
|
|
367
|
+
is documented in [validation-engine/API.md](../validation-engine/API.md#validating-an-aws-cli-command).
|
|
368
|
+
|
|
369
|
+
## Report Types
|
|
370
|
+
|
|
371
|
+
### ValidationReport
|
|
372
|
+
|
|
373
|
+
`validate_template` always returns a `ValidationReport` - a template syntax failure is returned as a report with
|
|
374
|
+
`ReportStatus.ERROR` and an `F1101` diagnostic; only infrastructure or engine failures raise:
|
|
375
|
+
|
|
376
|
+
```python
|
|
377
|
+
@dataclass
|
|
378
|
+
class ValidationReport:
|
|
379
|
+
file_path: str
|
|
380
|
+
status: ReportStatus # OK, ANALYSIS_INCOMPLETE (findings may be omitted), or ERROR (pipeline failure)
|
|
381
|
+
version: str
|
|
382
|
+
metadata: ReportMetadata
|
|
383
|
+
performance: PerformanceMetrics
|
|
384
|
+
diagnostics: list[Diagnostic]
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
Every finding is a `Diagnostic` (see [Diagnostic](#diagnostic)). Its enrichment fields - `documentation_url`,
|
|
388
|
+
`rule_description`, `phase` (`PARSE` | `SCHEMA` | `LINT`), and `context` (`ViolationContext` with `actual_value`,
|
|
389
|
+
`expected_constraint`, `resolution_source`, etc.) - are populated only at `detail_level` `DETAILED` (the default);
|
|
390
|
+
validating at `STANDARD` leaves them `None`, keeping the base diagnostic fields.
|
|
391
|
+
|
|
392
|
+
`metadata` carries the summary counts, the number of suppressed diagnostics, the resources scanned and rules
|
|
393
|
+
evaluated, the strict flag and severity threshold used, and optional budget-exhaustion records. Each budget-exhaustion
|
|
394
|
+
record retains a stable machine-readable kind and also includes a human-readable description sentence, the numeric
|
|
395
|
+
limit, and whether that specific exhaustion makes analysis incomplete. `requiredPropertyCombinations` is context-only,
|
|
396
|
+
so its `analysis_incomplete` value is `False` and the report can remain `ReportStatus.OK`.
|
|
397
|
+
|
|
398
|
+
### Diagnostic
|
|
399
|
+
|
|
400
|
+
```python
|
|
401
|
+
@dataclass
|
|
402
|
+
class Diagnostic:
|
|
403
|
+
rule_id: str # e.g. "E3012", "F1001", "W3010"
|
|
404
|
+
severity: Severity # FATAL, ERROR, WARN, INFO, DEBUG
|
|
405
|
+
message: str
|
|
406
|
+
source: RuleOrigin # SCHEMA, CFN_LINT, ENGINE, CUSTOM, GUARD
|
|
407
|
+
entity: Entity | None # the named template entity the finding targets, if any
|
|
408
|
+
property_path: str | None # e.g. "Properties.BucketName", or section-absolute like "Parameters/MyParam/Type"
|
|
409
|
+
suggested_fix: str | None
|
|
410
|
+
category: str | None
|
|
411
|
+
start_line: int | None
|
|
412
|
+
start_column: int | None
|
|
413
|
+
end_line: int | None
|
|
414
|
+
end_column: int | None
|
|
415
|
+
related_resources: list[RelatedResource] | None
|
|
416
|
+
condition_scenario: dict[str, bool] | None # condition truth assignment that triggers this diagnostic
|
|
417
|
+
# Enrichment fields: populated at detail_level DETAILED (the default), None at STANDARD.
|
|
418
|
+
documentation_url: str | None
|
|
419
|
+
rule_description: str | None
|
|
420
|
+
phase: Phase | None # PARSE | SCHEMA | LINT - pipeline stage that produced the finding
|
|
421
|
+
context: ViolationContext | None # actual_value, expected_constraint, resolution_source, etc.
|
|
422
|
+
|
|
423
|
+
# The named template entity a diagnostic is attributed to. The entity type is the
|
|
424
|
+
# singular form of the top-level template section the entity is declared in.
|
|
425
|
+
@dataclass
|
|
426
|
+
class Entity:
|
|
427
|
+
logical_id: str # logical ID as declared in the template
|
|
428
|
+
entity_type: EntityType
|
|
429
|
+
resource_type: str | None = None # CloudFormation type, when the entity is a resource whose type is known
|
|
430
|
+
|
|
431
|
+
class EntityType(enum.Enum):
|
|
432
|
+
RESOURCE, PARAMETER, OUTPUT, MAPPING, METADATA, RULE, CONDITION, TRANSFORM, FORMAT_VERSION, DESCRIPTION
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
`Severity`, `RuleOrigin`, `DetailLevel`, and `ReportStatus` are `enum.Enum` classes; use `.name` for the string form
|
|
436
|
+
(`Severity.WARN.name == "WARN"`).
|