Skip to content

Instantly share code, notes, and snippets.

@zytek
Last active February 5, 2020 19:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zytek/f87db81ddce89523a7c4afd2516319a9 to your computer and use it in GitHub Desktop.
Save zytek/f87db81ddce89523a7c4afd2516319a9 to your computer and use it in GitHub Desktop.
Terraform recipes for IAM and S3

Terraform AWS S3 bucket and IAM policy recipes

Relates to: https://gist.github.com/magnetikonline/6215d9e80021c1f8de12

Prerequisite: encrypted state

WARNING: all examples here also create user and access key - this secret key WILL be stored in state file. This is both convenient: secrets available upon running terraform output - and dangerous. You should use encrypted state storage (S3 encrypted bucket for example) if you go this route. Of course you don't have to create users this way - they can be referenced via data aws_iam_user or just a name attribute.

Read only access to path for user

resource "aws_iam_user" "joe" {
  name = "joe.foo
}

resource "aws_iam_access_key" "joe" {
  user = "${aws_iam_user.joe.name}"
}

data "aws_iam_policy_document" "s3-read-joe" {
  statement {
    actions = [
      "s3:GetObject*",
      "s3:ListMultipart*",
    ]

    resources = [
      "arn:aws:s3:::some-bucket/path1*",
      "arn:aws:s3:::some-bucket/path2/foo",
    ]
  }

  statement {
    actions = [
      "s3:ListBucket",
    ]

    resources = [
      "arn:aws:s3:::some-bucket",
    ]

    condition {
      test     = "StringLike"
      variable = "s3:prefix"

      values = [
        "path1/*",
        "path2/foo*",
      ]
    }
  }
}

resource "aws_iam_policy" "s3-joe" {
  name   = "s3-joe"
  policy = "${data.aws_iam_policy_document.s3-read-joe.json}"
}

resource "aws_iam_user_policy_attachment" "joe-a" {
  policy_arn = "${aws_iam_policy.s3-joe.arn}"
  user       = "${aws_iam_user.joe.name}"
}

output "joe-key" {
  value = "${aws_iam_access_key.joe.id}"
}

output "joe-secret" {
  value     = "${aws_iam_access_key.joe.secret}"
  sensitive = true
}
@magnetikonline
Copy link

Nice work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment