Skip to content

Instantly share code, notes, and snippets.

@yohanb
Created March 4, 2020 20:59
Show Gist options
  • Save yohanb/1e135a1604139534a255cb8d965fb566 to your computer and use it in GitHub Desktop.
Save yohanb/1e135a1604139534a255cb8d965fb566 to your computer and use it in GitHub Desktop.
Pulumi policy as code for Azure resource tagging.
import { ResourceValidationPolicy, ResourceValidationArgs } from "@pulumi/policy";
const requiredTags = ["owner", "environment"];
const isAzureResource = (args: ResourceValidationArgs): boolean => args.type.startsWith("azure");
// Subject to change since more types will fall through
const isAzureResourceTagFriendly = (args: ResourceValidationArgs): boolean => {
return (
!args.type.startsWith("azure:network/subnet") &&
!args.type.startsWith("azure:compute/extension")
);
};
const hasRequiredTags = (args: ResourceValidationArgs): boolean => {
if (!args.props.tags) {
return false;
}
requiredTags.forEach(tag => {
if (!args.props.tags.hasOwnProperty(tag)) {
return false;
}
});
return true;
};
const tagPolicy: ResourceValidationPolicy = {
name: "mandatory-tags",
description: "Tags must be set on resources.",
enforcementLevel: "mandatory",
validateResource: (args, reportViolation) => {
if (
isAzureResource(args) &&
isAzureResourceTagFriendly(args) &&
!hasRequiredTags(args)
) {
reportViolation(
`Set the following required tags: '${requiredTags.join(',')}'.`
);
}
}
};
export default tagPolicy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment