4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Terraformを使ってdev環境でのみリソースを作成する

Last updated at Posted at 2018-10-23

はじめに

Terraformで複数環境を管理しているときに、CircleCIのAWS Permissionsに設定するためのIAMユーザーの作成もTerraform管理に含めたい!… ということで、dev環境でのみリソースを作成する方法です。
Terraformのバージョンは0.11.9で検証しています。

やり方

count = "${terraform.workspace == "dev" ? "1" : "0"}"
countは0のときは作成せず、1のときは一つ作成するという仕組みを利用します

terraform env new dev
terraform env select dev # これすることでterraform.workspaceがdevになります
  • 以下は全体のコードです
deployer_iam_user.tf
esource "aws_iam_user" "user" {
  count = "${terraform.workspace == "dev" ? "1" : "0"}"
  name = "${var.name}-deployer"
}

data "aws_iam_policy_document" "deployer_policy_document" {
  statement {
    actions = [
      "s3:ListBucket"
    ]

    resources = [
      "arn:aws:s3:::${var.bucket}"
    ]

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

      values = [
        ""
      ]
    }
  }

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

    resources = [
      "arn:aws:s3:::${var.bucket}",
    ]

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

      values = [
        "dev",
        "dev/*",
        "stg",
        "stg/*",
        "pro",
        "pro/*"
      ]
    }
  }

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

    resources = [
      "arn:aws:s3:::${var.bucket}/dev/*",
      "arn:aws:s3:::${var.bucket}/stg/*",
      "arn:aws:s3:::${var.bucket}/pro/*",
    ]
  }
}

resource "aws_iam_policy" "deployer_policy" {
  count = "${terraform.workspace == "dev" ? "1" : "0"}"
  name        = "${var.name}-deployer-policy"
  description = "${var.name} deployer policy"
  policy = "${data.aws_iam_policy_document.deployer_policy_document.json}"
}

resource "aws_iam_policy_attachment" "deployer-attach" {
  count = "${terraform.workspace == "dev" ? "1" : "0"}"
  name       = "${var.name}-deployer-attachment"
  users      = ["${aws_iam_user.user.id}"]
  policy_arn = "${aws_iam_policy.deployer_policy.arn}"
}

resource "aws_iam_access_key" "key" {
  count = "${terraform.workspace == "dev" ? "1" : "0"}"
  user = "${aws_iam_user.user.name}"
}
variables.tf
variable "name" {
  default = "sample"
}

variable "bucket" {
  default = "sample"
}

最後に

terraform env selectで環境を選択するだけでお手軽にCircleCIデプロイ用のIAMユーザーを作成することができました。
こんな感じですべてのリソースをTerraformで管理したいですね!

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?