template-validator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTemplate Validator
模板验证工具
Quick Start
快速开始
Validate CloudFormation templates for syntax errors, security issues, and adherence to best practices before deployment.
在部署前对CloudFormation模板进行语法错误、安全问题及最佳实践合规性验证。
Instructions
操作步骤
Step 1: Validate template syntax
步骤1:验证模板语法
bash
undefinedbash
undefinedBasic validation
Basic validation
aws cloudformation validate-template
--template-body file://template.yaml
--template-body file://template.yaml
aws cloudformation validate-template
--template-body file://template.yaml
--template-body file://template.yaml
Validation with parameters
Validation with parameters
aws cloudformation validate-template
--template-body file://template.yaml
--parameters ParameterKey=Param1,ParameterValue=Value1
--template-body file://template.yaml
--parameters ParameterKey=Param1,ParameterValue=Value1
**Check for:**
- Valid YAML/JSON syntax
- Required template sections
- Valid resource types
- Correct intrinsic function usage
- Parameter referencesaws cloudformation validate-template
--template-body file://template.yaml
--parameters ParameterKey=Param1,ParameterValue=Value1
--template-body file://template.yaml
--parameters ParameterKey=Param1,ParameterValue=Value1
**检查内容:**
- 有效的YAML/JSON语法
- 必填模板章节
- 有效的资源类型
- 正确使用内置函数
- 参数引用正确性Step 2: Use cfn-lint for comprehensive checks
步骤2:使用cfn-lint进行全面检查
bash
undefinedbash
undefinedInstall cfn-lint
Install cfn-lint
pip install cfn-lint
pip install cfn-lint
Validate template
Validate template
cfn-lint template.yaml
cfn-lint template.yaml
Validate with specific rules
Validate with specific rules
cfn-lint template.yaml --ignore-checks W
cfn-lint template.yaml --ignore-checks W
Output as JSON
Output as JSON
cfn-lint template.yaml --format json
**cfn-lint checks:**
- Template structure
- Resource properties
- Best practices
- Security issues
- Regional availabilitycfn-lint template.yaml --format json
**cfn-lint检查项:**
- 模板结构
- 资源属性
- 最佳实践合规性
- 安全问题
- 区域可用性Step 3: Security validation
步骤3:安全验证
Check IAM policies:
yaml
undefined检查IAM策略:
yaml
undefinedReview for overly permissive policies
Review for overly permissive policies
Resources:
Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: AppPolicy
PolicyDocument:
Statement:
# Avoid wildcards
- Effect: Allow
Action: s3:* # Too permissive!
Resource: '*' # Too broad!
**Better approach:**
```yaml
Policies:
- PolicyName: AppPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
Resource: !Sub '${MyBucket.Arn}/*'Check security groups:
yaml
undefinedResources:
Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: AppPolicy
PolicyDocument:
Statement:
# Avoid wildcards
- Effect: Allow
Action: s3:* # Too permissive!
Resource: '*' # Too broad!
**优化方案:**
```yaml
Policies:
- PolicyName: AppPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
Resource: !Sub '${MyBucket.Arn}/*'检查安全组:
yaml
undefinedAvoid open access
Avoid open access
Resources:
SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
SecurityGroupIngress:
# Don't allow 0.0.0.0/0 for SSH
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0 # Security risk!
**Better approach:**
```yaml
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 10.0.0.0/8 # Restrict to internal networkResources:
SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
SecurityGroupIngress:
# Don't allow 0.0.0.0/0 for SSH
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0 # Security risk!
**优化方案:**
```yaml
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 10.0.0.0/8 # Restrict to internal networkStep 4: Check resource dependencies
步骤4:检查资源依赖
Verify DependsOn usage:
yaml
Resources:
# Explicit dependency needed
Instance:
Type: AWS::EC2::Instance
DependsOn: InternetGatewayAttachment
Properties:
# ...
# Implicit dependency via Ref
SecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: !Ref SecurityGroup # Implicit dependencyCheck for circular dependencies:
- Review all DependsOn relationships
- Check Ref and GetAtt usage
- Verify no circular references
验证DependsOn的使用:
yaml
Resources:
# Explicit dependency needed
Instance:
Type: AWS::EC2::Instance
DependsOn: InternetGatewayAttachment
Properties:
# ...
# Implicit dependency via Ref
SecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: !Ref SecurityGroup # Implicit dependency检查循环依赖:
- 检查所有DependsOn关系
- 检查Ref和GetAtt的使用
- 确认无循环引用
Step 5: Validate best practices
步骤5:验证最佳实践
Use specific resource names:
yaml
undefined使用明确的资源名称:
yaml
undefinedGood
Good
Resources:
WebServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Resources:
WebServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Avoid generic names
Avoid generic names
Resources:
SecurityGroup1:
Type: AWS::EC2::SecurityGroup
**Add descriptions:**
```yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Web application infrastructure with ALB and Auto Scaling
Parameters:
InstanceType:
Type: String
Description: EC2 instance type for web serversUse tags:
yaml
Resources:
Instance:
Type: AWS::EC2::Instance
Properties:
Tags:
- Key: Name
Value: !Sub '${AWS::StackName}-WebServer'
- Key: Environment
Value: !Ref Environment
- Key: ManagedBy
Value: CloudFormationResources:
SecurityGroup1:
Type: AWS::EC2::SecurityGroup
**添加描述信息:**
```yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Web application infrastructure with ALB and Auto Scaling
Parameters:
InstanceType:
Type: String
Description: EC2 instance type for web servers使用标签:
yaml
Resources:
Instance:
Type: AWS::EC2::Instance
Properties:
Tags:
- Key: Name
Value: !Sub '${AWS::StackName}-WebServer'
- Key: Environment
Value: !Ref Environment
- Key: ManagedBy
Value: CloudFormationCommon Validation Checks
常见验证检查项
Syntax Validation
语法验证
Valid YAML structure:
yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Template description
Parameters:
# Parameters section
Resources:
# Resources section (required)
Outputs:
# Outputs sectionIntrinsic functions:
yaml
undefined有效的YAML结构:
yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Template description
Parameters:
# Parameters section
Resources:
# Resources section (required)
Outputs:
# Outputs section内置函数:
yaml
undefinedCorrect
Correct
Value: !Ref MyResource
Value: !GetAtt MyResource.Attribute
Value: !Sub '${MyResource}'
Value: !Ref MyResource
Value: !GetAtt MyResource.Attribute
Value: !Sub '${MyResource}'
Incorrect
Incorrect
Value: Ref: MyResource # Wrong syntax
Value: !GetAtt MyResource # Missing attribute
undefinedValue: Ref: MyResource # Wrong syntax
Value: !GetAtt MyResource # Missing attribute
undefinedSecurity Validation
安全验证
IAM policies:
- No wildcards in actions unless necessary
- Specific resources instead of '*'
- Least privilege principle
- No hardcoded credentials
Security groups:
- No 0.0.0.0/0 for sensitive ports (22, 3389, 3306, 5432)
- Specific port ranges
- Documented ingress rules
Encryption:
- Enable encryption for S3 buckets
- Enable encryption for EBS volumes
- Enable encryption for RDS instances
- Use KMS keys for sensitive data
IAM策略:
- 除非必要,否则不要在操作中使用通配符
- 使用具体资源而非'*'
- 遵循最小权限原则
- 不使用硬编码凭证
安全组:
- 敏感端口(22、3389、3306、5432)不允许0.0.0.0/0访问
- 使用具体端口范围
- 记录入站规则
加密:
- 为S3存储桶启用加密
- 为EBS卷启用加密
- 为RDS实例启用加密
- 对敏感数据使用KMS密钥
Resource Validation
资源验证
Required properties:
yaml
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
# BucketName is optional but recommended
BucketName: !Sub '${AWS::StackName}-bucket'Valid property values:
yaml
Resources:
Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: t3.micro # Must be valid instance type
ImageId: ami-12345678 # Must be valid AMI ID必填属性:
yaml
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
# BucketName is optional but recommended
BucketName: !Sub '${AWS::StackName}-bucket'有效的属性值:
yaml
Resources:
Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: t3.micro # Must be valid instance type
ImageId: ami-12345678 # Must be valid AMI IDValidation Tools
验证工具
AWS CLI
AWS CLI
bash
undefinedbash
undefinedValidate template
Validate template
aws cloudformation validate-template
--template-body file://template.yaml
--template-body file://template.yaml
aws cloudformation validate-template
--template-body file://template.yaml
--template-body file://template.yaml
Create change set (validates before applying)
Create change set (validates before applying)
aws cloudformation create-change-set
--stack-name my-stack
--change-set-name my-changes
--template-body file://template.yaml
--stack-name my-stack
--change-set-name my-changes
--template-body file://template.yaml
aws cloudformation create-change-set
--stack-name my-stack
--change-set-name my-changes
--template-body file://template.yaml
--stack-name my-stack
--change-set-name my-changes
--template-body file://template.yaml
Describe change set
Describe change set
aws cloudformation describe-change-set
--stack-name my-stack
--change-set-name my-changes
--stack-name my-stack
--change-set-name my-changes
undefinedaws cloudformation describe-change-set
--stack-name my-stack
--change-set-name my-changes
--stack-name my-stack
--change-set-name my-changes
undefinedcfn-lint
cfn-lint
bash
undefinedbash
undefinedBasic validation
Basic validation
cfn-lint template.yaml
cfn-lint template.yaml
Ignore warnings
Ignore warnings
cfn-lint template.yaml --ignore-checks W
cfn-lint template.yaml --ignore-checks W
Specific regions
Specific regions
cfn-lint template.yaml --regions us-east-1 us-west-2
cfn-lint template.yaml --regions us-east-1 us-west-2
Custom rules
Custom rules
cfn-lint template.yaml --append-rules custom-rules/
undefinedcfn-lint template.yaml --append-rules custom-rules/
undefinedcfn-nag
cfn-nag
bash
undefinedbash
undefinedInstall cfn-nag
Install cfn-nag
gem install cfn-nag
gem install cfn-nag
Scan template
Scan template
cfn_nag_scan --input-path template.yaml
cfn_nag_scan --input-path template.yaml
Scan with rules
Scan with rules
cfn_nag_scan --input-path template.yaml --deny-list-path rules.txt
undefinedcfn_nag_scan --input-path template.yaml --deny-list-path rules.txt
undefinedTaskCat
TaskCat
bash
undefinedbash
undefinedInstall taskcat
Install taskcat
pip install taskcat
pip install taskcat
Test template
Test template
taskcat test run
taskcat test run
Configuration in .taskcat.yml
Configuration in .taskcat.yml
project:
name: my-project
regions:
- us-east-1
- us-west-2
tests:
default:
template: template.yaml
parameters:
InstanceType: t3.micro
undefinedproject:
name: my-project
regions:
- us-east-1
- us-west-2
tests:
default:
template: template.yaml
parameters:
InstanceType: t3.micro
undefinedValidation Checklist
验证检查清单
Template structure:
- Valid YAML/JSON syntax
- AWSTemplateFormatVersion present
- Description provided
- Resources section present
Parameters:
- Descriptive names
- Descriptions provided
- Validation constraints (AllowedValues, AllowedPattern)
- Appropriate defaults
- NoEcho for sensitive values
Resources:
- Descriptive logical IDs
- Required properties present
- Valid property values
- Appropriate DependsOn usage
- Tags applied
Security:
- IAM policies follow least privilege
- No hardcoded credentials
- Security groups restrict access
- Encryption enabled where appropriate
- No overly permissive policies
Outputs:
- Descriptive names
- Descriptions provided
- Appropriate exports
- Conditional outputs where needed
Best practices:
- Consistent naming convention
- Appropriate use of parameters
- Cross-stack references via exports
- Proper error handling
- Documentation in descriptions
模板结构:
- 有效的YAML/JSON语法
- 存在AWSTemplateFormatVersion
- 提供描述信息
- 存在Resources章节
参数:
- 名称具有描述性
- 提供描述信息
- 配置验证约束(AllowedValues、AllowedPattern)
- 设置合适的默认值
- 敏感值使用NoEcho
资源:
- 逻辑ID具有描述性
- 存在必填属性
- 属性值有效
- 合理使用DependsOn
- 应用标签
安全:
- IAM策略遵循最小权限原则
- 无硬编码凭证
- 安全组限制访问
- 按需启用加密
- 无过度宽松的策略
输出:
- 名称具有描述性
- 提供描述信息
- 合理配置导出
- 按需使用条件输出
最佳实践:
- 命名约定一致
- 合理使用参数
- 通过导出实现跨栈引用
- 正确处理错误
- 在描述中添加文档
Advanced
进阶内容
For detailed information, see:
- Security Best Practices - Comprehensive security validation guide
- Validation Rules - Complete list of validation rules and checks
如需详细信息,请参阅:
- Security Best Practices - 全面的安全验证指南
- Validation Rules - 完整的验证规则与检查项列表