使用Terraform进行管理,AWS IAM组和用户
我学习了AWS IAM,并在控制台上学会了创建的方法,所以我实践了使用Terraform进行创建和管理的方式,并总结了一篇文章。关于Terraform项目的设置,我已经单独发表了一篇文章,请务必阅读。
我的设计
在AWS中,推荐的做法是创建群组,并为群组授予权限,然后将用户与群组关联起来,而不是为每个单独的IAM用户授予权限。这样可以更轻松地管理,尤其是当组织变大并且使用AWS资源的成员增加时。在本次情景中,我们将创建IAM群组和策略,然后创建用户并将其关联起来。
-
- 開発者用のIAMグループを作成する
EC2(VPC)、ALB、Auto Scaling、RDS、S3のアクセスが可能
開発者であるIAM ユーザーは上記のグループに紐づけられる
Terraform项目的配置
.
├── docker-compose.yml // Terraform実行のためのDocker環境
└── src
├── module_aws.tf
├── modules
│ └── aws
│ ├── iam_group.tf
│ └── iam_user.tf
└── providers.tf
将来,考虑到可能使用其他服务提供商(例如GCP),我们将其作为一个模块分开。
我是IAM组,正在创建策略。
module "aws" {
source = "./modules/aws"
}
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.44.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_iam_group" "developers" {
name = "developers"
path = "/users/"
}
我认为可以执行”terraform plan”来进行确认。
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# module.aws.aws_iam_group.developers will be created
+ resource "aws_iam_group" "developers" {
+ arn = (known after apply)
+ id = (known after apply)
+ name = "developers"
+ path = "/users/"
+ unique_id = (known after apply)
}
# module.aws.aws_iam_group_policy.developer_policy will be created
+ resource "aws_iam_group_policy" "developer_policy" {
+ group = "developers"
+ id = (known after apply)
+ name = "developer_policy"
+ policy = jsonencode(
{
+ Statement = [
+ {
+ Action = [
+ "rds:*",
+ "s3:*",
+ "ec2:*",
+ "elasticloadbalancing:*",
+ "autoscaling-plans:*",
]
+ Effect = "Allow"
+ Resource = "*"
},
]
+ Version = "2012-10-17"
}
)
}
Plan: 2 to add, 0 to change, 0 to destroy.
创建 IAM 用户,并将其添加到组中。
resource "aws_iam_user" "example" {
name = "example"
path = "/"
force_destroy = true
}
// 作成したIAMユーザーを、グループに追加する
resource "aws_iam_user_group_membership" "example" {
user = aws_iam_user.example.name
groups = [
aws_iam_group.developers.name
]
}
这个也可以通过terraform plan进行确认。
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# module.aws.aws_iam_user.example will be created
+ resource "aws_iam_user" "example" {
+ arn = (known after apply)
+ force_destroy = true
+ id = (known after apply)
+ name = "example"
+ path = "/"
+ tags_all = (known after apply)
+ unique_id = (known after apply)
}
# module.aws.aws_iam_user_group_membership.example will be created
+ resource "aws_iam_user_group_membership" "example" {
+ groups = [
+ "developers",
]
+ id = (known after apply)
+ user = "example"
}
Plan: 2 to add, 0 to change, 0 to destroy.
只要执行terraform apply,就会应用到目前为止所创建的内容。您可以从AWS控制台上的IAM页面进行确认。
还将继续整理其他资源。