# Oshun ECS Service Roles Module

This Terraform module creates domain-specific IAM task roles for ECS services
with tailored permissions for each Oshun domain.

## Features

- **Domain-Specific Roles**: Pre-configured roles for Yemaya, Lilith, Isis,
  Sophia, Hathor, and Bellona domains
- **Least Privilege**: Scoped permissions based on service requirements
- **Secrets Integration**: Automatic Secrets Manager and SSM Parameter Store
  access
- **AI/ML Services**: Optional permissions for AWS AI services (Bedrock,
  Comprehend, etc.)
- **S3 Access Patterns**: Configurable read/write access to buckets and paths
- **SQS Integration**: Consumer and publisher permissions for job queues
- **Observability**: Built-in X-Ray tracing and CloudWatch metrics permissions
- **ECS Exec**: SSH-like debugging access via SSM

## Usage

```hcl
module "ecs_roles" {
  source = "../ecs-roles"

  environment = "production"
  region      = "us-east-1"
  name_prefix = "oshun"

  # From ECS cluster module
  cluster_name = module.ecs.cluster_name
  cluster_arn  = module.ecs.cluster_arn

  # From secrets module
  secrets_kms_key_arn = module.secrets.kms_key_arn
  secrets_prefix      = module.secrets.parameter_prefix

  # From SSM module
  parameters_prefix = module.ssm.parameter_prefix

  # ECS Exec logging
  ecs_exec_log_group_arn = module.ecs.log_group_ecs_exec_arn

  # Domain service configurations
  yemaya_services = {
    studio-api = {
      description    = "Creative Studio API"
      secrets_access = ["yemaya/*", "database/yemaya"]
      s3_write_paths = ["projects/*", "exports/*"]
    }
  }

  lilith_services = {
    consciousness-api = {
      description    = "Consciousness AI API"
      secrets_access = ["lilith/*", "database/lilith", "ai/*"]
      enable_bedrock = true
    }
  }

  tags = {
    Environment = "production"
  }
}
```

## Domain Service Configurations

### Yemaya (Creative Studio)

```hcl
yemaya_services = {
  studio-api = {
    description    = "Creative Studio API service"
    enabled        = true
    secrets_access = ["yemaya/*", "database/yemaya"]
    s3_write_paths = ["projects/*", "exports/*"]
    enable_bedrock = false
  }
  renderer = {
    description    = "Rendering worker service"
    secrets_access = ["yemaya/*"]
    s3_write_paths = ["renders/*", "temp/*"]
    enable_bedrock = true
  }
}
```

### Lilith (Consciousness)

```hcl
lilith_services = {
  consciousness-api = {
    description    = "Consciousness API service"
    secrets_access = ["lilith/*", "database/lilith", "ai/*"]
    enable_bedrock = true
  }
  agent-worker = {
    description    = "AI Agent worker"
    secrets_access = ["lilith/*", "ai/*"]
    enable_bedrock = true
  }
}
```

### Isis (Generative Factory)

```hcl
isis_services = {
  factory-api = {
    description    = "Generative Factory API"
    secrets_access = ["isis/*", "database/isis", "ai/*"]
    s3_write_paths = ["generations/*"]
    enable_bedrock = true
  }
  image-worker = {
    description    = "Image generation worker"
    secrets_access = ["isis/*", "ai/*"]
    s3_write_paths = ["images/*", "temp/*"]
    enable_bedrock = true
  }
}
```

### Sophia (Research & Knowledge)

```hcl
sophia_services = {
  research-api = {
    description       = "Research API service"
    secrets_access    = ["sophia/*", "database/sophia", "ai/*"]
    enable_bedrock    = true
    enable_opensearch = true
  }
  indexer = {
    description       = "Document indexing service"
    secrets_access    = ["sophia/*"]
    enable_opensearch = true
  }
}
```

### Hathor (Worldbuilding)

```hcl
hathor_services = {
  worldbuilding-api = {
    description    = "Worldbuilding API"
    secrets_access = ["hathor/*", "database/hathor", "ai/*"]
    s3_write_paths = ["worlds/*", "maps/*"]
    enable_bedrock = true
  }
}
```

### Bellona (Build Engine)

```hcl
bellona_services = {
  build-api = {
    description    = "Build Engine API"
    secrets_access = ["bellona/*", "database/bellona"]
    s3_write_paths = ["builds/*", "artifacts/*"]
  }
  runner = {
    description    = "Build runner worker"
    secrets_access = ["bellona/*"]
    s3_write_paths = ["builds/*", "logs/*"]
  }
}
```

### Common Services

```hcl
common_services = {
  api-gateway = {
    description    = "API Gateway service"
    secrets_access = ["jwt/*", "oauth/*"]
  }
  auth-service = {
    description    = "Authentication service"
    secrets_access = ["jwt/*", "oauth/*", "encryption/*"]
    enable_ses     = true
  }
}
```

## Custom Service Configuration

For services with unique requirements:

```hcl
services = {
  custom-worker = {
    domain      = "custom"
    description = "Custom processing worker"
    enabled     = true

    # Secrets access patterns
    secrets_access = ["custom/*", "database/custom"]

    # SSM parameters access
    parameters_access = ["custom/*", "app/*"]

    # S3 permissions
    s3_read_buckets  = ["models", "assets"]
    s3_write_buckets = ["outputs"]
    s3_read_paths    = ["shared/*"]
    s3_write_paths   = ["custom/*"]

    # SQS permissions
    sqs_consume_queues = ["custom-jobs"]
    sqs_publish_queues = ["custom-results", "custom-dlq"]

    # DynamoDB permissions
    dynamodb_tables_read  = ["custom-state"]
    dynamodb_tables_write = ["custom-state"]

    # AWS AI services
    enable_bedrock    = true
    enable_comprehend = false
    enable_rekognition = false

    # Communication services
    enable_ses = false
    enable_sns = true

    # Search services
    enable_opensearch = false

    # Debugging and observability
    enable_ecs_exec           = true
    enable_xray               = true
    enable_cloudwatch_metrics = true
    cloudwatch_namespaces     = ["oshun/Custom"]

    # Custom inline policies
    custom_policies = [
      {
        name = "custom-api-access"
        policy = jsonencode({
          Version = "2012-10-17"
          Statement = [
            {
              Effect   = "Allow"
              Action   = ["lambda:InvokeFunction"]
              Resource = "arn:aws:lambda:*:*:function:custom-*"
            }
          ]
        })
      }
    ]

    # Managed policy ARNs
    managed_policy_arns = []

    tags = {
      Team = "custom-team"
    }
  }
}
```

## Outputs

### Using Role ARNs in Task Definitions

```hcl
resource "aws_ecs_task_definition" "yemaya_api" {
  family = "yemaya-studio-api"

  # Use the task role from this module
  task_role_arn = module.ecs_roles.service_task_role_arns["yemaya-studio-api"]

  # Use the execution role from ECS cluster module
  execution_role_arn = module.ecs.task_execution_role_arn

  container_definitions = jsonencode([{
    name  = "api"
    image = "..."
    # ...
  }])
}
```

### Accessing Roles by Domain

```hcl
# Get all Yemaya roles
locals {
  yemaya_roles = module.ecs_roles.yemaya_task_roles
}

# Access specific role
output "yemaya_api_role" {
  value = module.ecs_roles.yemaya_studio_api_role_arn
}
```

## Permissions Reference

### Default Permissions (All Services)

| Permission | Description                       |
| ---------- | --------------------------------- |
| ECS Exec   | SSM Session Manager for debugging |
| X-Ray      | Distributed tracing               |
| CloudWatch | Custom metrics publishing         |

### Optional Permissions

| Flag               | Service         | Description                 |
| ------------------ | --------------- | --------------------------- |
| enable_bedrock     | AWS Bedrock     | Foundation model invocation |
| enable_comprehend  | AWS Comprehend  | NLP analysis                |
| enable_rekognition | AWS Rekognition | Image/video analysis        |
| enable_transcribe  | AWS Transcribe  | Speech-to-text              |
| enable_polly       | AWS Polly       | Text-to-speech              |
| enable_translate   | AWS Translate   | Language translation        |
| enable_textract    | AWS Textract    | Document text extraction    |
| enable_ses         | AWS SES         | Email sending               |
| enable_sns         | AWS SNS         | Push notifications          |
| enable_opensearch  | AWS OpenSearch  | Search index operations     |
| enable_elasticache | AWS ElastiCache | Redis connection            |

## Best Practices

1. **Least Privilege**: Only enable permissions actually needed by the service
2. **Secrets Scoping**: Use specific secret patterns rather than wildcards
3. **S3 Path Scoping**: Restrict write access to specific paths
4. **Queue Naming**: Use consistent queue naming for SQS permissions
5. **Observability**: Keep X-Ray and CloudWatch enabled for debugging

## Inputs

| Name                   | Description                 | Type        | Default     | Required |
| ---------------------- | --------------------------- | ----------- | ----------- | :------: |
| environment            | Deployment environment      | string      | -           |   yes    |
| region                 | AWS region                  | string      | "us-east-1" |    no    |
| name_prefix            | Resource name prefix        | string      | "oshun"     |    no    |
| cluster_name           | ECS cluster name            | string      | -           |   yes    |
| cluster_arn            | ECS cluster ARN             | string      | -           |   yes    |
| secrets_kms_key_arn    | KMS key for secrets         | string      | ""          |    no    |
| secrets_prefix         | Secrets Manager path prefix | string      | ""          |    no    |
| parameters_prefix      | SSM Parameter Store prefix  | string      | ""          |    no    |
| yemaya_services        | Yemaya service configs      | map(object) | {}          |    no    |
| lilith_services        | Lilith service configs      | map(object) | {}          |    no    |
| isis_services          | Isis service configs        | map(object) | {}          |    no    |
| sophia_services        | Sophia service configs      | map(object) | {}          |    no    |
| hathor_services        | Hathor service configs      | map(object) | {}          |    no    |
| bellona_services       | Bellona service configs     | map(object) | {}          |    no    |
| common_services        | Common service configs      | map(object) | {}          |    no    |
| services               | Custom service configs      | map(object) | {}          |    no    |
| ecs_exec_log_group_arn | Log group for ECS Exec      | string      | ""          |    no    |

## Outputs

| Name                    | Description                        |
| ----------------------- | ---------------------------------- |
| service_task_role_arns  | Map of service names to role ARNs  |
| service_task_role_names | Map of service names to role names |
| yemaya_task_roles       | Yemaya domain roles                |
| lilith_task_roles       | Lilith domain roles                |
| isis_task_roles         | Isis domain roles                  |
| sophia_task_roles       | Sophia domain roles                |
| hathor_task_roles       | Hathor domain roles                |
| bellona_task_roles      | Bellona domain roles               |
| common_task_roles       | Common service roles               |
| roles_summary           | Summary of created roles           |
