template-validator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Template 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
undefined
bash
undefined

Basic validation

Basic validation

aws cloudformation validate-template
--template-body file://template.yaml
aws cloudformation validate-template
--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

**Check for:**
- Valid YAML/JSON syntax
- Required template sections
- Valid resource types
- Correct intrinsic function usage
- Parameter references
aws cloudformation validate-template
--template-body file://template.yaml
--parameters ParameterKey=Param1,ParameterValue=Value1

**检查内容:**
- 有效的YAML/JSON语法
- 必填模板章节
- 有效的资源类型
- 正确使用内置函数
- 参数引用正确性

Step 2: Use cfn-lint for comprehensive checks

步骤2:使用cfn-lint进行全面检查

bash
undefined
bash
undefined

Install 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 availability
cfn-lint template.yaml --format json

**cfn-lint检查项:**
- 模板结构
- 资源属性
- 最佳实践合规性
- 安全问题
- 区域可用性

Step 3: Security validation

步骤3:安全验证

Check IAM policies:
yaml
undefined
检查IAM策略:
yaml
undefined

Review 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
undefined
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!

**优化方案:**
```yaml
Policies:
  - PolicyName: AppPolicy
    PolicyDocument:
      Statement:
        - Effect: Allow
          Action:
            - s3:GetObject
            - s3:PutObject
          Resource: !Sub '${MyBucket.Arn}/*'
检查安全组:
yaml
undefined

Avoid 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 network
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!

**优化方案:**
```yaml
SecurityGroupIngress:
  - IpProtocol: tcp
    FromPort: 22
    ToPort: 22
    CidrIp: 10.0.0.0/8  # Restrict to internal network

Step 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 dependency
Check 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
undefined

Good

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 servers
Use 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: CloudFormation
Resources: 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: CloudFormation

Common Validation Checks

常见验证检查项

Syntax Validation

语法验证

Valid YAML structure:
yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Template description

Parameters:
  # Parameters section

Resources:
  # Resources section (required)

Outputs:
  # Outputs section
Intrinsic functions:
yaml
undefined
有效的YAML结构:
yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Template description

Parameters:
  # Parameters section

Resources:
  # Resources section (required)

Outputs:
  # Outputs section
内置函数:
yaml
undefined

Correct

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
undefined
Value: Ref: MyResource # Wrong syntax Value: !GetAtt MyResource # Missing attribute
undefined

Security 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 ID

Validation Tools

验证工具

AWS CLI

AWS CLI

bash
undefined
bash
undefined

Validate template

Validate template

aws cloudformation validate-template
--template-body file://template.yaml
aws cloudformation validate-template
--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
aws cloudformation create-change-set
--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
undefined
aws cloudformation describe-change-set
--stack-name my-stack
--change-set-name my-changes
undefined

cfn-lint

cfn-lint

bash
undefined
bash
undefined

Basic 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/
undefined
cfn-lint template.yaml --append-rules custom-rules/
undefined

cfn-nag

cfn-nag

bash
undefined
bash
undefined

Install 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
undefined
cfn_nag_scan --input-path template.yaml --deny-list-path rules.txt
undefined

TaskCat

TaskCat

bash
undefined
bash
undefined

Install 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
undefined
project: name: my-project regions: - us-east-1 - us-west-2 tests: default: template: template.yaml parameters: InstanceType: t3.micro
undefined

Validation 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 - 完整的验证规则与检查项列表