Skip to content

Instantly share code, notes, and snippets.

@jpancoast
Last active December 9, 2022 21:33
Show Gist options
  • Save jpancoast/13adacfba410da883bf46be7786f2dcf to your computer and use it in GitHub Desktop.
Save jpancoast/13adacfba410da883bf46be7786f2dcf to your computer and use it in GitHub Desktop.
How to limit AWS Security Group Changes to terraform only

The idea came up awhile back to see if there was a way to limit AWS Security Group changes to ONLY Terraform. This is one way I figured out how to do it. Another way might be to create a specific terraform user and put the restriction in the policy that way. Or maybe add the Condition to the below policy.

None of these methods are fool proof. Usernames, User Agents, etc. can be spoofed. But it's better than nothing to help prevent people from making changes via the AWS Console and getting out of sync with whatever IAC solution you're using.

While this is specific for security groups, it should be simple to modify it for preventing modification of other things as well. Also, the UA is incredibly strict, you should change it to some wildcard matching so it doesn't break when you're using a new Terraform. Or, if you're wacky, you could use this to restrict which version(s) of TF to use, but that would be nuts. Also the policy is probably not perfect, this is just an example, yo!

Here's the policy I tested with. It prevents changes being made via the UI and the AWS CLI.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        },
        {
            "Effect": "Deny",
            "Action": [
                "ec2:AuthorizeSecurityGroupIngress",
                "ec2:RevokeSecurityGroupIngress",
                "ec2:AuthorizeSecurityGroupEgress",
                "ec2:RevokeSecurityGroupEgress",
                "ec2:ModifySecurityGroupRules",
                "ec2:UpdateSecurityGroupRuleDescriptionsIngress",
                "ec2:UpdateSecurityGroupRuleDescriptionsEgress",
                "ec2:CreateSecurityGroup",
                "ec2:DeleteSecurityGroup"
            ],
            "Resource": "*",
            "Condition": {
                "StringNotLike": {
                    "aws:UserAgent": "APN/1.0 HashiCorp/1.0 Terraform/1.2.5 (+https://www.terraform.io) terraform-provider-aws/4.46.0 (+https://registry.terraform.io/providers/hashicorp/aws) aws-sdk-go/1.44.153 (go1.19.3; darwin; amd64)",
                    "aws:UserName": "aws-go-sdk-*"
                }
            }
        }
    ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment