只使用Terraform在开发环境中创建资源
首先
当使用Terraform管理多个环境时,我想要包含在Terraform管理中创建IAM用户以配置CircleCI的AWS权限!以下是仅在dev环境中创建资源的方法。我在验证Terraform版本为0.11.9。
做法 (zuò fǎ)
count = “${terraform.workspace == “dev” ? “1” : “0”}”
根据条件判断来规定count的值,当count为0时不创建,为1时创建一个。
terraform env new dev
terraform env select dev # これすることでterraform.workspaceがdevになります
- 以下は全体のコードです
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}"
}
variable "name" {
default = "sample"
}
variable "bucket" {
default = "sample"
}
最后
只需使用terraform env select选择环境,就可以轻松创建用于CircleCI部署的IAM用户。我想用Terraform来管理所有资源,会很方便!