Policy as Code automates enforcement and implementation via the policy to find out logical inconsistencies , syntax error, missing dependencies before they go into the Infrastructure Provisioning process through the IAC. They act as guardrails and are proven to be valuable in Infra code testability. Policy as code ensures consistency and accountability with version control and transparency improving development efficiency. They reduce implementation error and deployment time along with prevention of drifts early in the development
Some Examples of Policy as Code are
- Hashicorp Sentinel
- Pulumi Crossguard
- Open Policy Agent
- Cloudformation Guard
In this blog we will be talking about CloudFormation Guard which is an open source policy as code evaluation tool
The AWS’s Guard command line interface (CLI) provides a simple-to-use, yet powerful and expressive, declarative domain-specific language (DSL) that you can use to express policy as code. Also you can use CLI commands to validate structured hierarchical JSON or YAML data against those rules. Guard also provides a built-in unit testing framework to verify that your rules work as intended.
Cfn-lint is like a typescript for js. It does thorough inspection of the template instruction. The linter shows errors on wrong formats.
Cfn guard is opensource cli. For example Creating rules to ensure the cryptographic keys for ec2 is always set or The volume of ec2 is always less than 20 GB and is encrypted.
Installing the Cloudformation Guard CLI
Set the path (optionally in ~/.bashconfig)
Check if cfn-guard is installed
Rules are made of clauses based upon the Guard domain-specific language (DSL) that an be validated for json or yaml structures. Rules can be on plaintext and do not require an extension.
Guide to Migrating if you’re already using cfn-guard 1.0 to 2.0 or later.
Unit Testing Syntax
Validating multiple rules against a template.
Lets get started with ec2 volume size
We are saving this sample template to create a ec2 volume of type gp2 with size 10 gb
Creating a Rule
Now let’s create a rule that says the size should be less than or equal to 30 gb and type should be gp2
Now lets validate with the cfn-guard cli
The Result for failed test because our yaml contains gp2 and the rule contains gp3
The guard test failed because gp2 was compared with gp3. The test passes when the value is gp2
Now let’s also modify the volume size to <= 40
It gives another error
The IAC can now be controlled with a policy to enforce organizational compliance. In this way we have established a guardrail with policy as code leveraging AWS CloudFormation Guard.