You're absolutely right! For a complete setup, you'll need Cognito resources with custom user groups, and likely DynamoDB tables for storing additional user data and relationships. Here's the full Terraform configuration:
🔧 Complete Terraform Setup
✅ main.tf (Extended Version)
hcl Copy code
provider "aws" {
region = var.region
}
# ============================================
# COGNITO USER POOL & GROUPS
# ============================================
# Cognito User Pool
resource "aws_cognito_user_pool" "user_pool" {
name = "${var.app_name}-user-pool"
# Password policy
password_policy {
minimum_length = 8
require_lowercase = true
require_numbers = true
require_symbols = true
require_uppercase = true
}
# Username configuration
username_attributes = ["email"]
# Auto-verified attributes
auto_verified_attributes = ["email"]
# User attributes
schema {
attribute_data_type = "String"
name = "email"
required = true
mutable = true
}
schema {
attribute_data_type = "String"
name = "given_name"
required = true
mutable = true
}
schema {
attribute_data_type = "String"
name = "family_name"
required = true
mutable = true
}
# Custom attributes
schema {
attribute_data_type = "String"
name = "user_role"
required = false
mutable = true
}
tags = {
Environment = var.environment
}
}
# Cognito User Pool Client
resource "aws_cognito_user_pool_client" "user_pool_client" {
name = "${var.app_name}-client"
user_pool_id = aws_cognito_user_pool.user_pool.id
generate_secret = false
# OAuth flows
supported_identity_providers = ["COGNITO"]
explicit_auth_flows = [
"ALLOW_USER_SRP_AUTH",
"ALLOW_REFRESH_TOKEN_AUTH",
"ALLOW_USER_PASSWORD_AUTH"
]
# Token validity
access_token_validity = 1 # hours
id_token_validity = 1 # hours
refresh_token_validity = 30 # days
}
# Cognito Identity Pool
resource "aws_cognito_identity_pool" "identity_pool" {
identity_pool_name = "${var.app_name}-identity-pool"
allow_unauthenticated_identities = false
cognito_identity_providers {
client_id = aws_cognito_user_pool_client.user_pool_client.id
provider_name = aws_cognito_user_pool.user_pool.endpoint
server_side_token_check = false
}
tags = {
Environment = var.environment
}
}
# ============================================
# COGNITO USER GROUPS
# ============================================
# Admin Group
resource "aws_cognito_user_group" "admin_group" {
name = "admin"
user_pool_id = aws_cognito_user_pool.user_pool.id
description = "Administrator users"
precedence = 1
role_arn = aws_iam_role.admin_role.arn
}
# User Group
resource "aws_cognito_user_group" "user_group" {
name = "user"
user_pool_id = aws_cognito_user_pool.user_pool.id
description = "Regular users"
precedence = 2
role_arn = aws_iam_role.user_role.arn
}
# Manager Group
resource "aws_cognito_user_group" "manager_group" {
name = "manager"
user_pool_id = aws_cognito_user_pool.user_pool.id
description = "Manager users"
precedence = 1
role_arn = aws_iam_role.manager_role.arn
}
# ============================================
# DYNAMODB TABLES
# ============================================
# User Profiles Table
resource "aws_dynamodb_table" "user_profiles" {
name = "${var.app_name}-user-profiles"
billing_mode = "PAY_PER_REQUEST"
hash_key = "userId"
attribute {
name = "userId"
type = "S"
}
attribute {
name = "email"
type = "S"
}
global_secondary_index {
name = "email-index"
hash_key = "email"
}
tags = {
Environment = var.environment
}
}
# Organizations/Companies Table
resource "aws_dynamodb_table" "organizations" {
name = "${var.app_name}-organizations"
billing_mode = "PAY_PER_REQUEST"
hash_key = "organizationId"
attribute {
name = "organizationId"
type = "S"
}
tags = {
Environment = var.environment
}
}
# User-Organization Relationships
resource "aws_dynamodb_table" "user_organizations" {
name = "${var.app_name}-user-organizations"
billing_mode = "PAY_PER_REQUEST"
hash_key = "userId"
range_key = "organizationId"
attribute {
name = "userId"
type = "S"
}
attribute {
name = "organizationId"
type = "S"
}
attribute {
name = "role"
type = "S"
}
global_secondary_index {
name = "organization-role-index"
hash_key = "organizationId"
range_key = "role"
}
tags = {
Environment = var.environment
}
}
# ============================================
# APPSYNC API
# ============================================
resource "aws_appsync_graphql_api" "api" {
authentication_type = "AMAZON_COGNITO_USER_POOLS"
name = "${var.app_name}-api"
user_pool_config {
aws_region = var.region
default_action = "ALLOW"
user_pool_id = aws_cognito_user_pool.user_pool.id
}
additional_authentication_provider {
authentication_type = "AWS_IAM"
}
tags = {
Environment = var.environment
}
}
# GraphQL Schema
resource "aws_appsync_schema" "schema" {
api_id = aws_appsync_graphql_api.api.id
definition = file("${path.module}/schema.graphql")
}
# ============================================
# APPSYNC DATA SOURCES
# ============================================
# User Profiles Data Source
resource "aws_appsync_datasource" "user_profiles_ds" {
api_id = aws_appsync_graphql_api.api.id
name = "UserProfilesDataSource"
service_role_arn = aws_iam_role.appsync_role.arn
type = "AMAZON_DYNAMODB"
dynamodb_config {
table_name = aws_dynamodb_table.user_profiles.name
}
}
# Organizations Data Source
resource "aws_appsync_datasource" "organizations_ds" {
api_id = aws_appsync_graphql_api.api.id
name = "OrganizationsDataSource"
service_role_arn = aws_iam_role.appsync_role.arn
type = "AMAZON_DYNAMODB"
dynamodb_config {
table_name = aws_dynamodb_table.organizations.name
}
}
# User Organizations Data Source
resource "aws_appsync_datasource" "user_organizations_ds" {
api_id = aws_appsync_graphql_api.api.id
name = "UserOrganizationsDataSource"
service_role_arn = aws_iam_role.appsync_role.arn
type = "AMAZON_DYNAMODB"
dynamodb_config {
table_name = aws_dynamodb_table.user_organizations.name
}
}
# ============================================
# IAM ROLES
# ============================================
# AppSync Service Role
resource "aws_iam_role" "appsync_role" {
name = "${var.app_name}-appsync-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "appsync.amazonaws.com"
}
}
]
})
}
# AppSync DynamoDB Policy
resource "aws_iam_role_policy" "appsync_dynamodb_policy" {
name = "${var.app_name}-appsync-dynamodb-policy"
role = aws_iam_role.appsync_role.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem"
]
Resource = [
aws_dynamodb_table.user_profiles.arn,
"${aws_dynamodb_table.user_profiles.arn}/*",
aws_dynamodb_table.organizations.arn,
"${aws_dynamodb_table.organizations.arn}/*",
aws_dynamodb_table.user_organizations.arn,
"${aws_dynamodb_table.user_organizations.arn}/*"
]
}
]
})
}
# Cognito Authenticated Role
resource "aws_iam_role" "authenticated_role" {
name = "${var.app_name}-authenticated-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Federated = "cognito-identity.amazonaws.com"
}
Action = "sts:AssumeRoleWithWebIdentity"
Condition = {
StringEquals = {
"cognito-identity.amazonaws.com:aud" = aws_cognito_identity_pool.identity_pool.id
}
"ForAnyValue:StringLike" = {
"cognito-identity.amazonaws.com:amr" = "authenticated"
}
}
}
]
})
}
# Admin Role
resource "aws_iam_role" "admin_role" {
name = "${var.app_name}-admin-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Federated = "cognito-identity.amazonaws.com"
}
Action = "sts:AssumeRoleWithWebIdentity"
}
]
})
}
# User Role
resource "aws_iam_role" "user_role" {
name = "${var.app_name}-user-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Federated = "cognito-identity.amazonaws.com"
}
Action = "sts:AssumeRoleWithWebIdentity"
}
]
})
}
# Manager Role
resource "aws_iam_role" "manager_role" {
name = "${var.app_name}-manager-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Federated = "cognito-identity.amazonaws.com"
}
Action = "sts:AssumeRoleWithWebIdentity"
}
]
})
}
# Attach roles to identity pool
resource "aws_cognito_identity_pool_roles_attachment" "identity_pool_roles" {
identity_pool_id = aws_cognito_identity_pool.identity_pool.id
roles = {
"authenticated" = aws_iam_role.authenticated_role.arn
}
role_mapping {
identity_provider = "${aws_cognito_user_pool.user_pool.endpoint}:${aws_cognito_user_pool_client.user_pool_client.id}"
ambiguous_role_resolution = "AuthenticatedRole"
type = "Token"
}
}
# ============================================
# S3 BUCKET FOR REACT APP
# ============================================
resource "aws_s3_bucket" "react_app_bucket" {
bucket = var.bucket_name
}
resource "aws_s3_bucket_public_access_block" "react_app_bucket_pab" {
bucket = aws_s3_bucket.react_app_bucket.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
resource "aws_s3_bucket_website_configuration" "react_app_bucket_website" {
bucket = aws_s3_bucket.react_app_bucket.id
index_document {
suffix = "index.html"
}
error_document {
key = "index.html"
}
}
resource "aws_s3_bucket_policy" "allow_public_read" {
bucket = aws_s3_bucket.react_app_bucket.id
depends_on = [aws_s3_bucket_public_access_block.react_app_bucket_pab]
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Sid = "PublicReadGetObject"
Effect = "Allow"
Principal = "*"
Action = ["s3:GetObject"]
Resource = "${aws_s3_bucket.react_app_bucket.arn}/*"
}]
})
}
✅ variables.tf
hcl Copy code
variable "region" {
description = "AWS Region"
default = "us-east-1"
}
variable "app_name" {
description = "Application name"
type = string
default = "my-react-app"
}
variable "environment" {
description = "Environment (dev, staging, prod)"
type = string
default = "dev"
}
variable "bucket_name" {
description = "Name of the S3 bucket to host the React app"
type = string
}
✅ schema.graphql
graphql Copy code
type UserProfile @aws_cognito_user_pools {
userId: ID!
email: String!
firstName: String!
lastName: String!
role: String
organizationId: String
createdAt: String!
updatedAt: String!
}
type Organization @aws_cognito_user_pools {
organizationId: ID!
name: String!
description: String
createdAt: String!
updatedAt: String!
}
type UserOrganization @aws_cognito_user_pools {
userId: ID!
organizationId: ID!
role: String!
permissions: [String]
createdAt: String!
}
type Query {
getUserProfile(userId: ID!): UserProfile
getOrganization(organizationId: ID!): Organization
getUsersByOrganization(organizationId: ID!): [UserProfile]
getOrganizationsByUser(userId: ID!): [Organization]
}
type Mutation {
createUserProfile(input: CreateUserProfileInput!): UserProfile
updateUserProfile(input: UpdateUserProfileInput!): UserProfile
createOrganization(input: CreateOrganizationInput!): Organization
addUserToOrganization(input: AddUserToOrganizationInput!): UserOrganization
}
input CreateUserProfileInput {
userId: ID!
email: String!
firstName: String!
lastName: String!
role: String
}
input UpdateUserProfileInput {
userId: ID!
firstName: String
lastName: String
role: String
}
input CreateOrganizationInput {
name: String!
description: String
}
input AddUserToOrganizationInput {
userId: ID!
organizationId: ID!
role: String!
permissions: [String]
}
✅ outputs.tf
hcl Copy code
output "user_pool_id" {
value = aws_cognito_user_pool.user_pool.id
}
output "user_pool_client_id" {
value = aws_cognito_user_pool_client.user_pool_client.id
}
output "identity_pool_id" {
value = aws_cognito_identity_pool.identity_pool.id
}
output "appsync_api_url" {
value = aws_appsync_graphql_api.api.uris["GRAPHQL"]
}
output "website_url" {
value = "http://${aws_s3_bucket.react_app_bucket.website_endpoint}"
}
output "dynamodb_tables" {
value = {
user_profiles = aws_dynamodb_table.user_profiles.name
organizations = aws_dynamodb_table.organizations.name
user_organizations = aws_dynamodb_table.user_organizations.name
}
}
🔧 Deploy Everything
bash Copy code
terraform init
terraform apply -var="bucket_name=my-react-app-bucket-123456" -var="app_name=my-app"
📱 React App Configuration
After deployment, update your React app's src/aws-exports.js:
js Copy code
const config = {
Auth: {
region: 'us-east-1',
userPoolId: 'OUTPUT_FROM_TERRAFORM',
userPoolWebClientId: 'OUTPUT_FROM_TERRAFORM',
identityPoolId: 'OUTPUT_FROM_TERRAFORM'
},
API: {
GraphQL: {
endpoint: 'OUTPUT_FROM_TERRAFORM',
region: 'us-east-1',
defaultAuthMode: 'COGNITO_USER_POOLS'
}
}
};
export default config;
This setup gives you:
Cognito User Pools with custom groups (admin, user, manager)
DynamoDB tables for user profiles, organizations, and relationships
AppSync API with GraphQL schema
Proper IAM roles for different user types
S3 hosting for your React app
The DynamoDB tables allow you to store extended user data beyond what Cognito provides natively.