Terraforming S3 Policies to an EC2 IAM Role

All the buzzwords and AWS abbreviations! Another post where I just want to note down something I thought was cool. Actually I have a lot more terraform related I'd like to write down, hopefully I will do more of it in the future.

Yesterday night I was doing some maintenance updating our loadbalancer. While I was at it I found a way to get rid of some previously hardcoded IAM credentials that were being used to upload backups of our HAProxy config via aws-cli to an S3 bucket.

Instead of creating a new IAM user with a policy to interact with a specific bucket, you can just give that policy to the EC2 instance's IAM role. Then inside the EC2 instance AWS cli is already installed with credentials for that role. At least on AWS Linux, may be different on other OSes. After giving the policy to the role it automagically just worked to interact with bucket without adding any extra credentials.

To add the policies to the role via terraform was super easy, it just needed the following:

resource "aws_iam_role_policy" "s3-gateway-buckets" {
  name   = "s3-gateway-buckets"
  role   = "${aws_iam_role.gateway.id}"
  policy = "${data.aws_iam_policy_document.s3-gateway-buckets.json}"
}

data "aws_iam_policy_document" "s3-gateway-buckets" {
  statement {
    effect = "Allow"

    actions = [
      "s3:*",
    ]

    resources = [
      "arn:aws:s3:::some-backup",
      "arn:aws:s3:::some-backup/*"
    ]
  }
}