Skip to content

Instantly share code, notes, and snippets.

@kenseii
Created December 2, 2022 02:55
Show Gist options
  • Save kenseii/37f19a22af2ab084e89ab9d6817734a1 to your computer and use it in GitHub Desktop.
Save kenseii/37f19a22af2ab084e89ab9d6817734a1 to your computer and use it in GitHub Desktop.
Automating the IAM role connection to MongoDB atlas
import os
from pulumi import get_stack, get_project # so that each resource has a project & staging/dev... in AWS console
import pulumi_mongodbatlas as mongodbatlas
ACCOUNT_ID = os.environ["ACCOUNT_ID"]
ATLAS_PROJECT_ID = os.environ["ATLAS_PROJECT_ID"]
my_func_role_arn = f"arn:aws:iam::{ACCOUNT_ID}:role/{get_project()}-{get_stack()}-my-func-iam-role"
lambda_cloud_provider_access = mongodbatlas.CloudProviderAccess(
f"{get_project()}-{get_stack()}-my-func-database-authorization",
iam_assumed_role_arn=my_func_role_arn,
project_id=ATLAS_PROJECT_ID,
provider_name="AWS"
)
iam_for_lambda = iam.Role(
f"{get_project()}-{get_stack()}-my-func-iam-role",
name=f"{get_project()}-{get_stack()}-my-func-iam-role",
assume_role_policy={
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
},
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::SOMETHING:root"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"sts:ExternalId": lambda_cloud_provider_access.atlas_assumed_role_external_id
}
}
}
]
})
lambda_role_authorization = mongodbatlas.CloudProviderAccessAuthorization(
f"{get_project()}-{get_stack()}-my-func-role-access-authorization",
project_id=ATLAS_PROJECT_ID,
aws=mongodbatlas.CloudProviderAccessAuthorizationAwsArgs(iam_assumed_role_arn=my_func_role_arn),
role_id= lambda_cloud_provider_access.role_id)
get_user = mongodbatlas.DatabaseUser(f"{get_project()}-{get_stack()}-database-user",
username=iam_for_lambda.arn,
project_id=ATLAS_PROJECT_ID,
auth_database_name="$external",
aws_iam_type="ROLE",
roles=[mongodbatlas.DatabaseUserRoleArgs(
role_name="readWriteAnyDatabase",
database_name="admin",
)],
labels=[mongodbatlas.DatabaseUserLabelArgs(
key="%s",
value="%s",
)],
scopes=[mongodbatlas.DatabaseUserScopeArgs(
name="Cluster0",
type="CLUSTER",
)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment