NEW: iam user module

This commit is contained in:
xpk 2022-09-15 16:31:30 +08:00
parent a4bdee471e
commit 06233f9ae0
Signed by: xpk
GPG Key ID: CD4FF6793F09AB86
3 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,37 @@
# iam-user module
Module for creating IAM user. Credentials, if any, will be stored in secretsmanager
## Example
```terraform
module iam-user {
source = "../../modules/security_identity_compliance/iam-user"
default-tags = local.default-tags
iam-user-name = var.iam-user-name
iam-user-policy = data.aws_iam_policy_document.user-policy.json
create-access-key = false
create-password = false
managed-policy-arns = ["arn:aws:iam::aws:policy/job-function/ViewOnlyAccess"]
}
data aws_iam_policy_document user-policy {
statement {
sid = "ManageOwnCredentials"
actions = [
"iam:ChangePassword",
"iam:CreateAccessKey",
"iam:DeleteAccessKey",
"iam:ListAccessKey",
"iam:CreateVirtualMFADevice",
"iam:EnableMFADevice",
"iam:ListMFA*",
"iam:ListVirtualMFA*",
"iam:ResyncMFADevice"
]
effect = "Allow"
resources = ["arn:aws:iam::account-id:user/${var.iam-user-name}"]
}
}
```

View File

@ -0,0 +1,50 @@
resource "aws_iam_user" "iam-user" {
name = var.iam-user-name
tags = var.default-tags
force_destroy = true
}
resource "aws_iam_access_key" "iam-user-access-key" {
count = var.create-access-key ? 1 : 0
user = aws_iam_user.iam-user.name
}
resource "aws_iam_user_policy" "iam-user-policy" {
name = "SelfServiceAccess"
user = aws_iam_user.iam-user.name
policy = var.iam-user-policy
}
resource "aws_iam_user_policy_attachment" "iam-user-managed-policies" {
for_each = toset(var.managed-policy-arns)
user = aws_iam_user.iam-user.name
policy_arn = each.value
}
resource "random_password" "iam-user-pass" {
count = var.create-password ? 1 : 0
length = 20
special = true
}
resource "aws_iam_user_login_profile" "iam-user-profile" {
count = var.create-password ? 1 : 0
user = aws_iam_user.iam-user.name
}
resource "aws_secretsmanager_secret" "secretmanager" {
count = var.create-access-key || var.create-password ? 1 : 0
name = "IamUserCredential-${var.iam-user-name}"
description = "AWS resource credential"
tags = var.default-tags
}
resource "aws_secretsmanager_secret_version" "iam-user-secret" {
count = var.create-access-key || var.create-password ? 1 : 0
secret_id = aws_secretsmanager_secret.secretmanager[0].id
secret_string = jsonencode(
{ "ConsolePassword" : length(random_password.iam-user-pass) > 0 ? random_password.iam-user-pass[0].result : "NotSet",
"AccessKeyId" : length(aws_iam_access_key.iam-user-access-key) > 0 ? aws_iam_access_key.iam-user-access-key[0].id : "NotSet",
"KeySecret" : length(aws_iam_access_key.iam-user-access-key) > 0 ? aws_iam_access_key.iam-user-access-key[0].secret : "NotSet"
})
}

View File

@ -0,0 +1,10 @@
variable iam-user-name {}
variable iam-user-policy {}
variable create-access-key {
type = bool
}
variable create-password {
type = bool
}
variable default-tags {}
variable managed-policy-arns {}