aws-cloudformation / cfn-lint

CloudFormation Linter
MIT No Attribution
2.45k stars 592 forks source link

How to add custom rule for DeletionPolicy on a resource #3205

Open yusuf963 opened 6 months ago

yusuf963 commented 6 months ago

cfn-lint 0.86.4

I have cloudformation template.json, and I want to add custom rule for "DeletionPolicy" attribute for a specific value which is "Retain" for a specific resource e.g EC2 or Route53

  "Resources": {
    "EC2Instance": {
      "DeletionPolicy": "Detele",
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "InstanceType": "m4.16xlarge",
        "ImageId": "ami-019a123123123",
        "KeyName": { "Ref": "KeyName" },
        "SecurityGroups": [
          { "Ref": "InstanceSecurityGroup" }
        ]
      }
    }
}

and I have .cfnlintrc and custom_rules.txt files in the root

templates:
  -  myapp/template.json
ignore_templates:
  - codebuild.yaml
include_checks:
  - I
  - E3012 # = type-checking

custom_rules.txt file, each rule in a single line:

AWS::EC2::Instance InstanceType NOT_EQUALS "m4.16xlarge" WARN "This is an expensive instance type, use t2.micro instead"
AWS::EC2::Instance DeletionPolicy NOT_EQUALS "Delete" ERROR "You should set DeletionPolicy to Retain"

I am aware of the custom rule format : <Resource Type> <Property[*]> <Operator> <Value> [Error Level] [Custom Error Message] and I know that "DeletionPolicy" is not a property on the Properties object of a resource. How is it possible to make the DeletionPolicy custom rule work? when I run cfn-lint I only get warning about the instance type and nothing about the DeletionPolicy value W9001 This is an expensive instance type, use t2.micro instead Instead as a desired outcome I should get : W9001 This is an expensive instance type, use t2.micro instead E12345 You should set DeletionPolicy to Retain

kddejong commented 4 months ago

We can't do this today. We would have to alter how our custom rules work. We can make this fairly easy using the full cfn-lint rules.