diff --git a/.github/workflows/terraform.yml b/.github/workflows/terraform.yml index 122ed88025..ae858db134 100644 --- a/.github/workflows/terraform.yml +++ b/.github/workflows/terraform.yml @@ -85,7 +85,15 @@ jobs: "download-lambda", "lambda", "multi-runner", + "compute-providers/ec2", + "compute-providers/ec2/trust-policy", "runner-binaries-syncer", + "orchestration-providers/webhook", + "orchestration-providers/webhook/job-retry", + "orchestration-providers/webhook/pool", + "orchestration-providers/webhook/scale-runners", + "runner-config", + "runner-config/ssm-housekeeper", "runners", "setup-iam-permissions", "ssm", @@ -214,6 +222,15 @@ jobs: matrix: module: - modules/runners + - modules/multi-runner + - modules/orchestration-providers/webhook + - modules/orchestration-providers/webhook/job-retry + - modules/orchestration-providers/webhook/pool + - modules/orchestration-providers/webhook/scale-runners + - modules/runner-config + - modules/runner-config/ssm-housekeeper + - modules/compute-providers/ec2 + - modules/compute-providers/ec2/trust-policy defaults: run: working-directory: ${{ matrix.module }} diff --git a/docs/adr/002-runner-orchestration-provider-boundary.md b/docs/adr/002-runner-orchestration-provider-boundary.md new file mode 100644 index 0000000000..32742d30e5 --- /dev/null +++ b/docs/adr/002-runner-orchestration-provider-boundary.md @@ -0,0 +1,311 @@ +# ADR-002: Runner Orchestration Provider Boundary + +## Status + +Proposed + +## Date + +2026-08-15 + +## Context + +The multi-runner module currently receives workflow-job demand through a shared GitHub webhook. A build queue then invokes scale-up, while scheduled Lambda functions handle scale-down, a runner pool, and queued-job retries. Those components evolved together and their settings are spread across shared module inputs and each runner entry. + +That layout assumes every runner configuration uses the same demand-control model. It also makes the runner configuration module responsible for webhook-specific resources. Adding another model would require provider conditionals throughout the module or a second copy of the common runner and compute-provider wiring. + +GitHub Actions Runner Scale Sets require a different control model. A future implementation is expected to use the runner scale-set and agent APIs, including: + +- `_apis/runtime/runnerscalesets` +- `_apis/distributedtask/pools/0/agents` + +Unlike the current event and schedule driven Lambda components, a scale-set controller maintains reconciliation state and long-lived coordination with GitHub. It may therefore need a containerized service, with ECS as a candidate deployment target, rather than another independent Lambda handler. + +The Terraform contract should make that future addition possible without moving webhook fields a second time. This ADR defines that boundary. It does not implement the scale-set API client, controller, container image, or ECS resources. + +## Terminology + +- **Runner configuration**: One entry in `experimental.multi_runner_config`, including common runner behavior, one orchestration provider, and one compute provider. +- **Orchestration provider**: The implementation that receives or reconciles runner demand and owns the control components needed to turn that demand into capacity actions. +- **Compute provider**: The implementation that creates and manages runner capacity, such as EC2. It supplies capabilities to the selected orchestration provider. +- **Webhook orchestration**: The existing webhook, queue, scale-up, scale-down, pool, and job-retry implementation. +- **Scale-set orchestration**: A future stateful controller built on GitHub's runner scale-set APIs. + +The public contract and documentation use “runner configuration.” They do not introduce a separate nickname for the existing implementation. + +## Decision + +We will introduce a typed orchestration-provider boundary in the experimental multi-runner v2 interface. + +### Provider selection is per runner configuration + +Every experimental runner configuration must contain an `orchestration` object with exactly one non-null typed provider block. In this phase the only supported block is `webhook`: + +```hcl +experimental = { + multi_runner_config = { + linux_arm64 = { + orchestration = { + webhook = { + runner = { + boot_time_in_minutes = 5 + ephemeral = true + jit_config_enabled = null + maximum_count = 4 + } + + github = { + organization_runners = true + } + + matcherConfig = { + labelMatchers = [["linux", "arm64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m7g.large"] + } + } + } + } +} +``` + +Selection is based on the populated provider block, not on a string discriminator. The wrapper's nullness must be known during planning because it determines the Terraform graph. Values inside the selected provider may remain unknown until apply. + +Validation counts non-null provider blocks rather than naming one special case. A future provider can therefore be added as a sibling without changing the selection rule. Different runner configurations may select different providers once more than one exists, but one runner configuration cannot combine providers. + +### Global orchestration blocks provide defaults; they do not select providers + +`experimental.orchestration.webhook` is the global defaults and shared-component namespace for webhook orchestration. Its presence does not select webhook orchestration for every runner configuration. Selection remains under `experimental.multi_runner_config..orchestration`. + +The webhook global namespace owns: + +- the default runner boot timeout used by webhook scale-down and pool components; +- the default ephemeral and just-in-time registration lifecycle used by webhook controls and runner bootstrap; +- the default maximum runner count enforced by webhook scale-up and pool components; +- the repository allow list enforced by the shared webhook; +- queue-selection strategy, EventBridge routing, and matcher-parameter tier; +- build-queue defaults, redrive behavior, tags, and encryption; +- the shared webhook Lambda configuration and artifact selection; +- the runner-control artifact shared by scale, pool, and job-retry; and +- default scale-up, scale-down, and pool component settings. + +Job-retry remains a per-runner-configuration webhook setting in this phase; its +typed block supplies its own defaults rather than inheriting a global block. + +Runner boot time, ephemeral mode, JIT configuration, and maximum runner count are webhook-provider settings rather than common runner identity. Their canonical paths live under `experimental.orchestration.webhook.runner`, with matching paths under `experimental.multi_runner_config..orchestration.webhook.runner` for runner-configuration overrides. Stable-v1 translation maps the existing lifecycle, boot-time, and capacity inputs into those provider paths, and the unchanged stable `modules/runners` call reads from the canonical provider block. No compatibility aliases are retained under the experimental common `runner` object. The webhook provider resolves a null JIT setting to the effective ephemeral mode, exposes that lifecycle contract to runner-config bootstrap, injects boot time into scale-down and pool, and keeps these settings out of compute-provider capabilities. + +The common `experimental.github` block continues to own credentials and GitHub API client settings shared across implementations, including `enterprise_server` and `user_agent`. Repository filtering belongs to the shared webhook at `experimental.orchestration.webhook.github.repository_white_list`; per-configuration `organization_runners` remains in the same provider-owned GitHub block. + +The common `experimental.lambda` block contains only provider-neutral Lambda substrate: runtime, architecture, networking, role settings, additional principals, tags, and an optional shared artifact bucket. It does not select a provider archive. Each component owner supplies its own local zip or S3 object key and version. + +The webhook provider owns one runner-control artifact at `orchestration.webhook.lambda.artifact`, shared by scale, pool, and job-retry. Its `lambda.scale` child contains only `up` and `down` configuration, while the ingress webhook retains its separate `lambda.webhook.artifact`. The provider-neutral SSM housekeeper owns its artifact selector under `ssm.housekeeper.lambda.artifact`. A runner-configuration selection overrides the global `experimental.ssm.housekeeper.lambda.artifact`; an S3 selection combines its key and optional object version with the common Lambda artifact bucket, a zip selection uses its local path, and no selection uses runner-config's packaged runner control-plane archive. This selector is independent of the webhook runner-control artifact. Stable-v1 translation maps the existing runner artifact into both canonical component contracts so the translated representation remains complete without changing the stable resource path. + +For a selected webhook provider, resolution follows: + +```text +runner-configuration override > experimental orchestration.webhook default +``` + +Tag maps merge from broad to narrow. A runner-configuration override affects only that runner configuration; it does not configure a shared singleton. + +### Module ownership follows the provider boundary + +The Terraform implementation is split as follows: + +| Layer | Responsibility | +| --- | --- | +| `modules/multi-runner` | Selects stable or experimental mode, resolves global and runner-configuration values, owns shared webhook ingress and build queues, and routes typed provider objects. | +| `modules/runner-config` | Composes provider-neutral runner resources, selects exactly one orchestration provider and one compute provider, creates or selects the runner role, and connects provider capabilities. | +| `modules/orchestration-providers/webhook` | Owns webhook orchestration composition, provider defaults, tag layering, and the scale, pool, and retry leaf modules. | +| `modules/orchestration-providers/webhook/scale-runners` | Owns the scale-up and scale-down Lambdas, schedules, queue integration, IAM, and outputs. | +| `modules/orchestration-providers/webhook/pool` | Owns optional scheduled pool resources and IAM. | +| `modules/orchestration-providers/webhook/job-retry` | Owns optional queued-job retry resources and IAM. | +| `modules/runner-config/ssm-housekeeper` | Owns provider-neutral cleanup of runner token and configuration parameters, including its component-specific Lambda artifact. | +| `modules/compute-providers/` | Owns capacity resources and returns policy, environment-variable, trust-policy, and resource capabilities. | + +The former `modules/runner-stack` name becomes `modules/runner-config`. “Runner configuration” describes the module's purpose without implying a specific deployment topology. + +```mermaid +flowchart TD + Multi["multi-runner: normalize and route"] --> Config["runner-config: compose one runner configuration"] + Config --> Selector{"exactly one orchestration provider"} + Selector --> Webhook["orchestration-providers/webhook"] + Selector -. future .-> ScaleSet["orchestration-providers/scale-set"] + Config --> ComputeSelector{"exactly one compute provider"} + ComputeSelector --> EC2["compute-providers/ec2"] + EC2 --> Capabilities["compute capabilities"] + Capabilities --> Webhook + Capabilities -. future .-> ScaleSet + Webhook --> Scale["scale-runners"] + Webhook --> Pool["pool"] + Webhook --> Retry["job-retry"] +``` + +Provider leaf modules live below `modules/orchestration-providers/webhook`, not below `modules/runner-config`. This keeps the composition module small and prevents provider-owned resources from becoming a permanent part of the common contract. + +### Compute providers expose capabilities, not orchestration resources + +The selected compute provider remains independent from the selected orchestration provider. It returns the policy documents, environment variables, trust policy, managed-policy references, and resources needed by orchestration components. + +`runner-config` adapts that provider output into the scale-up, scale-down, and pool capabilities consumed by webhook orchestration. The webhook provider owns its Lambda roles and attaches the capability fragments it needs. The compute provider does not create the common runner role or webhook resources. + +This direction keeps the dependency graph one-way: + +```text +runner-config -> compute provider -> capability contract -> orchestration provider +``` + +A future scale-set controller may require a different subset or extension of the capability contract. That extension belongs at the provider boundary; it must not add scale-set conditionals to the webhook leaves. + +### Compatibility and state are explicit + +Stable inputs are translated into the same internal canonical representation so defaults and shared singleton values have one resolution path. Stable runner configurations continue to call the existing `modules/runners` implementation at their existing addresses. Opting into experimental v2 is module-wide: a non-empty `experimental.multi_runner_config` replaces, rather than merges with, the stable map. + +The experimental implementation preserves in-progress v2 state with declarative moves: + +- `module.runner_stacks` moves to `module.runner_configs`; +- scale-up/scale-down resources move beneath `module.webhook["webhook"].module.scale_runners`; +- pool resources move beneath `module.webhook["webhook"].module.pool`; and +- job-retry resources move beneath `module.webhook["webhook"].module.job_retry`. + +The canonical v2 output groups resources under `orchestration.webhook`. Direct `scale_up`, `scale_down`, and `pool` outputs remain compatibility aliases during the experimental transition. + +This ADR does not define an automatic stable-v1-to-v2 state migration. Existing deployments remain on the stable path until that migration is separately designed and documented. + +### IAM and encryption follow resource ownership + +Provider-owned IAM policies use conditional statements for optional KMS keys. A null key omits the statement; policies do not use placeholder account IDs, key IDs, or ARNs to satisfy Terraform typing. + +Parameter Store and queue encryption are separate concerns: + +| Key purpose | Consumer | Required KMS actions | +| --- | --- | --- | +| GitHub App parameters in Parameter Store | Scale-up, scale-down, pool, and job retry as applicable | `kms:Decrypt` | +| Encrypted build queue | Scale-up | `kms:Decrypt` | +| Encrypted build queue | Job retry when publishing a retry | `kms:Decrypt`, `kms:GenerateDataKey` | + +Because queue KMS values are used as IAM `Resource` entries, the experimental queue contract requires a KMS key ARN when a customer-managed key is selected. SSM write access is scoped to the runner token and configuration paths. Wildcard resources are allowed only for AWS APIs that do not support resource-level permissions, such as the required X-Ray actions, and the policy must document that reason. + +### Existing shared modules stay unchanged + +This refactor does not change `modules/webhook` or `modules/ssm`. + +The shared webhook remains at its existing unconditional module address. The shared SSM module continues to create or reference the webhook secret even when no runner configuration selects webhook orchestration. That singleton contract may support other uses and is independent of the per-runner exact-one provider selection. + +Any later proposal to make those shared modules conditional is a separate compatibility and state decision. + +### Scale-set implementation is deferred + +No `scale_set` field is added to the Terraform type in this phase. The typed object and module layout reserve the extension point without publishing an incomplete contract. + +A follow-up design must decide at least: + +1. the public TypeScript SDK surface for runner scale-set and agent operations; +2. authentication, API-version negotiation, error mapping, retries, and idempotency; +3. the reconciliation and persistence model for desired, acquired, busy, and removed runners; +4. the controller's shutdown, recovery, concurrency, and high-availability behavior; +5. the container build and release contract for the TypeScript service; +6. whether ECS/Fargate is the default deployment and how networking, scaling, logging, health checks, and upgrades work; +7. the capabilities required from each compute provider; and +8. Terraform migration and coexistence behavior when the new provider is enabled. + +The intended end state permits webhook and scale-set orchestration in the same multi-runner module instance when different runner configurations select them. It does not permit both controllers to own the same runner configuration. + +## Consequences + +### Positive + +- A future orchestration provider becomes a sibling module instead of a cross-cutting conditional. +- Runner and compute-provider configuration remains reusable across demand-control models. +- Provider-owned queue, Lambda, artifact, IAM, and output settings have one discoverable namespace. +- Exact-one validation prevents ambiguous ownership of a runner configuration. +- Stable behavior and shared singleton addresses remain unchanged. +- Moved blocks preserve the addresses already created by the experimental v2 work. + +### Negative + +- The experimental input is more deeply nested than the existing flat interface. +- Global webhook defaults and per-runner webhook selection use similarly named blocks with different purposes. +- Internal modules have explicit adapter objects and capability contracts that require maintenance. +- Adding a stateful provider will still require new runtime, deployment, observability, and failure-recovery design; the Terraform boundary alone does not solve those concerns. +- Compatibility aliases temporarily expose both canonical and historical v2 output paths. + +## Alternatives Considered + +### Add a flat orchestration mode string + +A value such as `orchestration_type = "webhook"` plus a flat collection of settings would make unrelated fields valid for every provider and require cross-field validation. + +**Decision**: Use typed, nullable sibling blocks. The populated block both selects and configures the provider. + +### Put provider conditionals directly in `runner-config` + +This would keep fewer directories initially, but every provider would add resources, variables, IAM branches, and outputs to the common module. + +**Decision**: Keep `runner-config` as a selector and composer. Put concrete resources under `modules/orchestration-providers/`. + +### Keep webhook leaves under `runner-config` + +Scale, pool, and retry are all webhook orchestration behavior. Leaving them under the common module would blur ownership and make a future provider appear to support components it does not use. + +**Decision**: Move the leaves under the webhook provider root and preserve state with moved blocks. + +### Add the scale-set schema and ECS service now + +Publishing placeholders would lock in names and types before the API client, reconciliation semantics, and runtime model have been validated. + +**Decision**: Publish only the provider-neutral extension point now. Add the scale-set provider in a follow-up ADR and implementation. + +### Make the shared webhook and webhook secret conditional + +That change would alter existing singleton resource addresses and would conflate module-level ingress with per-runner provider selection. + +**Decision**: Leave `modules/webhook` and `modules/ssm` unchanged in this refactor. + +## Migration and Verification + +Implementation and review must verify the boundary at several levels. + +### Terraform contract tests + +- A runner configuration with exactly one webhook provider plans successfully. +- Zero or multiple non-null orchestration providers fail with a focused validation message. +- Provider-wrapper nullness may shape the plan while values inside the selected provider may be unknown until apply. +- Per-runner values override global webhook defaults, and omitted nullable values inherit them. +- Shared singleton resources consume global values rather than arbitrary per-runner overrides. +- Stable inputs preserve stable resource addresses and output shape. +- The experimental module and child-module renames produce move operations rather than destroy/create operations. +- Canonical nested outputs and compatibility aliases reference the same resources. + +### Provider and IAM tests + +- `runner-config` routes only the selected orchestration provider. +- The webhook root composes scale, pool, and retry leaves with the resolved values supplied by `multi-runner`; it does not invent fallback ARNs or empty resource objects. +- Compute-provider capability fragments reach the correct webhook component. +- Null SSM or queue KMS keys omit their IAM statements. +- Queue and Parameter Store KMS permissions remain separate and use the least actions required. +- SSM writes are limited to the configured token and runner-configuration paths. +- Any wildcard IAM resource has an AWS API limitation documented next to it. + +### Compatibility checks + +- `modules/webhook` has no diff. +- `modules/ssm` has no diff. +- Stable multi-runner tests continue to pass. +- Experimental provider-routing, computed-input, runner-config, webhook-provider, scale, pool, retry, and SSM-housekeeper tests pass. +- Terraform formatting, documentation generation, and repository pre-commit checks are clean. + +Before an existing experimental deployment adopts the module rename, its plan must be inspected for only the expected moved addresses. Stable deployments must not enable v2 until a stable-to-v2 migration procedure exists. + +## References + +- [Experimental compute-provider refactor](../modules/internal/compute-provider-refactor.md) +- [GitHub Actions Runner Scale Set reference implementation](https://github.com/actions/scaleset) +- [PR #5204 warm-pool proposal and ADR structure](https://github.com/github-aws-runners/terraform-aws-github-runner/pull/5204) +- [ADR-001 warm-pool decision in PR #5204](https://github.com/github-aws-runners/terraform-aws-github-runner/blob/feature/warm-pool-hibernation/docs/adr/001-warm-pool-hibernation.md) +- [ADR-001 warm-pool implementation plan in PR #5204](https://github.com/github-aws-runners/terraform-aws-github-runner/blob/feature/warm-pool-hibernation/docs/adr/001-warm-pool-implementation-plan.md) diff --git a/docs/index.md b/docs/index.md index 7a7d0f70c6..7020b5f606 100644 --- a/docs/index.md +++ b/docs/index.md @@ -101,7 +101,23 @@ Besides these permissions, the lambdas also need permission to CloudWatch (for l ## Terraform main modules -Currently we support two main modules. The `runners` module is the main module for creating runners. And the 'multi-runner' module is a wrapper around the `runners` module to create multiple runners in one go. The `multi-runner` module is useful for creating runners for multiple repositories or organizations. +Currently we support two main modules. The existing `runners` module remains the stable EC2 implementation, and the `multi-runner` module creates multiple runner configurations in one deployment. Stable top-level `multi_runner_config` entries continue to use the unchanged `runners` module when `experimental.multi_runner_config` is empty. A non-empty experimental map takes priority over the stable map; the maps are not combined. Experimental entries use the new provider-oriented `runner-config`. + +Multi-runner centralizes mode selection and canonical configuration in `config.experimental.translation.tf`. A non-empty experimental runner-configuration map selects v2; otherwise the file projects the flat globals and stable runner configurations into the same schema. That selection produces `local.raw_translated_experimental`, from which the same file derives `local.translated_experimental_base` by applying schema defaults, global/runner-configuration precedence, tag merges, IAM ownership, paths, observability, webhook queues, and provider defaults. Provider selection and the shared runner-binary syncer and discovery use this plan-known base. After discovery, the translation file derives the final `local.translated_experimental`, including labels, runner-config GitHub client settings, webhook queue event mapping, Lambda artifact and principals, the webhook pool Lambda wrapper, SSM KMS, and the discovered EC2 binaries object. The remaining shared components, webhook queues, and runner implementations consume that final canonical representation. Stable runner configurations are adapted back into the existing `module.runners["configuration"]` call, preserving their Terraform addresses while removing a second configuration path. The `module.runner_configs` call directly iterates the gated final runner configurations, inlines the environment tag and live GitHub App and build-queue references into `orchestration.webhook`, and forwards the remaining canonical objects, including the typed orchestration and compute-provider wrappers. + +The `experimental` object provides sibling global defaults through `tags`, `roles`, `runner`, `github`, `lambda`, `orchestration`, `ssm`, `observability`, and `compute_provider`. Root `experimental.lambda` is provider-neutral shared Lambda substrate: the artifact bucket, runtime, architecture, principals, networking, tags, and role defaults used across orchestration and non-orchestration consumers. Webhook-specific global defaults live together under `experimental.orchestration.webhook`, including the maximum runner count, the shared webhook's routing and matcher storage, build-queue defaults and encryption, control-plane artifact selectors, and webhook, scale-up, scale-down, and pool Lambda settings. This global block supplies defaults; it does not select an orchestration provider. Each runner configuration separately makes that selection through its own `orchestration` wrapper. The only supported orchestration provider today is `orchestration.webhook`, which owns that runner configuration's maximum runner count, registration scope, matcher, build-queue overrides, scale-up and scale-down settings, scheduled pool, and job retry. Keeping those fields behind a typed provider wrapper allows future orchestration providers to be introduced as mutually exclusive siblings without moving the common runner, Lambda substrate, SSM, observability, or compute-provider contracts again. The shared GitHub App Parameter Store module, webhook, runner-binary syncer, termination watcher, and AMI housekeeper consume the translated global values. Migrated v2 consumers do not fall back to matching flat inputs; those flat values seed stable-mode translation only. Per-configuration overrides remain configuration-specific. A nullable runner-configuration field with a corresponding experimental global inherits that global value when omitted or null. A runner configuration that selects an external runner IAM role intentionally suppresses inherited managed policies and additional trust policy JSON because the module does not manage that role. Tag maps merge from broad to narrow. Only module naming (`prefix`), `aws_partition`, and `aws_region` remain active flat-only inputs; legacy `iam_overrides` remains in the input schema but has no active consumer. + +Global `experimental.orchestration.webhook.queue` owns v2 defaults for build-queue delay (`30` seconds), retention (`86400` seconds), visibility (`180` seconds), redrive, tags, and encryption. Runner-configuration `experimental.multi_runner_config[].orchestration.webhook.queue` fields override the global delay, retention, visibility, redrive, and tag values; encryption remains global-only. Omitting the whole encryption block selects SQS-managed encryption and null KMS attributes. If the block is supplied explicitly, all three leaf keys are required: use a non-null `sqs_managed_sse_enabled` with null KMS fields for the non-KMS mode, or set that field to null and provide `kms_master_key_id` for KMS mode. This encryption configures the multi-runner build queues and their dead-letter queues, not the webhook provider's separate job-retry queue, and its CMK is independent from `experimental.ssm.kms_key_id`. Runner-config forwards the distinct build-queue key to the webhook orchestration provider: scale-up receives `kms:Decrypt`, while job-retry receives `kms:Decrypt` and `kms:GenerateDataKey` for publishing. The existing shared `modules/webhook` contract remains unchanged and still requires caller-supplied key access when that publisher targets customer-managed encrypted queues. For v2, `experimental.multi_runner_config[].orchestration.webhook.queue.visibility_timeout_seconds` must be at least six times the resolved `experimental.multi_runner_config[].orchestration.webhook.lambda.scale.up.timeout`; the Lambda timeout does not itself configure queue visibility. The v1 translation continues to use `runners_scale_up_lambda_timeout` and flat `queue_encryption`. + +V2 requires `experimental.github.app`, and `experimental.github.additional_apps` defaults to an empty list. These nested values are authoritative end-to-end: the shared Parameter Store module persists or selects their credentials, and v2 runner configurations consume the resulting references. Flat `github_app` and `additional_github_apps` seed stable-mode translation only. `experimental.orchestration.webhook.github.repository_white_list` defaults to `[]` and filters the shared webhook when populated. `experimental.github.enterprise_server.url` defaults to `null` and configures v2 runner-config GitHub clients and the termination watcher. `experimental.github.enterprise_server.ssl_verify` and `experimental.github.user_agent` remain runner-config client settings and default to `true` and `github-aws-runners`. Both client settings belong inside `experimental.github`; they are not root `experimental` fields or per-configuration orchestration settings. + +The shared webhook, runner configurations, SSM housekeepers, runner-binary syncer, termination watcher, and AMI housekeeper consume the provider-neutral runtime, architecture, networking, role, and tag defaults under `experimental.lambda`; `lambda.principals` configures runner-config, runner-binary-syncer, termination-watcher, and AMI-housekeeper roles, but not the webhook role. Global observability settings configure logging and tracing, and global metrics also configure the termination watcher. The runner-control artifact shared by webhook scale, pool, and job-retry is selected globally under `experimental.orchestration.webhook.lambda.artifact`: `artifact.zip` selects a local archive, while `artifact.s3.{key,object_version}` selects an object from the shared `experimental.lambda.artifact.s3.bucket`. Leaving both artifact sources null uses the packaged runner archive. The module validates that zip and S3 are not selected together and that an S3 wrapper has a non-null shared bucket and key. Stable-mode translation preserves the legacy precedence in which a configured flat S3 bucket wins over the flat runner zip. The shared bucket alone selects no component. Each artifact-capable singleton—including the webhook—uses it only when that component's separate nested `artifact.s3` wrapper supplies its key and optional object version. Runner-config's common SSM housekeeper independently resolves `multi_runner_config[].ssm.housekeeper.lambda.artifact` over the global `experimental.ssm.housekeeper.lambda.artifact`; S3 combines the component key and version with the shared artifact bucket, zip uses the selected local path, and no selection uses the packaged control-plane archive. The runner-binary syncer follows the same parallel selector at `experimental.compute_provider.ec2.runner_binaries.syncer.artifact.{zip,s3}`, with its S3 key and optional object version also resolved against `experimental.lambda.artifact.s3.bucket`. `experimental.orchestration.webhook` owns queue selection, EventBridge routing, accepted event types, and matcher-parameter tier, while `experimental.orchestration.webhook.lambda.webhook` owns the separate ingress webhook artifact, API Gateway access logs, sizing, and component tags. `compute_provider.ec2.instance_termination_watcher`, `compute_provider.ec2.ami.housekeeper`, and `compute_provider.ec2.runner_binaries` own their singleton-specific features, artifacts, sizing, schedules, and related settings. + +`experimental.compute_provider.ec2.runner_binaries.enabled` defaults each EC2 runner configuration to the shared synchronized distribution, while a nullable per-configuration `compute_provider.ec2.binaries_syncer.enabled` can override it. Enabled distributions are created once per unique operating-system and architecture pair. The global enable value, distribution encryption enablement, distribution KMS-key nullness, and access-logging bucket nullness must be known during planning because they determine module or resource shape. A distribution-bucket CMK grants the syncer access, but runner roles do not derive `kms:Decrypt` from that setting; attach decrypt permission to module-managed or external runner roles separately. + +Global `ssm.paths.root` is the base for shared and runner-configuration-owned parameters. The shared GitHub App and webhook paths append `ssm.paths.app` (default `app`) and `ssm.paths.webhook` (default `webhook`), while normalization appends the runner-configuration key only for configuration-owned paths. The default derived base is `/github-action-runners/${prefix}`, and runner token/config segments default to `runners/tokens` and `runners/config`. Global `ssm.kms_key_id` is an optional ARN-valued scalar that encrypts the shared GitHub App parameters, configures the webhook, and adds matching decrypt permissions to every runner configuration; it does not select encryption for runtime-created runner parameters. Webhook-provider leaves conditionally omit their KMS statements when this value is null, while apply-time-unknown key ARNs remain valid during planning. Nested metrics retain the established defaults: disabled, using the `GitHub Runners` namespace, with the rate-limit, job-retry, Spot-termination, and Spot-warning switches enabled. Spot metrics are global termination-watcher settings rather than per-configuration overrides. + +Each runner configuration selects two independent typed providers: one `orchestration` provider for demand control and one `compute_provider` for runner capacity. `orchestration.webhook` is the sole supported orchestration provider today. The global `experimental.compute_provider` block owns shared v2 provider defaults plus the runner-binary, termination-watcher, and AMI-housekeeper singleton configuration, but it does not select a provider. The wrapped provider objects reach runner-config, which validates each exact-one selection and dispatches the matching root-level provider module. `orchestration-providers/webhook` owns scale-up, scale-down, scheduled pool, job retry, and their webhook-specific defaults and tag layering; runner-config retains common SSM housekeeping plus the common runner role and attachments. The EC2 provider supplies EC2-specific policy requirements and owns the instance profile, launch template, bootstrap resources, and runner log groups. These modules are internal experimental implementation boundaries, not standalone public entry points. Later releases can add mutually exclusive orchestration siblings without changing the common or compute-provider contracts. See the [experimental compute-provider refactor](modules/internal/compute-provider-refactor.md) and [multi-runner v2 migration roadmap](modules/public/multi-runner.md#multi-runner-v2-migration-roadmap). EC2 is the only active Terraform-managed provider; microVM, CodeBuild, and other provider modules are future work. Both modules are built on top of the same base modules. When using the multi-runner module you can deploy different runners with only one deployment. diff --git a/docs/modules/internal/compute-provider-refactor.md b/docs/modules/internal/compute-provider-refactor.md new file mode 100644 index 0000000000..b93015541d --- /dev/null +++ b/docs/modules/internal/compute-provider-refactor.md @@ -0,0 +1,533 @@ +# Experimental compute-provider refactor + +!!! warning "Experimental opt-in" + + The provider-oriented Terraform interface is experimental. Its schema can change before it becomes stable. A non-empty `experimental.multi_runner_config` enables it for the whole module instance and takes priority over the stable top-level `multi_runner_config`; the two maps are not combined. When the experimental map is empty, existing stable `multi_runner_config` deployments continue to use the unchanged legacy implementation. + +## Why this refactor exists + +The scale-up, scale-down, pool, job-retry, queue, SSM housekeeping, and GitHub registration workflows are not inherently EC2-specific. The legacy `runners` module combines that common control plane with EC2 launch templates, instance profiles, bootstrap parameters, log groups, IAM permissions, and Lambda environment variables. Adding another compute provider in that structure would require copying common behavior or adding provider conditionals throughout the module. + +The refactor introduces a provider boundary so a future MicroVM or other backend can reuse the control plane. Only the policy statements, environment variables, and resources required by the selected compute provider should change. + +## Ownership model + +The implementation is split into demand-orchestration selection, provider-neutral control-plane components, and compute-provider implementations: + +| Layer | Owns | +| --- | --- | +| `multi-runner` | Module-level v1/v2 mode selection, flat/nested input projection, canonical global/runner-configuration resolution, typed orchestration and compute-provider routing, configuration keys, webhook build queues and matching, and runner-binary discovery. | +| `runner-config` | Typed orchestration and compute-provider dispatch, shared runner configuration in SSM, the SSM housekeeper, and the common runner role and policy attachments. | +| `orchestration-providers/webhook` | Webhook-provider selection contract, defaults and tag layering, plus composition of the provider-owned control-plane leaves. | +| `orchestration-providers/webhook/scale-runners` | Provider-neutral scale-up and scale-down Lambdas, schedules and queue integration, and their execution roles and policies. | +| `orchestration-providers/webhook/pool` | Optional scheduled runner-pool resources and their Lambda and IAM wiring. | +| `orchestration-providers/webhook/job-retry` | Optional queued-job retry resources and their Lambda and IAM wiring. | +| `runner-config/ssm-housekeeper` | Parameter Store cleanup Lambda, schedule, logging, and IAM resources. | +| `compute-providers//trust-policy` | Provider-specific default runner-role trust, merged with the optional caller-provided trust document before the common role is created. | +| `compute-providers/` | Provider-specific resources, permission requirements, and the IAM and environment-variable fragments consumed by the common control plane after the runner role is resolved. | + +The EC2 provider owns the instance profile, launch template, security group, AMI and bootstrap parameters, runner log groups, EC2 policy statements, and EC2 Lambda environment variables. EC2 is the only implemented Terraform compute provider in this phase. + +Runner-config, the root orchestration and compute providers, and their leaf modules are internal implementation boundaries rather than standalone public modules. Callers opt into the experimental interface through `experimental.multi_runner_config`; `multi-runner` calls `runner-config`, which selects the provider modules. Their direct input and output contracts may change while v2 remains experimental. + +Each external v2 runner configuration selects demand orchestration separately from its compute provider. The required `orchestration` wrapper has one supported provider today: `experimental.multi_runner_config..orchestration.webhook`. It owns the runner configuration's maximum runner count, registration scope, matcher, build-queue overrides, scale-up, scale-down, pool, and job-retry settings. The wrapper is intentionally typed as a provider boundary so later orchestration implementations can be added as mutually exclusive siblings without moving common configuration fields again. + +The runner configuration also populates exactly one typed compute-provider block, such as `experimental.multi_runner_config..compute_provider.ec2`; that block's presence must be known during planning because it determines capacity routing. Multi-runner module validation enforces both selections through resource preconditions, while each provider implementation owns its provider-specific semantic validation. + +After resolving global `experimental.compute_provider.ec2` values with the selected runner configuration's `compute_provider.ec2` overrides, `multi-runner` preserves the typed wrapper expected by `runner-config`. The direct contract is `compute_provider = { ec2 = { ... } }`, not a flat EC2 object. Runner-config validates that exactly one compute-provider block is non-null, derives the provider type from that block, and passes `compute_provider.` to the selected provider module as its nested `config` object. It independently validates the exact-one `orchestration = { webhook = { ... } }` wrapper and invokes the selected root orchestration provider with provider-neutral common objects such as `runner`, the Lambda substrate, SSM, observability, and the selected compute-provider capabilities. + +Binary discovery is completed before the runner-config call. `config.experimental.translation.tf` enriches the final canonical runner configuration at `compute_provider.ec2.binaries_syncer.s3`, leaving `s3` null when synchronization is disabled. The `module.runner_configs` call then passes that runner configuration's wrapped `compute_provider` object unchanged. Runner-config and the EC2 provider therefore receive the typed provider-owned shape; neither expects a bare `{ arn, id, key }` object directly at `compute_provider.binaries_syncer`. + +Runner-config creates or selects the runner IAM role, but the current EC2 provider owns the role's default trust-policy document. Each provider implementation supplies a small `trust-policy` submodule that accepts `additional_trust_policy_json` and returns the final `assume_role_policy`. The full provider separately returns its nested `provider` contract containing `policies.runner`, `policies.scale_up`, `policies.scale_down`, and `policies.pool`, component environment variables, and provider resources. Runner-config uses the isolated trust-policy output when it creates the runner role, attaches runner policies itself, and passes the scale-up, scale-down, and pool capabilities to the selected orchestration provider. A provider never creates or attaches the common runner IAM role. + +The trust relationship is deliberately rendered by an isolated provider submodule: + +1. `multi-runner` validates the runner configuration's typed orchestration and compute-provider selections, resolves its global and per-configuration values, and invokes `runner-config` with both wrapped provider configurations. +2. `runner-config` independently derives the orchestration and compute providers from their single non-null typed blocks. +3. `compute-providers//trust-policy` combines the provider default with `runner.iam.additional_trust_policy_json` without referencing the runner-role input. +4. `runner-config` creates or selects the common runner role from the returned `assume_role_policy`. +5. The full compute provider receives the resolved role so it can create resources such as the EC2 instance profile and render `iam:PassRole` statements. +6. The provider returns its nested policy, environment-variable, and resource contract. +7. Runner-config attaches runner policies, while `orchestration-providers/webhook` attaches scale-up, scale-down, and pool policy fragments to the roles it owns through its leaves. + +The trust-policy output depends only on its input documents, not on the full provider resources that consume the runner role. This preserves provider ownership of the trust relationship while keeping the dependency graph one-way. + +## Selection and canonical translation + +Multi-runner produces one canonical consumer representation for both input modes: + +1. `config.experimental.translation.tf` selects the module mode and builds `local.raw_translated_experimental`. A non-empty experimental runner-configuration map selects the nested `var.experimental` input for v2; otherwise the file projects flat module globals and stable `multi_runner_config` entries into the same schema for v1. +2. The same translation file then derives `local.translated_experimental_base`. It applies schema defaults and global/runner-configuration precedence, merges tags, resolves IAM ownership and paths, and normalizes observability, `orchestration.webhook`, and compute-provider values. Provider selection, plan-shaping validation, and the shared runner-binary syncer and discovery consume this fully resolved base. +3. After runner-binary discovery, the translation file derives the final `local.translated_experimental`. It completes runner labels, GitHub enterprise and User-Agent settings, webhook queue event mapping, Lambda artifact and principals, the webhook pool Lambda wrapper, SSM KMS, and each enabled EC2 runner configuration's `compute_provider.ec2.binaries_syncer.s3`. The remaining shared components, webhook queues, and runner implementations consume this final canonical object. + +Stable translation always emits `orchestration.webhook`, but stable runner configurations remain on `module.runners["configuration"]`: `runners.tf` adapts each final canonical runner configuration back to the existing `modules/runners` input contract, preserving Terraform addresses without maintaining a separate configuration source. This is not the phase-2 implementation migration to `runner-config`. For v2, `module.runner_configs` directly iterates the gated final runner-configuration map. Its input arguments inline the environment tag and live GitHub App and build-queue references into `orchestration.webhook`, then forward the complete orchestration and compute-provider wrappers. Binary output enrichment and all other derived configuration shaping are already complete in canonical translation. + +## Phase 1 dispatch and compatibility + +Phase 1 exposes both contracts with deterministic module-level precedence. An empty `experimental.multi_runner_config` selects the stable v1 path. A non-empty experimental map selects the v2 path and takes priority over the stable top-level `multi_runner_config`; entries from the maps are never combined. + +```mermaid +flowchart TD + Stable["top-level multi_runner_config and flat globals"] --> Select{"Is experimental.multi_runner_config non-empty?"} + Experimental["var.experimental"] --> Select + Select -->|No| V1["raw_translated_experimental: project flat v1"] + Select -->|Yes| V2["raw_translated_experimental: select nested v2"] + V1 --> Base["translated_experimental_base: defaults and global/configuration resolution"] + V2 --> Base + Base --> Discovery["Provider selection, runner-binary syncer, and discovery"] + Discovery --> Final["translated_experimental: enrich EC2 binaries_syncer.s3"] + Final --> Singleton["Shared SSM, webhook, termination watcher, and AMI housekeeper"] + Final --> Shared["Webhook build queues and matching"] + Final -->|v1 legacy-argument adapter| Legacy["module.runners[configuration]"] + Final -->|v2 direct module input adaptation| RunnerConfig["module.runner_configs[configuration]"] + RunnerConfig --> Orchestration["orchestration-providers/webhook"] + Orchestration --> Scaling["orchestration-providers/webhook/scale-runners"] + Orchestration --> Pool["orchestration-providers/webhook/pool"] + Orchestration --> Retry["orchestration-providers/webhook/job-retry"] + RunnerConfig --> Housekeeper["runner-config/ssm-housekeeper"] + RunnerConfig --> Trust["compute-providers/provider/trust-policy"] + Trust --> Role["common runner role"] + Role --> Provider + RunnerConfig --> Provider["compute-providers/"] + Provider --> Scaling + Provider --> Pool +``` + +The canonical object gives shared singleton resources one global representation and each webhook orchestration and runner implementation one fully resolved runner-configuration representation: + +- When `experimental.multi_runner_config` is empty, every key in the stable top-level `multi_runner_config` continues to call `modules/runners` at its historical `module.runners["configuration"]` address. +- Flat v1 inputs are projected into `raw_translated_experimental`, resolved into `translated_experimental_base`, finalized as `translated_experimental`, and then adapted by `runners.tf` to the existing child-module arguments. +- The v1 translation uses `runners_scale_up_lambda_timeout` for build-queue visibility, preserving the stable flat behavior. +- The v1 translation wraps its existing registration scope, matcher, queue, scale, pool, and retry values under `orchestration.webhook`; the stable public input and resource behavior remain unchanged. +- Stable queue tagging and the flat `runners_map` output remain unchanged. +- When `experimental.multi_runner_config` is non-empty, every key in the experimental map calls `modules/runner-config` at `module.runner_configs["configuration"]`; stable-map entries are not dispatched. +- Declarative `moved` blocks preserve the experimental call rename from `module.runner_stacks` to `module.runner_configs` and move the former runner-config scale, pool, and retry children directly beneath `module.webhook["webhook"]` without an intermediate state address. +- Experimental resources are exposed separately through the nested `runners_map_v2` output. +- The maps are not combined. A non-empty v2 map has explicit priority over the stable map. + +No v1-to-v2 state move is included in phase 1. Enabling v2 for a module instance that already manages v1 runners changes its implementation addresses; phase 1 does not migrate that state. Existing deployments should keep v2 empty until the documented state-migration phase. The current v2 path is intended for new or explicitly experimental deployments. + +## Opting in + +Nested global settings are the source of defaults for v2 runner configurations and the applicable singleton shared components. The GitHub App Parameter Store module, webhook, runner-binary syncer, termination watcher, and AMI housekeeper consume translated globals. Every v2 runner configuration must currently select `orchestration.webhook`; no other orchestration provider is implemented. The wrapper is the durable provider boundary for future mutually exclusive siblings. Migrated v2 consumers do not fall back to matching flat inputs; those values seed the stable-mode translation only. The singleton-specific webhook, binary-syncer, termination-watcher, and AMI-housekeeper settings all have nested owners. Only module naming (`prefix`), `aws_partition`, and `aws_region` remain active flat-only inputs; legacy `iam_overrides` remains in the input schema but has no active consumer. Per-configuration values override globals only inside that runner configuration and never configure singleton resources. Nested defaults mirror established v1 behavior, while nullable runner-configuration fields inherit the corresponding global when omitted or set to null. Set a global override only when the value is genuinely shared by every runner configuration, and put configuration-specific differences in that configuration itself. An external `runner.iam.role` is the exception to normal inheritance: inherited managed policies and additional trust policy JSON are suppressed because the module does not manage that role. + +```hcl +module "multi_runner" { + source = "github-aws-runners/github-runner/aws//modules/multi-runner" + + experimental = { + # Base tags for v2 queues and runner configurations and for translated singleton + # resources such as shared SSM, webhook, binary syncer, watcher, and AMI + # housekeeper. + tags = { + Workload = "runner-configurations" + ManagedBy = "terraform" + } + + roles = { + path = "/github-actions/" + } + + runner = { + os = "linux" + architecture = "arm64" + } + + github = { + # Required in v2. These nested values are authoritative for shared SSM + # and every v2 runner configuration. + app = var.github_app + additional_apps = var.additional_github_apps + + # The URL also configures the shared termination watcher. TLS verification + # and the User-Agent remain runner-config GitHub-client settings. + enterprise_server = { + url = var.ghes_url + ssl_verify = true + } + user_agent = "github-aws-runners" + } + + # Provider-neutral Lambda substrate shared by orchestration, runner SSM + # housekeeping, and other singleton consumers. + lambda = { + runtime = "nodejs24.x" + architecture = "arm64" + artifact = { + s3 = { + # Shared bucket only; every component selects its own object. + bucket = var.lambda_artifact_bucket + } + } + principals = var.additional_lambda_principals + } + + # Global defaults are grouped by orchestration provider. This block does + # not select a provider; each runner configuration has its own exact-one + # orchestration selector below. + orchestration = { + webhook = { + runner = { + boot_time_in_minutes = 5 + ephemeral = true + jit_config_enabled = null + maximum_count = 4 + } + + github = { + repository_white_list = [ + "example/example-repository", + ] + } + + queue_selection_strategy = "first" + eventbridge = { + enable = true + accept_events = [] + } + matcher_config_parameter_store_tier = "Standard" + + lambda = { + artifact = { + # Use zip instead for a local archive. Leave both fields null for + # the packaged runner archive shared by scale, pool, and job retry. + zip = null + s3 = { + key = "runner-config.zip" + object_version = null + } + } + + # Component S3 wrappers select objects from the shared + # experimental.lambda artifact bucket. + webhook = { + artifact = { + zip = null + s3 = { + key = "webhook.zip" + object_version = null + } + } + api_gateway_access_log_settings = { + destination_arn = aws_cloudwatch_log_group.webhook_access.arn + format = "$context.requestId" + } + memory_size = 512 + timeout = 10 + tags = { + Component = "webhook" + } + } + + scale = { + up = { + memory_size = 1024 + event_source_mapping = { + batch_size = 5 + } + } + down = { + memory_size = 512 + } + } + + pool = { + memory_size = 512 + } + } + + # Global webhook build-queue defaults. Visibility is independent of the + # scale-up Lambda timeout and must remain at least six times that + # timeout. Encryption is global-only; runner configurations cannot override it. + queue = { + delay_webhook_event = 30 + job_queue_retention_in_seconds = 86400 + visibility_timeout_seconds = 180 + redrive_build_queue = { + enabled = false + maxReceiveCount = null + } + tags = { + QueueOwner = "platform" + } + encryption = { + sqs_managed_sse_enabled = null + kms_master_key_id = aws_kms_key.github_app_parameters.arn + kms_data_key_reuse_period_seconds = 300 + } + } + } + } + + # Shared resources append app/webhook. Runner configurations append their key. + ssm = { + paths = { + root = "/github-actions" + app = "app" + webhook = "webhook" + } + + # This ARN-valued scalar may be unknown until apply. It encrypts shared + # app parameters, configures the webhook, and grants runner-config + # decrypt access. + kms_key_id = aws_kms_key.github_app_parameters.arn + + parameters = { + tags = { + DataClass = "runner-runtime" + } + } + + housekeeper = { + schedule_expression = "rate(12 hours)" + lambda = { + memory_size = 512 + } + } + } + + # Omitted observability fields retain the v2 schema defaults. For example, + # metrics default to disabled with the "GitHub Runners" namespace, while + # each individual metric switch defaults to enabled. + observability = { + logs = { + level = "info" + retention_in_days = 30 + tags = { + LogOwner = "platform" + } + } + tracing = { + mode = "Active" + } + metrics = { + enable = true + namespace = "GitHub Runners" + } + } + + # Shared v2 EC2 defaults. This block neither selects EC2 nor supplies + # required provider fields. Runner-binary settings are global because each + # syncer is shared by runner configurations with the same OS and architecture. + compute_provider = { + ec2 = { + vpc_id = var.vpc_id + subnet_ids = var.subnet_ids + + ami = { + housekeeper = { + enabled = true + cleanup_config = { + minimumDaysOld = 30 + dryRun = true + } + artifact = { + zip = null + s3 = { + key = "ami-housekeeper.zip" + object_version = null + } + } + lambda = { + memory_size = 256 + timeout = 300 + } + schedule = { + expression = "cron(11 7 * * ? *)" + } + } + } + + instance_termination_watcher = { + enabled = true + features = { + enable_spot_termination_handler = true + enable_spot_termination_notification_watcher = true + } + enable_runner_deregistration = true + environment_variables = {} + artifact = { + zip = null + s3 = { + key = "termination-watcher.zip" + object_version = null + } + } + lambda = { + memory_size = 512 + timeout = 30 + } + } + + runner_binaries = { + enabled = true + s3 = { + encryption = { + enabled = true + bucket_key_enabled = null + sse_algorithm = "AES256" + kms_master_key_id = null + } + tags = {} + versioning = "Disabled" + logging = { + bucket = null + prefix = null + } + } + syncer = { + # Both null selects the packaged syncer archive. Set at most one. + artifact = { + zip = null + s3 = null + } + lambda = { + memory_size = 256 + timeout = 300 + } + schedule = { + expression = "cron(27 * * * ? *)" + state = "ENABLED" + } + } + } + } + } + + multi_runner_config = { + arm = { + tags = { + Environment = "arm-runners" + } + + # Demand-control settings are selected through a typed orchestration + # provider. Webhook is the only supported provider today; future + # providers can be added as mutually exclusive siblings without moving + # these fields again. + orchestration = { + webhook = { + # This runner configuration overrides the webhook provider's global cap. + runner = { + boot_time_in_minutes = 7 + ephemeral = true + maximum_count = 8 + } + + github = { + organization_runners = true + } + lambda = { + scale = { + up = { + memory_size = 1536 + } + } + } + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "arm64"]] + } + } + } + + # A runner-configuration root is also a base; this resolves to + # /github-actions/high-capacity/arm for this entry. + ssm = { + paths = { + root = "/github-actions/high-capacity" + } + housekeeper = { + lambda = { + memory_size = 768 + } + } + } + + observability = { + logs = { + level = "debug" + } + metrics = { + namespace = "GitHub Runners Arm" + } + } + + # Each runner configuration also selects exactly one compute provider and supplies its + # provider-specific values here. + compute_provider = { + ec2 = { + instance_types = ["m7g.large"] + } + } + } + } + } +} +``` + +## Inputs, tags, and outputs + +The `experimental` object has global siblings for `tags`, `roles`, `runner`, `github`, `lambda`, `orchestration`, `ssm`, `observability`, and `compute_provider`, in addition to its runner-configuration map at `multi_runner_config`. Root `experimental.lambda` contains only provider-neutral shared Lambda substrate: the artifact bucket, runtime, architecture, principals, networking, role, and tag values. These settings configure v2 runner configurations and shared consumers beyond webhook orchestration, including the runner-binary syncer, termination watcher, AMI housekeeper, and per-configuration SSM housekeepers. `lambda.principals` configures v2 runner-config, runner-binary-syncer, termination-watcher, and AMI-housekeeper roles, but not the shared webhook role. Global webhook-specific defaults are grouped under `experimental.orchestration.webhook`: runner lifecycle, boot time, and maximum count; repository filtering; shared routing and matcher storage; queue defaults and encryption; the runner-control artifact shared by scale, pool, and job-retry; and the ingress webhook, scale, and pool Lambda component settings. The global orchestration block is a defaults namespace, while each runner configuration's separate `orchestration` wrapper is the exact-one provider selector. The termination watcher, AMI housekeeper, and runner-binary syncer retain their nested component owners under `compute_provider.ec2`. The active flat-only settings are `prefix`, `aws_partition`, and `aws_region`; legacy `iam_overrides` remains in the schema without an active consumer. + +Each v2 runner configuration groups common provider-neutral settings by owner under `runner`, `lambda`, `ssm`, and `observability`; backend settings live under `compute_provider.`. Demand-control settings live under a separate `orchestration` provider wrapper. Its sole supported block today is `orchestration.webhook`, containing provider-owned runner lifecycle, boot-time, and capacity settings, `github.organization_runners`, `matcherConfig`, `queue`, `lambda.scale.up`, `lambda.scale.down`, `lambda.pool`, and `job_retry`. A nullable per-configuration field inherits its corresponding experimental global when omitted or null, except that an external runner role suppresses inherited IAM management inputs. Precedence within a runner configuration is therefore a non-null configuration override followed by the global nested value, including that field's nested schema default. Per-configuration precedence does not extend to singleton shared resources: the webhook, runner-binary syncer, termination watcher, AMI housekeeper, and shared GitHub App Parameter Store module consume global translated values only. The runner-binary enable switch is an exception only in that it determines whether its OS/architecture pair participates in the shared syncer set; all syncer and distribution-bucket settings remain global. + +Global `experimental.orchestration.webhook.queue` owns v2 build-queue defaults. `delay_webhook_event` defaults to `30`, `job_queue_retention_in_seconds` to `86400`, `visibility_timeout_seconds` to `180`, and `tags` to `{}`. `redrive_build_queue.enabled` defaults to `false`, while `redrive_build_queue.maxReceiveCount` defaults to null. A null per-configuration redrive wrapper or leaf inherits its corresponding global value, and an enabled result requires a resolved `maxReceiveCount` greater than zero. Fields under `experimental.multi_runner_config[].orchestration.webhook.queue` override those global defaults, and runner-configuration queue tags merge over global queue tags. Build-queue visibility is independent from Lambda configuration: `experimental.multi_runner_config[].orchestration.webhook.lambda.scale.up.timeout` controls the function only, while `experimental.multi_runner_config[].orchestration.webhook.queue.visibility_timeout_seconds` controls SQS and must be at least six times the resolved scale-up timeout. + +Queue encryption is global-only. Omitting the entire `experimental.orchestration.webhook.queue.encryption` block defaults `sqs_managed_sse_enabled` to `true` and the KMS fields to null, matching flat `queue_encryption`. If callers supply an explicit block, all three leaf keys are required: use explicit nulls for inactive fields, with a non-null SQS-managed switch for the non-KMS mode or a non-null `kms_master_key_id` for KMS mode. It configures the multi-runner build queues and their dead-letter queues, not the webhook provider's separate job-retry queue. Runner configurations cannot override encryption. The queue CMK and `experimental.ssm.kms_key_id` are independent and are forwarded separately to `orchestration-providers/webhook`: scale-up receives queue-key `kms:Decrypt`, job-retry receives queue-key `kms:Decrypt` and `kms:GenerateDataKey`, and both retain separate Parameter Store decrypt statements. The existing shared `modules/webhook` contract remains unchanged and still requires caller-supplied key access when it publishes to customer-managed encrypted queues. The v1 translation retains the flat contract: per-configuration delay, retention, redrive, and tags keep their stable sources, build-queue visibility comes from `runners_scale_up_lambda_timeout`, and encryption comes from `queue_encryption`. + +Global `experimental.github` owns the GitHub App credentials persisted or selected by shared SSM and used by v2 runner configurations: `app` is required and `additional_apps` defaults to `[]`. `experimental.orchestration.webhook.github.repository_white_list` defaults to `[]` and filters the shared webhook when populated. `experimental.github.enterprise_server.url` defaults to `null` and configures both runner-config GitHub clients and the shared termination watcher. `experimental.github.enterprise_server.ssl_verify` defaults to `true`, and `experimental.github.user_agent` defaults to `github-aws-runners`; both remain runner-config client settings. Neither field is a root `experimental` sibling. Per-configuration `orchestration.webhook.github.organization_runners` is the separate registration-scope setting; runner configurations do not override credentials, repository filtering, the enterprise endpoint, or the User-Agent. + +Shared SSM creates or selects Parameter Store credentials from the authoritative `experimental.github` object, and the webhook and every v2 runner configuration consume the resulting references. Flat `github_app` and `additional_github_apps` seed only the stable-mode translation and impose no equality requirement in v2. The webhook does not make GitHub API requests. + +Global `experimental.orchestration.webhook` configures the shared webhook's queue-selection strategy, EventBridge implementation and accepted events, and matcher-configuration Parameter Store tier in addition to its queue and Lambda component defaults. `orchestration.webhook.eventbridge.enable` and the matcher tier must be known during planning because they select module or parameter-chunk shape. `first` deterministically chooses the first equally matched queue by priority, `random` spreads jobs among equals, and `all` sends a job to every match at the cost of multiple runner launches and registrations. + +Global `ssm.paths.root` is the base for shared GitHub App and webhook parameters and for every runner configuration. Shared resources append the global-only `ssm.paths.app` and `ssm.paths.webhook` segments, which default to `app` and `webhook`; normalization appends the runner-configuration key only for configuration-owned roots, keeping runner parameters isolated. The derived global base defaults to `/github-action-runners/${prefix}`, while runner token and config segments default to `runners/tokens` and `runners/config`. Global `ssm.tags` augments the base tags on the shared Parameter Store module and also defaults configuration-owned SSM tags; `ssm.parameters.tags` remains specific to configuration-managed and runtime-created runner parameters. The global housekeeper defaults preserve the established schedule, enabled state, Lambda artifact, sizing, and cleanup behavior; a nullable per-configuration field inherits those values. Avoid setting a global `ssm.housekeeper.config.tokenPath` unless every runner configuration is intentionally meant to clean the same path; omitting it lets each runner configuration derive its isolated token path. + +Global `observability` values provide defaults for every runner configuration and configure the applicable shared singleton consumers. Log level, retention, KMS key, class, and tracing configure the webhook, runner-binary syncer, termination watcher, and AMI housekeeper; metrics also configure the termination watcher. The nested defaults preserve established behavior: logs use level `info`, 180-day retention, no customer-managed KMS key, and class `STANDARD`; tracing defaults to no mode with HTTP and error capture disabled; metrics default to disabled in the `GitHub Runners` namespace while the rate-limit, job-retry, Spot-termination, and Spot-warning switches default to enabled. The two Spot switches are global termination-watcher settings and have no per-configuration override. Other nullable runner-configuration observability fields inherit the global value. `observability.logs.tags` remains specific to runner-config-owned log groups; shared singleton functions receive global `tags` and `lambda.tags`. The nullness of `observability.tracing.mode` must be known during planning because it selects X-Ray IAM statements and tracing blocks in runner-config consumers. + +The global `experimental.compute_provider` block owns v2 defaults for EC2 settings such as VPC and subnet IDs, managed-security-group behavior, egress rules, additional security groups, CloudWatch agent configuration, instance-profile path, key name, public IPv4 association, and tags. It also owns the shared AMI housekeeper, instance-termination watcher, and runner-binary distribution. It does not fall back to corresponding flat module inputs. VPC and subnet values must therefore be supplied through the global or per-configuration EC2 block when needed. Global values should be set only when they are shared across every applicable runner configuration. The global block never selects a provider and does not contain provider-specific required runner-configuration fields. Every runner configuration must still populate exactly one typed provider block; that per-configuration block selects the provider, supplies required fields such as EC2 `instance_types`, and preserves support for mixed-provider maps. + +`experimental.compute_provider.ec2.runner_binaries` owns whether EC2 runner configurations use the shared binary distribution by default, distribution-bucket encryption, tags, versioning and access logging, and syncer artifact, Lambda sizing, and schedule. A nullable per-configuration `compute_provider.ec2.binaries_syncer.enabled` overrides only the global enable default. The resolved enable value, `runner_binaries.s3.encryption.enabled`, the nullness of its `kms_master_key_id`, and the nullness of `runner_binaries.s3.logging.bucket` must be known during planning because they control module or resource shape. KMS encryption grants the syncer access to the distribution key, but runner roles do not derive `kms:Decrypt` from that field; callers must attach decrypt permission to the module-managed or external runner roles separately. + +Webhook-orchestration runner-control artifacts are selected globally through `experimental.orchestration.webhook.lambda.artifact.zip` or `experimental.orchestration.webhook.lambda.artifact.s3.{key,object_version}` and shared by scale, pool, and job-retry. The S3 wrapper selects an object from the shared `experimental.lambda.artifact.s3.bucket`; null zip and S3 wrappers use the packaged runner archive. V2 validation rejects simultaneous zip and S3 selection and requires a non-null shared bucket and key when the S3 wrapper is present. Stable-mode translation preserves the old S3-wins rule by clearing the translated zip and creating the runner artifact's S3 wrapper whenever the flat `lambda_s3_bucket` is set. The shared bucket alone selects no component. Every artifact-capable singleton uses its own `artifact.s3` wrapper to supply that component's key and optional object version. Runner-config's common SSM housekeeper independently resolves `multi_runner_config[].ssm.housekeeper.lambda.artifact` over the global `experimental.ssm.housekeeper.lambda.artifact`; S3 combines the component key and version with the shared artifact bucket, zip uses the selected local path, and no selection uses the packaged control-plane archive. Stable translation maps the existing runner artifact into this separate canonical component contract. The ingress webhook artifact remains separate under `experimental.orchestration.webhook.lambda.webhook.artifact`; the runner-binary syncer uses the parallel `compute_provider.ec2.runner_binaries.syncer.artifact.{zip,s3}` selector, whose S3 key and optional object version resolve against the same shared bucket. `compute_provider.ec2.instance_termination_watcher` owns watcher enablement, feature flags, runner deregistration, environment, artifact, and sizing. `compute_provider.ec2.ami.housekeeper` owns enablement, cleanup behavior, artifact, sizing, and schedule. Watcher enablement and feature flags, runner-deregistration enablement, and AMI-housekeeper enablement must be known during planning because they control child resource shape. + +Tags follow the same ownership model but merge rather than replace. Within v2 webhook queue and runner-config scopes, experimental global tags merge with runner-configuration tags and then with orchestration component or subcomponent tags from broad to narrow; a narrower value wins for a duplicate key. Singleton shared resources use only global scopes: shared SSM merges `experimental.tags` with `ssm.tags`, the webhook merges `experimental.lambda.tags` with `experimental.orchestration.webhook.lambda.webhook.tags`, and the runner-binary syncer, termination watcher, and AMI housekeeper receive global `tags` and `lambda.tags`. Distribution buckets additionally merge `compute_provider.ec2.runner_binaries.s3.tags`. EC2 global provider tags merge with per-configuration `compute_provider.ec2.tags`. EC2 runtime tags belong under `compute_provider.ec2.tags`; bootstrap tags required by the runner are reserved inside the provider and are not propagated to common resources. + +Application logging settings stay together under `observability.logs`, including `level`, retention, encryption, class, and runner-configuration log-group tags. Tracing stays under `observability.tracing`, and metrics enablement, namespace, and individual metric switches stay under `observability.metrics`. + +In v1 mode, entries remain exclusively in `runners_map` and retain their flat output fields; `runners_map_v2` is empty. In v2 mode, entries are exposed exclusively through `runners_map_v2` and `runners_map` is empty. Common resources are grouped under `runner`, demand-control resources under `orchestration.webhook`, and provider-specific resources under `provider.`. The provider key is derived from the selected typed compute-provider block. For example, the common runner role is available at `runners_map_v2["configuration"].runner.role`, scale-up resources at `runners_map_v2["configuration"].orchestration.webhook.scale_up`, and launch-template and runner-log artifacts under `runners_map_v2["configuration"].provider.ec2`. The webhook `pool` value is null when no pool configuration is supplied. + +## Plan-time provider selection and IAM shape + +Terraform must know resource and dynamic-block shape during planning, even when an ARN is produced by another resource and remains unknown until apply. Provider ownership inputs continue to use caller-known wrapper objects as discriminators. The webhook orchestration leaves conditionally emit KMS statements from the nullable Parameter Store and build-queue key scalars; a null value omits the statement, while an apply-time-unknown ARN remains valid during planning. No placeholder or sentinel ARN is rendered. The relevant configuration fragments are: + +```hcl +ssm = { + kms_key_id = aws_kms_key.runner_parameters.arn +} + +compute_provider = { + ec2 = { + ami = { + id_ssm_parameter = { + arn = aws_ssm_parameter.runner_ami.arn + } + kms_key = { + arn = aws_kms_key.runner_ami.arn + } + } + } +} +``` + +The populated `ec2` block tells both multi-runner routing and runner-config dispatch which provider implementation exists and must therefore be known during planning. Canonical translation preserves that wrapper, and the `module.runner_configs` input forwards it unchanged at the runner-config boundary. The orchestration wrapper follows the same exact-one rule. Within the compute block, each ownership-wrapper object tells Terraform that the corresponding policy exists; its `arn` may safely be computed. `ssm.kms_key_id`, `orchestration.webhook.queue.kms_key_id`, and values such as `observability.logs.kms_key_id` remain nullable scalar inputs even when their ARNs are unknown until apply. + +For experimental multi-runner v2, global `experimental.ssm.kms_key_id` encrypts the shared GitHub App parameters, configures the webhook with the same key, and adds matching decrypt permissions to every runner configuration so its control-plane functions can read those credentials. Its value may be unknown until apply. It does not select encryption for runtime-created runner parameters. Queue encryption is a separate global contract, may use a different CMK, and reaches only the scale-up consumer and job-retry publisher policies inside the webhook orchestration provider. + +## Migration phases + +1. **Phase 1 — v2 opt-in and canonical translation (current):** A non-empty experimental map opts the whole module instance into v2, while an empty map preserves the existing `module.runners["configuration"]` addresses. Both stable and experimental inputs already resolve through the same canonical pipeline. The v2 switch is not an in-place state migration. +2. **Phase 2 — deprecate legacy variables:** Deprecate the stable `multi_runner_config` and migrated flat inputs while retaining both dispatch paths and compatibility outputs for a release window. +3. **Phase 3 — remove legacy variables and migrate state:** In a breaking release, remove the deprecated inputs and flat output adapter, route the remaining canonical configuration through `runner-config`, and ship tested `moved` blocks plus commands for addresses Terraform cannot move declaratively. +4. **Phase 4 — remove `modules/runners`:** After direct consumers have had a separate deprecation and migration window, delete the legacy module. + +A future compute provider must add a typed external input block, multi-runner normalization and routing, and an integration that returns the same nested environment-variable, policy, and resource contract before it can be selected in Terraform. Populating more than one external provider block, or selecting a block whose resources are not implemented, is intentionally rejected. diff --git a/mkdocs.yaml b/mkdocs.yaml index 9b98e84a36..d974019b1b 100644 --- a/mkdocs.yaml +++ b/mkdocs.yaml @@ -57,6 +57,8 @@ nav: - Configuration: configuration.md - Getting started: getting-started.md - Security: security.md + - Architecture decisions: + - ADR-002 Runner orchestration provider boundary: adr/002-runner-orchestration-provider-boundary.md - Modules: - Runners (main): modules/runners.md - Submodules (public): @@ -65,6 +67,7 @@ nav: - Lambda Downloader: modules/public/download-lambda.md - Setup IAM permissions: modules/public/setup-iam-permissions.md - Submodules (internal): + - Compute provider refactor (experimental): modules/internal/compute-provider-refactor.md - Runners: modules/internal/runners.md - Syncer: modules/internal/runner-binaries-syncer.md - SSM: modules/internal/ssm.md diff --git a/modules/compute-providers/ec2/README.md b/modules/compute-providers/ec2/README.md new file mode 100644 index 0000000000..1963eea11f --- /dev/null +++ b/modules/compute-providers/ec2/README.md @@ -0,0 +1,80 @@ +# EC2 runner provider + +This internal module owns the EC2 compute implementation used by the common runner configuration. It creates the runner launch template, security group, instance profile, EC2 bootstrap parameters, and runner log groups. + +The module returns one nested `provider` contract. It groups EC2-specific Lambda settings under `environment_variables`, permission requirements under `policies.runner`, `policies.scale_up`, `policies.scale_down`, and `policies.pool`, and EC2 artifacts under `resources`. The parent runner configuration owns the shared runner role, provider-policy attachments, Lambda functions, execution roles, schedules, queues, retry flow, and SSM housekeeper. + +EC2 is the only active compute provider. The parent runner configuration selects it when `ec2` is the one populated typed block under `compute_provider`; no separate type input is required. A future provider must add its own typed block and implement the same contracts before it can be selected. + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.4.0 | +| [aws](#requirement\_aws) | >= 6.33 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.33 | +| [terraform](#provider\_terraform) | n/a | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_log_group.gh_runners](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_iam_instance_profile.runner](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_instance_profile) | resource | +| [aws_iam_policy.ami_id_ssm_parameter_read](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_policy) | resource | +| [aws_launch_template.runner](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/launch_template) | resource | +| [aws_security_group.runner_sg](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group) | resource | +| [aws_ssm_parameter.cloudwatch_agent_config_runner](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [aws_ssm_parameter.runner_ami_id](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [aws_ssm_parameter.runner_config_run_as](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [aws_ssm_parameter.runner_enable_cloudwatch](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [terraform_data.validate_config](https://registry.terraform.io/providers/hashicorp/terraform/latest/docs/resources/data) | resource | +| [terraform_data.validate_runner](https://registry.terraform.io/providers/hashicorp/terraform/latest/docs/resources/data) | resource | +| [aws_ami.runner](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami) | data source | +| [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | +| [aws_iam_policy_document.ami_id_ssm_parameter_read](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.cloudwatch](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.create_tags](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.describe_tags](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.distribution_bucket](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_up](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.service_linked_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.session_manager](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.ssm_parameters](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.terminate_self](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [aws\_partition](#input\_aws\_partition) | AWS partition used to construct IAM ARNs. | `string` | `"aws"` | no | +| [aws\_region](#input\_aws\_region) | AWS region used by compute-provider resources and policy documents. | `string` | n/a | yes | +| [config](#input\_config) | EC2 compute-provider configuration. Paths match `compute_provider.ec2` in the runner configuration.

- `ami`: Optional AMI discovery and encryption configuration. Null selects defaults for `runner.os` and `runner.architecture`.
- `ami.filter`: AMI filter names mapped to accepted values and merged over the provider defaults.
- `ami.owners`: AWS account IDs or aliases allowed to own the selected AMI.
- `ami.id_ssm_parameter`: Optional externally managed SSM parameter containing the AMI ID. Its object presence is the plan-time ownership discriminator.
- `ami.id_ssm_parameter.arn`: ARN of the external AMI-ID parameter. The ARN may remain unknown until apply.
- `ami.kms_key`: Optional customer-managed KMS key required for encrypted AMIs or snapshots. Its object presence is the plan-time policy discriminator.
- `ami.kms_key.arn`: ARN of the AMI KMS key. The ARN may remain unknown until apply.
- `vpc_id`: VPC in which runner networking resources are created.
- `subnet_ids`: Subnets from which the control plane may launch runners.
- `overrides.name_runner`: Optional Name tag override for runner compute resources.
- `overrides.name_sg`: Optional Name tag override for the managed security group.
- `instance_profile`: Optional externally managed instance profile. Its object presence is the plan-time ownership discriminator.
- `instance_profile.name`: Name of the external instance profile. The name may remain unknown until apply.
- `instance_profile_path`: IAM path for the provider-managed instance profile. Null derives the path from `prefix`.
- `binaries_syncer.enabled`: Uses the synchronized runner distribution from S3 during bootstrap.
- `binaries_syncer.s3`: S3 object containing the synchronized runner distribution. Required when synchronization is enabled.
- `binaries_syncer.s3.arn`: Runner-distribution bucket ARN used by IAM policies.
- `binaries_syncer.s3.id`: Runner-distribution bucket name used in the bootstrap URI.
- `binaries_syncer.s3.key`: Runner-distribution object key.
- `block_device_mappings`: EBS mappings added to the launch template.
- `block_device_mappings[].delete_on_termination`: Deletes the volume when its runner terminates.
- `block_device_mappings[].device_name`: Device name exposed to the runner instance.
- `block_device_mappings[].encrypted`: Enables EBS encryption.
- `block_device_mappings[].iops`: Provisioned IOPS for volume types that support configurable IOPS.
- `block_device_mappings[].kms_key_id`: KMS key ID or ARN used to encrypt the volume.
- `block_device_mappings[].snapshot_id`: Snapshot used to initialize the volume.
- `block_device_mappings[].throughput`: Provisioned throughput for volume types that support it.
- `block_device_mappings[].volume_initialization_rate`: Fixed initialization rate for supported snapshot-backed volumes.
- `block_device_mappings[].volume_size`: EBS volume size in GiB.
- `block_device_mappings[].volume_type`: EBS volume type.
- `ebs_optimized`: Requests EBS-optimized instances.
- `instance_target_capacity_type`: Primary capacity type, either `spot` or `on-demand`.
- `instance_allocation_strategy`: EC2 Fleet allocation strategy.
- `instance_type_priorities`: Optional numeric priorities keyed by instance type.
- `instance_max_spot_price`: Optional maximum hourly Spot price.
- `instance_types`: EC2 instance types available to the control plane.
- `user_data`: Runner bootstrap user-data configuration.
- `user_data.enabled`: Enables launch-template user data.
- `user_data.template`: Optional path to a custom user-data template.
- `user_data.content`: Optional complete user-data content used instead of a template.
- `user_data.pre_install`: Script inserted before runner installation.
- `user_data.post_install`: Script inserted after runner installation.
- `user_data.debug_logging_enabled`: Enables verbose user-data tracing, which can expose secrets.
- `ssm_enabled`: Includes Session Manager permissions in the provider's runner policy group.
- `create_service_linked_role_spot`: Allows scale-up to create the EC2 Spot service-linked role.
- `cloudwatch_agent.enabled`: Enables CloudWatch agent configuration for runner instances.
- `cloudwatch_agent.config`: Optional complete CloudWatch agent configuration.
- `managed_security_group_enabled`: Creates and attaches the provider-managed security group.
- `log_files`: Optional files collected by the CloudWatch agent. Null uses provider defaults.
- `log_files[].log_group_name`: CloudWatch log-group name before optional prefixing.
- `log_files[].prefix_log_group`: Prefixes the log-group name with the runner configuration path.
- `log_files[].file_path`: File or glob read by the CloudWatch agent.
- `log_files[].log_stream_name`: CloudWatch log-stream name template.
- `log_files[].log_class`: CloudWatch log-group class for the collected file.
- `key_name`: Optional EC2 key-pair name.
- `additional_security_group_ids`: Existing security groups attached to runners.
- `detailed_monitoring_enabled`: Enables detailed EC2 monitoring.
- `egress_rules`: Rules created on the managed security group.
- `egress_rules[].cidr_blocks`: IPv4 CIDR destinations.
- `egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations.
- `egress_rules[].prefix_list_ids`: AWS prefix-list destinations.
- `egress_rules[].from_port`: First destination port in the permitted range.
- `egress_rules[].protocol`: IP protocol name or number. Use `-1` for all protocols.
- `egress_rules[].security_groups`: Destination security-group IDs.
- `egress_rules[].self`: Allows traffic to the managed security group itself.
- `egress_rules[].to_port`: Last destination port in the permitted range.
- `egress_rules[].description`: Optional rule description.
- `tags`: Runner instance, volume, network-interface, and eligible Spot-request tags. Provider-required bootstrap tags take final precedence.
- `metadata_options`: Instance Metadata Service configuration.
- `metadata_options.instance_metadata_tags`: Exposes instance tags through Instance Metadata Service when enabled.
- `metadata_options.http_endpoint`: Enables or disables the Instance Metadata Service endpoint.
- `metadata_options.http_tokens`: Controls whether IMDSv2 session tokens are optional or required.
- `metadata_options.http_put_response_hop_limit`: Network hop limit for Instance Metadata Service token responses.
- `credit_specification`: CPU credit mode for burstable instance types.
- `cpu_options`: CPU topology and processor-feature configuration.
- `cpu_options.core_count`: Number of CPU cores exposed to the runner instance.
- `cpu_options.threads_per_core`: Number of hardware threads exposed per CPU core.
- `cpu_options.amd_sev_snp`: Enables or disables AMD SEV-SNP on supported instance types.
- `cpu_options.nested_virtualization`: Enables or disables nested virtualization on supported instance types.
- `placement`: EC2 placement configuration.
- `placement.affinity`: Dedicated Host affinity setting.
- `placement.availability_zone`: Availability Zone in which runner instances are placed.
- `placement.group_id`: Placement-group ID.
- `placement.group_name`: Placement-group name.
- `placement.host_id`: Dedicated Host ID.
- `placement.host_resource_group_arn`: ARN of the host resource group used for placement.
- `placement.spread_domain`: Spread-domain placement value.
- `placement.tenancy`: Instance tenancy, such as `default`, `dedicated`, or `host`.
- `placement.partition_number`: Placement-group partition number.
- `license_specifications`: License Manager configurations added to the launch template.
- `license_specifications[].license_configuration_arn`: ARN of an AWS License Manager license configuration.
- `associate_public_ipv4_address`: Associates a public IPv4 address with runner network interfaces.
- `enable_on_demand_failover_for_errors`: EC2 errors that trigger on-demand fallback after a Spot failure.
- `scale_errors`: EC2 errors treated as retryable scale-up failures.
- `use_dedicated_host`: Enables the dedicated-host launch path. |
object({
ami = optional(object({
filter = optional(map(list(string)), { state = ["available"] })
owners = optional(list(string), ["amazon"])
id_ssm_parameter = optional(object({
arn = string
}), null)
kms_key = optional(object({
arn = string
}), null)
}), null)
vpc_id = string
subnet_ids = list(string)
overrides = optional(object({
name_runner = optional(string, "")
name_sg = optional(string, "")
}), {})
instance_profile = optional(object({
name = string
}), null)
instance_profile_path = optional(string, null)
binaries_syncer = optional(object({
enabled = optional(bool, true)
s3 = optional(object({
arn = string
id = string
key = string
}), null)
}), {})
block_device_mappings = optional(list(object({
delete_on_termination = optional(bool, true)
device_name = optional(string, "/dev/xvda")
encrypted = optional(bool, true)
iops = optional(number)
kms_key_id = optional(string)
snapshot_id = optional(string)
throughput = optional(number)
volume_initialization_rate = optional(number)
volume_size = number
volume_type = optional(string, "gp3")
})), [{ volume_size = 30 }])
ebs_optimized = optional(bool, false)
instance_target_capacity_type = optional(string, "spot")
instance_allocation_strategy = optional(string, "lowest-price")
instance_type_priorities = optional(map(number), null)
instance_max_spot_price = optional(string, null)
instance_types = list(string)
user_data = optional(object({
enabled = optional(bool, true)
template = optional(string, null)
content = optional(string, null)
pre_install = optional(string, "")
post_install = optional(string, "")
debug_logging_enabled = optional(bool, false)
}), {})
ssm_enabled = optional(bool, false)
create_service_linked_role_spot = optional(bool, false)
cloudwatch_agent = optional(object({
enabled = optional(bool, true)
config = optional(string, null)
}), {})
managed_security_group_enabled = optional(bool, true)
log_files = optional(list(object({
log_group_name = string
prefix_log_group = bool
file_path = string
log_stream_name = string
log_class = optional(string, "STANDARD")
})), null)
key_name = optional(string, null)
additional_security_group_ids = optional(list(string), [])
detailed_monitoring_enabled = optional(bool, false)
egress_rules = optional(list(object({
cidr_blocks = list(string)
ipv6_cidr_blocks = list(string)
prefix_list_ids = list(string)
from_port = number
protocol = string
security_groups = list(string)
self = bool
to_port = number
description = string
})), [{
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
prefix_list_ids = null
from_port = 0
protocol = "-1"
security_groups = null
self = null
to_port = 0
description = null
}])
tags = optional(map(string), {})
metadata_options = optional(object({
instance_metadata_tags = optional(string, "enabled")
http_endpoint = optional(string, "enabled")
http_tokens = optional(string, "required")
http_put_response_hop_limit = optional(number, 1)
}), {})
credit_specification = optional(string, null)
cpu_options = optional(object({
core_count = optional(number)
threads_per_core = optional(number)
amd_sev_snp = optional(string)
nested_virtualization = optional(string)
}), null)
placement = optional(object({
affinity = optional(string)
availability_zone = optional(string)
group_id = optional(string)
group_name = optional(string)
host_id = optional(string)
host_resource_group_arn = optional(string)
spread_domain = optional(string)
tenancy = optional(string)
partition_number = optional(number)
}), null)
license_specifications = optional(list(object({
license_configuration_arn = string
})), [])
associate_public_ipv4_address = optional(bool, false)
enable_on_demand_failover_for_errors = optional(list(string), [])
scale_errors = optional(list(string), [
"UnfulfillableCapacity",
"MaxSpotInstanceCountExceeded",
"TargetCapacityLimitExceededException",
"RequestLimitExceeded",
"ResourceLimitExceeded",
"MaxSpotInstanceCountExceeded",
"MaxSpotFleetRequestCountExceeded",
"InsufficientInstanceCapacity",
"InsufficientCapacityOnHost",
])
use_dedicated_host = optional(bool, false)
})
| n/a | yes | +| [github](#input\_github) | GitHub Enterprise Server settings available to compute-provider bootstrap data.

- `enterprise_server.url`: Optional GitHub Enterprise Server base URL. Null selects GitHub.com.
- `enterprise_server.ssl_verify`: Enables TLS certificate verification for GitHub Enterprise Server. |
object({
enterprise_server = optional(object({
url = optional(string, null)
ssl_verify = optional(bool, true)
}), {})
})
| `{}` | no | +| [observability](#input\_observability) | CloudWatch Logs settings available to compute-provider runner log groups.

- `logs.retention_in_days`: Retention period for provider-owned runner log groups.
- `logs.kms_key_id`: Optional KMS key ID or ARN used to encrypt runner log groups.
- `logs.tags`: Shared log-group tags that override module-level `tags`. |
object({
logs = optional(object({
retention_in_days = optional(number, 180)
kms_key_id = optional(string, null)
tags = optional(map(string), {})
}), {})
})
| `{}` | no | +| [prefix](#input\_prefix) | Prefix used to identify resources created for the runner configuration. | `string` | `"github-actions"` | no | +| [runner](#input\_runner) | Provider-neutral runner settings consumed by compute providers.

- `os`: Runner operating system. Supported values are `linux`, `osx`, and `windows`.
- `architecture`: Runner distribution architecture.
- `name_prefix`: Prefix added to registered runner names.
- `run_as_root`: Runs the runner service as root.
- `run_as`: Operating-system user used when `run_as_root` is false.
- `hooks.job_started`: Script installed as the runner job-started hook.
- `hooks.job_completed`: Script installed as the runner job-completed hook.
- `iam.role.arn`: Resolved runner-role ARN referenced by provider policies and resources.
- `iam.role.name`: Resolved runner-role name used by provider resources.
- `iam.role.managed`: Whether runner-config manages the resolved runner role.
- `iam.managed_policy_arns`: Common managed-policy ARNs returned with the provider-specific runner policies for attachment by runner-config.
- `iam.path`: IAM path available to provider-managed IAM resources. Null derives the path from `prefix`. |
object({
os = optional(string, "linux")
architecture = optional(string, "x64")
name_prefix = optional(string, "")
run_as_root = optional(bool, false)
run_as = optional(string, "ec2-user")
hooks = optional(object({
job_started = optional(string, "")
job_completed = optional(string, "")
}), {})
iam = object({
role = object({
arn = string
name = string
managed = optional(bool, true)
})
managed_policy_arns = optional(map(string), {})
path = optional(string, null)
})
})
| n/a | yes | +| [ssm](#input\_ssm) | Parameter Store paths and tag scopes available to compute-provider bootstrap resources.

- `paths.root`: Root Parameter Store path for the runner configuration.
- `paths.tokens`: Path segment used for registration tokens and just-in-time configuration.
- `paths.config`: Path segment used for persistent runner and provider configuration.
- `tags`: Shared SSM tags that override module-level `tags`.
- `parameters.tags`: Parameter-specific tags that override module-level and shared SSM tags. |
object({
paths = object({
root = string
tokens = string
config = string
})
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
}), {})
})
| n/a | yes | +| [tags](#input\_tags) | Base tags available to taggable compute-provider resources. Provider-specific tags override this map within their documented scopes. | `map(string)` | `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [environment\_variables](#output\_environment\_variables) | Provider-specific Lambda environment variable fragments consumed by runner-config. | +| [policies](#output\_policies) | Provider-specific IAM policy fragments consumed by runner-config. | +| [provider](#output\_provider) | Nested EC2 compute-provider contract consumed by runner-config. | +| [resources](#output\_resources) | Provider-specific EC2 resources exposed by runner-config. | + diff --git a/modules/compute-providers/ec2/control-plane.tf b/modules/compute-providers/ec2/control-plane.tf new file mode 100644 index 0000000000..d476f91cb4 --- /dev/null +++ b/modules/compute-providers/ec2/control-plane.tf @@ -0,0 +1,216 @@ +# EC2-specific IAM and environment fragments consumed by the common control +# plane in runner-config. +data "aws_iam_policy_document" "ami_id_ssm_parameter_read" { + count = local.ami_id_ssm_external ? 1 : 0 + + statement { + effect = "Allow" + actions = ["ssm:GetParameter"] + resources = [local.ami_id_ssm_parameter_arn] + } +} + +resource "aws_iam_policy" "ami_id_ssm_parameter_read" { + count = local.ami_id_ssm_external ? 1 : 0 + name = "${var.prefix}-ami-id-ssm-parameter-read" + path = local.role_path + description = "Allows for reading ${var.prefix} GitHub runner AMI ID from an SSM parameter" + tags = local.provider_tags + policy = data.aws_iam_policy_document.ami_id_ssm_parameter_read[0].json +} + +data "aws_iam_policy_document" "scale_up" { + statement { + effect = "Allow" + actions = [ + "ec2:DescribeInstances", + "ec2:DescribeLaunchTemplateVersions", + "ec2:DescribeTags", + "ec2:RunInstances", + "ec2:CreateFleet", + "ec2:CreateTags", + ] + resources = ["*"] + } + + statement { + effect = "Allow" + actions = ["ec2:TerminateInstances"] + resources = ["*"] + + condition { + test = "StringEquals" + variable = "ec2:ResourceTag/ghr:Application" + values = ["github-action-runner"] + } + } + + statement { + effect = "Allow" + actions = ["ec2:TerminateInstances"] + resources = ["*"] + + condition { + test = "StringEquals" + variable = "ec2:ResourceTag/ghr:environment" + values = [var.prefix] + } + } + + statement { + effect = "Allow" + actions = ["iam:PassRole"] + resources = [var.runner.iam.role.arn] + } + + statement { + effect = "Allow" + actions = ["ssm:GetParameter", "ssm:GetParameters"] + resources = [local.ami_id_ssm_module_managed ? aws_ssm_parameter.runner_ami_id[0].arn : local.ami_id_ssm_parameter_arn] + } + + dynamic "statement" { + for_each = local.ami_kms_key_enabled ? [local.ami_kms_key_arn] : [] + + content { + effect = "Allow" + actions = ["kms:DescribeKey", "kms:ReEncrypt*", "kms:Decrypt"] + resources = [statement.value] + } + } + + dynamic "statement" { + for_each = local.ami_kms_key_enabled ? [local.ami_kms_key_arn] : [] + + content { + effect = "Allow" + actions = ["kms:CreateGrant"] + resources = [statement.value] + + condition { + test = "Bool" + variable = "aws:ViaAWSService" + values = ["true"] + } + } + } +} + +data "aws_iam_policy_document" "scale_down" { + statement { + effect = "Allow" + actions = ["ec2:DescribeInstances", "ec2:DescribeTags"] + resources = ["*"] + } + + statement { + effect = "Allow" + actions = ["ec2:TerminateInstances", "ec2:CreateTags", "ec2:DeleteTags"] + resources = ["*"] + + condition { + test = "StringEquals" + variable = "ec2:ResourceTag/ghr:Application" + values = ["github-action-runner"] + } + } + + statement { + effect = "Allow" + actions = ["ec2:TerminateInstances", "ec2:CreateTags", "ec2:DeleteTags"] + resources = ["*"] + + condition { + test = "StringEquals" + variable = "ec2:ResourceTag/ghr:environment" + values = [var.prefix] + } + } +} + +data "aws_iam_policy_document" "pool" { + statement { + effect = "Allow" + actions = [ + "ec2:DescribeInstances", + "ec2:DescribeTags", + "ec2:RunInstances", + "ec2:CreateFleet", + "ec2:CreateTags", + ] + resources = ["*"] + } + + statement { + effect = "Allow" + actions = ["iam:PassRole"] + resources = [var.runner.iam.role.arn] + } + + statement { + effect = "Allow" + actions = ["ssm:GetParameters"] + resources = [local.ami_id_ssm_module_managed ? aws_ssm_parameter.runner_ami_id[0].arn : local.ami_id_ssm_parameter_arn] + } + + dynamic "statement" { + for_each = local.ami_kms_key_enabled ? [local.ami_kms_key_arn] : [] + + content { + effect = "Allow" + actions = ["kms:DescribeKey", "kms:ReEncrypt*", "kms:Decrypt"] + resources = [statement.value] + } + } + + dynamic "statement" { + for_each = local.ami_kms_key_enabled ? [local.ami_kms_key_arn] : [] + + content { + effect = "Allow" + actions = ["kms:CreateGrant"] + resources = [statement.value] + + condition { + test = "Bool" + variable = "aws:ViaAWSService" + values = ["true"] + } + } + } +} + +data "aws_iam_policy_document" "service_linked_role" { + count = var.config.create_service_linked_role_spot ? 1 : 0 + + statement { + effect = "Allow" + actions = ["iam:CreateServiceLinkedRole"] + resources = ["arn:${var.aws_partition}:iam::*:role/aws-service-role/*"] + } +} + +locals { + scale_up_environment_variables = { + AMI_ID_SSM_PARAMETER_NAME = local.ami_id_ssm_parameter_name + INSTANCE_ALLOCATION_STRATEGY = var.config.instance_allocation_strategy + INSTANCE_MAX_SPOT_PRICE = var.config.instance_max_spot_price + INSTANCE_TARGET_CAPACITY_TYPE = var.config.instance_target_capacity_type + INSTANCE_TYPE_PRIORITIES = var.config.instance_type_priorities != null ? jsonencode(var.config.instance_type_priorities) : "" + INSTANCE_TYPES = join(",", var.config.instance_types) + LAUNCH_TEMPLATE_NAME = aws_launch_template.runner.name + SUBNET_IDS = join(",", var.config.subnet_ids) + ENABLE_ON_DEMAND_FAILOVER_FOR_ERRORS = jsonencode(var.config.enable_on_demand_failover_for_errors) + SCALE_ERRORS = jsonencode(var.config.scale_errors) + USE_DEDICATED_HOST = var.config.use_dedicated_host + } + + scale_down_environment_variables = {} + + pool_environment_variables = local.scale_up_environment_variables + + scale_up_iam_policy_json = data.aws_iam_policy_document.scale_up.json + scale_down_iam_policy_json = data.aws_iam_policy_document.scale_down.json + pool_iam_policy_json = data.aws_iam_policy_document.pool.json + service_linked_role_policy_json = var.config.create_service_linked_role_spot ? data.aws_iam_policy_document.service_linked_role[0].json : null +} diff --git a/modules/compute-providers/ec2/instance-profile.tf b/modules/compute-providers/ec2/instance-profile.tf new file mode 100644 index 0000000000..f01a865f73 --- /dev/null +++ b/modules/compute-providers/ec2/instance-profile.tf @@ -0,0 +1,9 @@ +# The common runner configuration owns the role; EC2 owns the profile consumed by its +# launch template. +resource "aws_iam_instance_profile" "runner" { + count = var.config.instance_profile == null ? 1 : 0 + name = "${var.prefix}-runner-profile" + role = var.runner.iam.role.name + path = local.instance_profile_path + tags = local.provider_tags +} diff --git a/modules/compute-providers/ec2/logging.tf b/modules/compute-providers/ec2/logging.tf new file mode 100644 index 0000000000..00ae952e4d --- /dev/null +++ b/modules/compute-providers/ec2/logging.tf @@ -0,0 +1,75 @@ +# EC2 runner log collection and CloudWatch resources. +locals { + runner_log_files = ( + var.config.log_files != null + ? var.config.log_files + : [ + { + "prefix_log_group" : true, + "file_path" : "/var/log/messages", + "log_group_name" : "messages", + "log_stream_name" : "{instance_id}", + "log_class" : "STANDARD" + }, + { + "log_group_name" : "user_data", + "prefix_log_group" : true, + "file_path" : var.runner.os == "windows" ? "C:/UserData.log" : "/var/log/user-data.log", + "log_stream_name" : "{instance_id}", + "log_class" : "STANDARD" + }, + { + "log_group_name" : "runner", + "prefix_log_group" : true, + "file_path" : var.runner.os == "windows" ? "C:/actions-runner/_diag/Runner_*.log" : "/opt/actions-runner/_diag/Runner_**.log", + "log_stream_name" : "{instance_id}", + "log_class" : "STANDARD" + }, + { + "log_group_name" : "runner-startup", + "prefix_log_group" : true, + "file_path" : var.runner.os == "windows" ? "C:/runner-startup.log" : "/var/log/runner-startup.log", + "log_stream_name" : "{instance_id}", + "log_class" : "STANDARD" + } + ] + ) + # CloudWatch agent collect_list schema expects log_group_class, not log_class + logfiles = var.config.cloudwatch_agent.enabled ? [for l in local.runner_log_files : { + "log_group_name" : l.prefix_log_group ? "/github-self-hosted-runners/${var.prefix}/${l.log_group_name}" : "/${l.log_group_name}" + "log_stream_name" : l.log_stream_name + "file_path" : l.file_path + "log_group_class" : l.log_class + }] : [] + + loggroups_names = distinct([for l in local.logfiles : l.log_group_name]) + # Create a list of unique log classes corresponding to each log group name + # This maintains the same order as loggroups_names for use with count + loggroups_classes = [ + for name in local.loggroups_names : [ + for l in local.logfiles : l.log_group_class + if l.log_group_name == name + ][0] + ] + +} + + +resource "aws_ssm_parameter" "cloudwatch_agent_config_runner" { + count = var.config.cloudwatch_agent.enabled ? 1 : 0 + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/cloudwatch_agent_config_runner" + type = "String" + value = var.config.cloudwatch_agent.config != null ? var.config.cloudwatch_agent.config : templatefile("${path.module}/templates/cloudwatch_config.json", { + logfiles = jsonencode(local.logfiles) + }) + tags = local.ssm_parameter_tags +} + +resource "aws_cloudwatch_log_group" "gh_runners" { + count = length(local.loggroups_names) + name = local.loggroups_names[count.index] + retention_in_days = var.observability.logs.retention_in_days + kms_key_id = var.observability.logs.kms_key_id + log_group_class = local.loggroups_classes[count.index] + tags = local.log_group_tags +} diff --git a/modules/compute-providers/ec2/outputs.tf b/modules/compute-providers/ec2/outputs.tf new file mode 100644 index 0000000000..422383df0f --- /dev/null +++ b/modules/compute-providers/ec2/outputs.tf @@ -0,0 +1,23 @@ +output "environment_variables" { + description = "Provider-specific Lambda environment variable fragments consumed by runner-config." + value = local.provider_environment_variables +} + +output "policies" { + description = "Provider-specific IAM policy fragments consumed by runner-config." + value = local.provider_policies +} + +output "resources" { + description = "Provider-specific EC2 resources exposed by runner-config." + value = local.provider_resources +} + +output "provider" { + description = "Nested EC2 compute-provider contract consumed by runner-config." + value = { + environment_variables = local.provider_environment_variables + policies = local.provider_policies + resources = local.provider_resources + } +} diff --git a/modules/compute-providers/ec2/policies-runner.tf b/modules/compute-providers/ec2/policies-runner.tf new file mode 100644 index 0000000000..c16077debc --- /dev/null +++ b/modules/compute-providers/ec2/policies-runner.tf @@ -0,0 +1,206 @@ +# EC2 runner permission documents returned to runner-config for attachment to +# the common runner role. +data "aws_caller_identity" "current" {} + +locals { + ssm_parameter_arn_prefix = "arn:${var.aws_partition}:ssm:${var.aws_region}:${data.aws_caller_identity.current.account_id}:parameter" + ssm_config_arn = "${local.ssm_parameter_arn_prefix}${var.ssm.paths.root}/${var.ssm.paths.config}" + cloudwatch_config_arn = "${local.ssm_config_arn}/cloudwatch_agent_config_runner" +} + +data "aws_iam_policy_document" "ssm_parameters" { + statement { + effect = "Allow" + actions = [ + "ssm:DeleteParameter", + "ssm:GetParameters", + "ssm:GetParameter", + ] + resources = [ + "${local.ssm_parameter_arn_prefix}${var.ssm.paths.root}/${var.ssm.paths.tokens}/*", + ] + + condition { + test = "StringLike" + variable = "ec2:SourceInstanceARN" + values = ["*/&{aws:ResourceTag/InstanceId}"] + } + } + + statement { + effect = "Allow" + actions = [ + "ssm:GetParameter", + "ssm:GetParameters", + "ssm:GetParametersByPath", + ] + resources = [ + local.ssm_config_arn, + "${local.ssm_config_arn}/*", + ] + } +} + +data "aws_iam_policy_document" "session_manager" { + statement { + effect = "Allow" + actions = [ + "ssm:DescribeAssociation", + "ssm:GetDeployablePatchSnapshotForInstance", + "ssm:GetDocument", + "ssm:DescribeDocument", + "ssm:GetManifest", + "ssm:ListAssociations", + "ssm:ListInstanceAssociations", + "ssm:PutInventory", + "ssm:PutComplianceItems", + "ssm:PutConfigurePackageResult", + "ssm:UpdateAssociationStatus", + "ssm:UpdateInstanceAssociationStatus", + "ssm:UpdateInstanceInformation", + ] + resources = ["*"] + } + + statement { + effect = "Allow" + actions = [ + "ssmmessages:CreateControlChannel", + "ssmmessages:CreateDataChannel", + "ssmmessages:OpenControlChannel", + "ssmmessages:OpenDataChannel", + ] + resources = ["*"] + } + + statement { + effect = "Allow" + actions = [ + "ec2messages:AcknowledgeMessage", + "ec2messages:DeleteMessage", + "ec2messages:FailMessage", + "ec2messages:GetEndpoint", + "ec2messages:GetMessages", + "ec2messages:SendReply", + ] + resources = ["*"] + } +} + +data "aws_iam_policy_document" "distribution_bucket" { + count = var.config.binaries_syncer.enabled ? 1 : 0 + + statement { + sid = "githubActionDist" + effect = "Allow" + actions = ["s3:GetObject", "s3:GetObjectAcl"] + resources = ["${try(var.config.binaries_syncer.s3.arn, "")}/${try(var.config.binaries_syncer.s3.key, "")}"] + } +} + +data "aws_iam_policy_document" "describe_tags" { + statement { + effect = "Allow" + actions = ["ec2:DescribeTags"] + resources = ["*"] + } +} + +data "aws_iam_policy_document" "create_tags" { + statement { + effect = "Allow" + actions = ["ec2:CreateTags"] + resources = ["arn:*:ec2:*:*:instance/*"] + + condition { + test = "ForAllValues:StringEquals" + variable = "aws:TagKeys" + values = ["ghr:github_runner_id"] + } + + condition { + test = "StringEquals" + variable = "aws:ARN" + values = ["&{ec2:SourceInstanceARN}"] + } + } +} + +data "aws_iam_policy_document" "terminate_self" { + statement { + effect = "Allow" + actions = ["ec2:TerminateInstances"] + resources = ["*"] + + condition { + test = "StringEquals" + variable = "aws:ARN" + values = ["&{ec2:SourceInstanceARN}"] + } + } +} + +data "aws_iam_policy_document" "cloudwatch" { + count = var.config.cloudwatch_agent.enabled ? 1 : 0 + + statement { + effect = "Allow" + actions = [ + "cloudwatch:PutMetricData", + "ec2:DescribeVolumes", + "ec2:DescribeTags", + "logs:PutLogEvents", + "logs:DescribeLogStreams", + "logs:DescribeLogGroups", + "logs:CreateLogStream", + ] + resources = ["*"] + } + + statement { + effect = "Allow" + actions = ["ssm:GetParameter"] + resources = ["${local.cloudwatch_config_arn}/*"] + } +} + +locals { + runner_inline_policies = merge( + { + ssm_parameters = { + name = "runner-ssm-parameters" + policy_json = data.aws_iam_policy_document.ssm_parameters.json + } + describe_tags = { + name = "runner-describe-tags" + policy_json = data.aws_iam_policy_document.describe_tags.json + } + create_tags = { + name = "runner-create-tags" + policy_json = data.aws_iam_policy_document.create_tags.json + } + terminate_self = { + name = "ec2" + policy_json = data.aws_iam_policy_document.terminate_self.json + } + }, + var.config.ssm_enabled ? { + session_manager = { + name = "runner-ssm-session" + policy_json = data.aws_iam_policy_document.session_manager.json + } + } : {}, + var.config.binaries_syncer.enabled ? { + distribution_bucket = { + name = "distribution-bucket" + policy_json = data.aws_iam_policy_document.distribution_bucket[0].json + } + } : {}, + var.config.cloudwatch_agent.enabled ? { + cloudwatch = { + name = "CloudWatchLogginAndMetrics" + policy_json = data.aws_iam_policy_document.cloudwatch[0].json + } + } : {}, + ) +} diff --git a/modules/compute-providers/ec2/provider-contract.tf b/modules/compute-providers/ec2/provider-contract.tf new file mode 100644 index 0000000000..5682496d78 --- /dev/null +++ b/modules/compute-providers/ec2/provider-contract.tf @@ -0,0 +1,34 @@ +locals { + provider_environment_variables = { + scale_up = local.scale_up_environment_variables + scale_down = local.scale_down_environment_variables + pool = local.pool_environment_variables + } + + provider_policies = { + runner = { + inline_policies = local.runner_inline_policies + managed_policy_arns = var.runner.iam.managed_policy_arns + } + scale_up = { + iam_policy_json = local.scale_up_iam_policy_json + additional_iam_policy_json = local.service_linked_role_policy_json + managed_policy_enabled = local.ami_id_ssm_external + managed_policy_arn = local.ami_id_ssm_external ? aws_iam_policy.ami_id_ssm_parameter_read[0].arn : null + } + scale_down = { + iam_policy_json = local.scale_down_iam_policy_json + } + pool = { + iam_policy_json = local.pool_iam_policy_json + managed_policy_enabled = local.ami_id_ssm_external + managed_policy_arn = local.ami_id_ssm_external ? aws_iam_policy.ami_id_ssm_parameter_read[0].arn : null + } + } + + provider_resources = { + launch_template = aws_launch_template.runner + runners_log_groups = try(aws_cloudwatch_log_group.gh_runners, []) + logfiles = local.logfiles + } +} diff --git a/modules/compute-providers/ec2/runner-config.tf b/modules/compute-providers/ec2/runner-config.tf new file mode 100644 index 0000000000..f1d859581c --- /dev/null +++ b/modules/compute-providers/ec2/runner-config.tf @@ -0,0 +1,13 @@ +resource "aws_ssm_parameter" "runner_config_run_as" { + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/run_as" + type = "String" + value = var.runner.run_as_root ? "root" : var.runner.run_as + tags = local.ssm_parameter_tags +} + +resource "aws_ssm_parameter" "runner_enable_cloudwatch" { + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/enable_cloudwatch" + type = "String" + value = var.config.cloudwatch_agent.enabled + tags = local.ssm_parameter_tags +} diff --git a/modules/compute-providers/ec2/runner-instances.tf b/modules/compute-providers/ec2/runner-instances.tf new file mode 100644 index 0000000000..e965d8f66c --- /dev/null +++ b/modules/compute-providers/ec2/runner-instances.tf @@ -0,0 +1,325 @@ +# AMI selection, bootstrap rendering, launch template, and security group for +# EC2 runner instances. +locals { + provider_tags = merge( + { + "Name" = format("%s-action-runner", var.prefix) + }, + var.tags, + ) + + ssm_parameter_tags = merge( + local.provider_tags, + var.ssm.tags, + var.ssm.parameters.tags, + ) + + log_group_tags = merge( + local.provider_tags, + var.observability.logs.tags, + ) + + name_sg = var.config.overrides.name_sg == "" ? local.provider_tags["Name"] : var.config.overrides.name_sg + name_runner = var.config.overrides.name_runner == "" ? local.provider_tags["Name"] : var.config.overrides.name_runner + runner_tags = merge( + local.provider_tags, + { + "Name" = local.name_runner + }, + var.config.tags, + { + "ghr:environment" = var.prefix + "ghr:ssm_config_path" = "${var.ssm.paths.root}/${var.ssm.paths.config}" + "ghr:runner_name_prefix" = var.runner.name_prefix + }, + ) + + role_path = var.runner.iam.path == null ? "/${var.prefix}/" : var.runner.iam.path + instance_profile_path = var.config.instance_profile_path == null ? "/${var.prefix}/" : var.config.instance_profile_path + userdata_template = var.config.user_data.template == null ? local.default_userdata_template[var.runner.os] : var.config.user_data.template + s3_location_runner_distribution = var.config.binaries_syncer.enabled ? "s3://${try(var.config.binaries_syncer.s3.id, "")}/${try(var.config.binaries_syncer.s3.key, "")}" : "" + default_ami = { + "windows" = { name = ["Windows_Server-2022-English-Full-ECS_Optimized-*"] } + "linux" = var.runner.architecture == "arm64" ? { name = ["al2023-ami-2023.*-kernel-6.*-arm64"] } : { name = ["al2023-ami-2023.*-kernel-6.*-x86_64"] } + "osx" = var.runner.architecture == "arm64" ? { name = ["amzn-ec2-macos-15.*-arm64"] } : { name = ["amzn-ec2-macos-15.*"] } + } + + default_userdata_template = { + "windows" = "${path.module}/templates/user-data.ps1" + "linux" = "${path.module}/templates/user-data.sh" + "osx" = "${path.module}/templates/user-data-osx.sh" + } + + userdata_install_runner = { + "windows" = "${path.module}/templates/install-runner.ps1" + "linux" = "${path.module}/templates/install-runner.sh" + "osx" = "${path.module}/templates/install-runner-osx.sh" + } + + userdata_start_runner = { + "windows" = "${path.module}/templates/start-runner.ps1" + "linux" = "${path.module}/templates/start-runner.sh" + "osx" = "${path.module}/templates/start-runner-osx.sh" + } + + # Handle AMI configuration + ami_config = var.config.ami != null ? var.config.ami : { + filter = local.default_ami[var.runner.os] + owners = ["amazon"] + id_ssm_parameter = null + kms_key = null + } + ami_kms_key_enabled = local.ami_config.kms_key != null + ami_kms_key_arn = local.ami_kms_key_enabled ? local.ami_config.kms_key.arn : null + ami_filter = merge(local.default_ami[var.runner.os], local.ami_config.filter) + ami_id_ssm_external = local.ami_config.id_ssm_parameter != null + ami_id_ssm_module_managed = !local.ami_id_ssm_external + ami_id_ssm_parameter_arn = local.ami_id_ssm_external ? local.ami_config.id_ssm_parameter.arn : null + # Extract parameter name from ARN (format: arn:aws:ssm:region:account:parameter/path/to/param) + ami_id_ssm_parameter_name = local.ami_id_ssm_external ? try(regex("parameter(/.+)$", local.ami_id_ssm_parameter_arn)[0], null) : null + + user_data = var.config.user_data.enabled ? (var.config.user_data.content == null ? templatefile(local.userdata_template, { + enable_debug_logging = var.config.user_data.debug_logging_enabled + s3_location_runner_distribution = local.s3_location_runner_distribution + pre_install = var.config.user_data.pre_install + install_runner = templatefile(local.userdata_install_runner[var.runner.os], { + S3_LOCATION_RUNNER_DISTRIBUTION = local.s3_location_runner_distribution + RUNNER_ARCHITECTURE = var.runner.architecture + }) + post_install = var.config.user_data.post_install + hook_job_started = var.runner.hooks.job_started + hook_job_completed = var.runner.hooks.job_completed + start_runner = templatefile(local.userdata_start_runner[var.runner.os], { + metadata_tags = var.config.metadata_options != null ? var.config.metadata_options.instance_metadata_tags : "enabled" + }) + ghes_url = var.github.enterprise_server.url + ghes_ssl_verify = var.github.enterprise_server.ssl_verify + + ## retain these for backwards compatibility + environment = var.prefix + enable_cloudwatch_agent = var.config.cloudwatch_agent.enabled + ssm_key_cloudwatch_agent_config = var.config.cloudwatch_agent.enabled ? aws_ssm_parameter.cloudwatch_agent_config_runner[0].name : "" + }) : var.config.user_data.content) : "" + + encoded_user_data = ( + var.runner.os == "linux" ? base64gzip(local.user_data) : + var.runner.os == "windows" ? base64encode(local.user_data) : + var.runner.os == "osx" ? base64encode(local.user_data) : + null + ) +} + +data "aws_ami" "runner" { + most_recent = "true" + + dynamic "filter" { + for_each = local.ami_filter + content { + name = filter.key + values = filter.value + } + } + + owners = local.ami_config.owners +} + +resource "aws_ssm_parameter" "runner_ami_id" { + count = local.ami_id_ssm_module_managed ? 1 : 0 + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/ami_id" + type = "String" + data_type = "aws:ec2:image" + value = data.aws_ami.runner.id + + tags = merge( + local.provider_tags, + local.ssm_parameter_tags, + { + # Remove parentheses from AMI name to comply with AWS tag constraints + "ghr:ami_name" = replace(data.aws_ami.runner.name, "/[()]/", "") + }, + { + "ghr:ami_creation_date" = data.aws_ami.runner.creation_date + }, + { + "ghr:ami_deprecation_time" = data.aws_ami.runner.deprecation_time + } + ) +} + +resource "aws_launch_template" "runner" { + name = "${var.prefix}-action-runner" + + dynamic "block_device_mappings" { + for_each = var.config.block_device_mappings != null ? var.config.block_device_mappings : [] + content { + device_name = block_device_mappings.value.device_name + + ebs { + delete_on_termination = block_device_mappings.value.delete_on_termination + encrypted = block_device_mappings.value.encrypted + iops = block_device_mappings.value.iops + kms_key_id = block_device_mappings.value.kms_key_id + snapshot_id = block_device_mappings.value.snapshot_id + throughput = block_device_mappings.value.throughput + volume_initialization_rate = block_device_mappings.value.volume_initialization_rate + volume_size = block_device_mappings.value.volume_size + volume_type = block_device_mappings.value.volume_type + } + } + } + + dynamic "metadata_options" { + for_each = var.config.metadata_options != null ? [var.config.metadata_options] : [] + + content { + http_endpoint = metadata_options.value.http_endpoint + http_tokens = metadata_options.value.http_tokens + http_put_response_hop_limit = metadata_options.value.http_put_response_hop_limit + instance_metadata_tags = metadata_options.value.instance_metadata_tags + } + } + + dynamic "metadata_options" { + for_each = var.config.metadata_options != null ? [] : [0] + + content { + instance_metadata_tags = "enabled" + } + } + + dynamic "credit_specification" { + for_each = var.config.credit_specification != null ? [var.config.credit_specification] : [] + content { + cpu_credits = credit_specification.value + } + } + + dynamic "cpu_options" { + for_each = var.config.cpu_options != null ? [var.config.cpu_options] : [] + content { + core_count = try(cpu_options.value.core_count, null) + threads_per_core = try(cpu_options.value.threads_per_core, null) + amd_sev_snp = try(cpu_options.value.amd_sev_snp, null) + nested_virtualization = try(cpu_options.value.nested_virtualization, null) + } + } + + dynamic "placement" { + for_each = var.config.placement != null ? [var.config.placement] : [] + content { + affinity = try(placement.value.affinity, null) + availability_zone = try(placement.value.availability_zone, null) + group_id = try(placement.value.group_id, null) + group_name = try(placement.value.group_name, null) + host_id = try(placement.value.host_id, null) + host_resource_group_arn = try(placement.value.host_resource_group_arn, null) + spread_domain = try(placement.value.spread_domain, null) + tenancy = try(placement.value.tenancy, null) + partition_number = try(placement.value.partition_number, null) + } + } + + dynamic "license_specification" { + for_each = var.config.license_specifications + content { + license_configuration_arn = license_specification.value.license_configuration_arn + } + } + + monitoring { + enabled = var.config.detailed_monitoring_enabled + } + + iam_instance_profile { + name = var.config.instance_profile != null ? var.config.instance_profile.name : aws_iam_instance_profile.runner[0].name + } + + instance_initiated_shutdown_behavior = "terminate" + image_id = "resolve:ssm:${local.ami_id_ssm_module_managed ? aws_ssm_parameter.runner_ami_id[0].arn : local.ami_id_ssm_parameter_arn}" + key_name = var.config.key_name + ebs_optimized = var.config.ebs_optimized + + vpc_security_group_ids = !var.config.associate_public_ipv4_address ? compact(concat( + var.config.managed_security_group_enabled ? [aws_security_group.runner_sg[0].id] : [], + var.config.additional_security_group_ids, + )) : [] + + tag_specifications { + resource_type = "instance" + tags = local.runner_tags + } + + tag_specifications { + resource_type = "volume" + tags = local.runner_tags + } + + # We avoid including the "spot-instances-request" tag_specifications block when on_demand_failover_for_errors is defined, + # because when using on-demand fallback, the spot instance request resource is not created and thus the tags would not apply. + # Additionally, tagging spot requests via the CreateFleetCommand in the Lambda function does not work as expected, + # so we rely on Terraform to manage these tags only when spot is exclusively used without on-demand failover. + dynamic "tag_specifications" { + for_each = var.config.instance_target_capacity_type == "spot" && length(var.config.enable_on_demand_failover_for_errors) == 0 ? [1] : [] # Include the block only if the value is "spot" and on_demand_failover_for_errors is not enabled + content { + resource_type = "spot-instances-request" + tags = local.runner_tags + } + } + + tag_specifications { + resource_type = "network-interface" + tags = local.runner_tags + } + + user_data = local.encoded_user_data + + tags = local.provider_tags + + update_default_version = true + + dynamic "network_interfaces" { + for_each = var.config.associate_public_ipv4_address ? [var.config.associate_public_ipv4_address] : [] + iterator = associate_public_ipv4_address + content { + associate_public_ip_address = associate_public_ipv4_address.value + security_groups = compact(concat( + var.config.managed_security_group_enabled ? [aws_security_group.runner_sg[0].id] : [], + var.config.additional_security_group_ids, + )) + } + } +} + +resource "aws_security_group" "runner_sg" { + count = var.config.managed_security_group_enabled ? 1 : 0 + name_prefix = "${var.prefix}-github-actions-runner-sg" + description = "Github Actions Runner security group" + + vpc_id = var.config.vpc_id + + ingress = [] + + dynamic "egress" { + for_each = var.config.egress_rules + iterator = each + + content { + cidr_blocks = each.value.cidr_blocks + ipv6_cidr_blocks = each.value.ipv6_cidr_blocks + prefix_list_ids = each.value.prefix_list_ids + from_port = each.value.from_port + protocol = each.value.protocol + security_groups = each.value.security_groups + self = each.value.self + to_port = each.value.to_port + description = each.value.description + } + } + + tags = merge( + local.provider_tags, + { + "Name" = format("%s", local.name_sg) + }, + ) +} diff --git a/modules/compute-providers/ec2/templates/cloudwatch_config.json b/modules/compute-providers/ec2/templates/cloudwatch_config.json new file mode 100644 index 0000000000..47b9bede8a --- /dev/null +++ b/modules/compute-providers/ec2/templates/cloudwatch_config.json @@ -0,0 +1,12 @@ +{ + "agent": { + "metrics_collection_interval": 5 + }, + "logs": { + "logs_collected": { + "files": { + "collect_list": ${logfiles} + } + } + } +} diff --git a/modules/compute-providers/ec2/templates/install-runner-osx.sh b/modules/compute-providers/ec2/templates/install-runner-osx.sh new file mode 100644 index 0000000000..ed848dad27 --- /dev/null +++ b/modules/compute-providers/ec2/templates/install-runner-osx.sh @@ -0,0 +1,61 @@ +# shellcheck shell=bash + +set -euo pipefail + +## install the runner (macOS) + +s3_location=${S3_LOCATION_RUNNER_DISTRIBUTION} +architecture=${RUNNER_ARCHITECTURE} + +if [ -z "$RUNNER_TARBALL_URL" ] && [ -z "$s3_location" ]; then + echo "Neither RUNNER_TARBALL_URL or s3_location are set" + exit 1 +fi + +file_name="actions-runner.tar.gz" + +echo "Setting up GH Actions runner tool cache" +mkdir -p /Users/runner/hostedtoolcache + +echo "Creating actions-runner directory for the GH Action installation" +sudo mkdir -p /opt/actions-runner +cd /opt/actions-runner || exit 1 + +if [[ -n "$runner_tarball_url" ]]; then + echo "Downloading the GH Action runner from $runner_tarball_url to $file_name" + curl -s -o "$file_name" -L "$runner_tarball_url" +else + echo "Retrieving REGION from AWS API" + token="$(curl -s -f -X PUT "http://169.254.169.254/latest/api/token" \ + -H "X-aws-ec2-metadata-token-ttl-seconds: 180")" + + region="$(curl -s -f -H "X-aws-ec2-metadata-token: $token" \ + http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)" + echo "Retrieved REGION from AWS API ($region)" + + echo "Downloading the GH Action runner from s3 bucket $s3_location" + aws s3 cp "$s3_location" "$file_name" --region "$region" --no-progress +fi + +echo "Un-tar action runner" +tar xzf "./$file_name" +echo "Delete tar file" +rm -rf "$file_name" + +os_name=$(sw_vers -productName 2>/dev/null || echo "macOS") +os_version=$(sw_vers -productVersion 2>/dev/null || echo "unknown") +arch_name=$(uname -m) + +echo "OS: $os_name $os_version ($arch_name)" + +if ! command -v brew >/dev/null 2>&1; then + echo "Homebrew not found; skipping dependency installation via brew" +else + echo "Homebrew detected; install any macOS-specific dependencies here if needed" + # Example: brew install jq awscli +fi + +echo "Set file ownership of action runner" +sudo chown -R "$user_name":staff /opt/actions-runner +sudo chmod 755 "/Users/runner" +sudo chown -R "$user_name":staff /Users/runner/hostedtoolcache diff --git a/modules/compute-providers/ec2/templates/install-runner.ps1 b/modules/compute-providers/ec2/templates/install-runner.ps1 new file mode 100644 index 0000000000..a13f91a65b --- /dev/null +++ b/modules/compute-providers/ec2/templates/install-runner.ps1 @@ -0,0 +1,13 @@ +## install the runner + +Write-Host "Creating actions-runner directory for the GH Action installation" +New-Item -ItemType Directory -Path C:\actions-runner ; Set-Location C:\actions-runner + +Write-Host "Downloading the GH Action runner from s3 bucket $s3_location" +aws s3 cp ${S3_LOCATION_RUNNER_DISTRIBUTION} actions-runner.zip + +Write-Host "Un-zip action runner" +Expand-Archive -Path actions-runner.zip -DestinationPath . + +Write-Host "Delete zip file" +Remove-Item actions-runner.zip diff --git a/modules/compute-providers/ec2/templates/install-runner.sh b/modules/compute-providers/ec2/templates/install-runner.sh new file mode 100644 index 0000000000..5ed5897e7c --- /dev/null +++ b/modules/compute-providers/ec2/templates/install-runner.sh @@ -0,0 +1,73 @@ +# shellcheck shell=bash + +## install the runner + +s3_location=${S3_LOCATION_RUNNER_DISTRIBUTION} + +if [ -z "$RUNNER_TARBALL_URL" ] && [ -z "$s3_location" ]; then + echo "Neither RUNNER_TARBALL_URL or s3_location are set" + exit 1 +fi + +file_name="actions-runner.tar.gz" + +echo "Setting up GH Actions runner tool cache" +# Required for various */setup-* actions to work, location is also know by various environment +# variable names in the actions/runner software : RUNNER_TOOL_CACHE / RUNNER_TOOLSDIRECTORY / AGENT_TOOLSDIRECTORY +# Warning, not all setup actions support the env vars and so this specific path must be created regardless +mkdir -p /opt/hostedtoolcache + +echo "Creating actions-runner directory for the GH Action installation" +cd /opt/ +mkdir -p actions-runner && cd actions-runner + + +if [[ -n "$RUNNER_TARBALL_URL" ]]; then + echo "Downloading the GH Action runner from $RUNNER_TARBALL_URL to $file_name" + curl -s -o $file_name -L "$RUNNER_TARBALL_URL" +else + echo "Retrieving TOKEN from AWS API" + token="$(curl -s -f -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 180")" + + region="$(curl -s -f -H "X-aws-ec2-metadata-token: $token" http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)" + echo "Retrieved REGION from AWS API ($region)" + + echo "Downloading the GH Action runner from s3 bucket $s3_location" + aws s3 cp "$s3_location" "$file_name" --region "$region" --no-progress +fi + +echo "Un-tar action runner" +tar xzf ./$file_name +echo "Delete tar file" +rm -rf $file_name + +os_id=$(awk -F= '/^ID=/{print $2}' /etc/os-release) +echo OS: $os_id + +# Install libicu on non-ubuntu, non-debian +if [[ ! "$os_id" =~ ^(ubuntu|debian).* ]]; then + max_attempts=5 + attempt_count=0 + success=false + while [ $success = false ] && [ $attempt_count -le $max_attempts ]; do + echo "Attempt $attempt_count/$max_attempts: Installing libicu" + dnf install -y libicu + if [ $? -eq 0 ]; then + success=true + else + echo "Failed to install libicu" + attempt_count=$(( attempt_count + 1 )) + sleep 5 + fi + done +fi + +# Install dependencies for ubuntu and debian +if [[ "$os_id" =~ ^(ubuntu|debian).* ]]; then + echo "Installing dependencies" + ./bin/installdependencies.sh +fi + +echo "Set file ownership of action runner" +chown -R "$user_name":"$user_name" /opt/actions-runner +chown -R "$user_name":"$user_name" /opt/hostedtoolcache diff --git a/modules/compute-providers/ec2/templates/start-runner-osx.sh b/modules/compute-providers/ec2/templates/start-runner-osx.sh new file mode 100644 index 0000000000..a6da66116d --- /dev/null +++ b/modules/compute-providers/ec2/templates/start-runner-osx.sh @@ -0,0 +1,185 @@ +#!/bin/bash + +# macOS variant of start-runner.sh + +tag_instance_with_runner_id() { + echo "Checking for .runner file to extract agent ID" + + if [[ ! -f "/opt/actions-runner/.runner" ]]; then + echo "Warning: .runner file not found" + return 0 + fi + + echo "Found .runner file, extracting agent ID" + local agent_id + agent_id=$(jq -r '.agentId' /opt/actions-runner/.runner 2>/dev/null || echo "") + + if [[ -z "$agent_id" || "$agent_id" == "null" ]]; then + echo "Warning: Could not extract agent ID from .runner file" + return 0 + fi + + echo "Tagging instance with GitHub runner agent ID: $agent_id" + if aws ec2 create-tags \ + --region "$region" \ + --resources "$instance_id" \ + --tags Key=ghr:github_runner_id,Value="$agent_id"; then + echo "Successfully tagged instance with agent ID: $agent_id" + return 0 + else + echo "Warning: Failed to tag instance with agent ID" + return 0 + fi +} + +cleanup() { + local exit_code="$1" + + if [ "$exit_code" -ne 0 ]; then + echo "ERROR: runner-start-failed with exit code $exit_code" + fi + + if [ "$agent_mode" = "ephemeral" ] || [ "$exit_code" -ne 0 ]; then + echo "Terminating instance" + aws ec2 terminate-instances \ + --instance-ids "$instance_id" \ + --region "$region" || true + fi +} + +trap 'cleanup $?' EXIT + +echo "Retrieving TOKEN from AWS API" +token=$(curl -f -X PUT "http://169.254.169.254/latest/api/token" \ + -H "X-aws-ec2-metadata-token-ttl-seconds: 180" || true) +if [ -z "$token" ]; then + retrycount=0 + until [ -n "$token" ]; do + echo "Failed to retrieve token. Retrying in 5 seconds." + sleep 5 + token=$(curl -f -X PUT "http://169.254.169.254/latest/api/token" \ + -H "X-aws-ec2-metadata-token-ttl-seconds: 180" || true) + retrycount=$((retrycount + 1)) + if [ $retrycount -gt 40 ]; then + break + fi + done +fi + +region=$(curl -f -H "X-aws-ec2-metadata-token: $token" \ + http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region) +echo "Retrieved REGION from AWS API ($region)" + +instance_id=$(curl -f -H "X-aws-ec2-metadata-token: $token" \ + http://169.254.169.254/latest/meta-data/instance-id) +echo "Retrieved INSTANCE_ID from AWS API ($instance_id)" + +availability_zone=$(curl -f -H "X-aws-ec2-metadata-token: $token" \ + http://169.254.169.254/latest/meta-data/placement/availability-zone) + +environment=$(curl -f -H "X-aws-ec2-metadata-token: $token" \ + http://169.254.169.254/latest/meta-data/tags/instance/ghr:environment || echo "") +ssm_config_path=$(curl -f -H "X-aws-ec2-metadata-token: $token" \ + http://169.254.169.254/latest/meta-data/tags/instance/ghr:ssm_config_path || echo "") +runner_name_prefix=$(curl -f -H "X-aws-ec2-metadata-token: $token" \ + http://169.254.169.254/latest/meta-data/tags/instance/ghr:runner_name_prefix || echo "") + +echo "Retrieved ghr:environment tag - ($environment)" +echo "Retrieved ghr:ssm_config_path tag - ($ssm_config_path)" +echo "Retrieved ghr:runner_name_prefix tag - ($runner_name_prefix)" + +parameters=$(aws ssm get-parameters-by-path \ + --path "$ssm_config_path" \ + --region "$region" \ + --query "Parameters[*].{Name:Name,Value:Value}") +echo "Retrieved parameters from AWS SSM ($parameters)" + +run_as=$(echo "$parameters" | jq -r '.[] | select(.Name == "'$ssm_config_path'/run_as") | .Value') +echo "Retrieved /$ssm_config_path/run_as parameter - ($run_as)" + +agent_mode=$(echo "$parameters" | jq -r '.[] | select(.Name == "'$ssm_config_path'/agent_mode") | .Value') +echo "Retrieved /$ssm_config_path/agent_mode parameter - ($agent_mode)" + +disable_default_labels=$(echo "$parameters" | jq -r '.[] | select(.Name == "'$ssm_config_path'/disable_default_labels") | .Value') +echo "Retrieved /$ssm_config_path/disable_default_labels parameter - ($disable_default_labels)" + +enable_jit_config=$(echo "$parameters" | jq -r '.[] | select(.Name == "'$ssm_config_path'/enable_jit_config") | .Value') +echo "Retrieved /$ssm_config_path/enable_jit_config parameter - ($enable_jit_config)" + +token_path=$(echo "$parameters" | jq -r '.[] | select(.Name == "'$ssm_config_path'/token_path") | .Value') +echo "Retrieved /$ssm_config_path/token_path parameter - ($token_path)" + +echo "Get GH Runner config from AWS SSM" +config=$(aws ssm get-parameter --name "$token_path"/"$instance_id" --with-decryption --region "$region" | jq -r ".Parameter | .Value") +while [[ -z "$config" ]]; do + echo "Waiting for GH Runner config to become available in AWS SSM" + sleep 1 + config=$(aws ssm get-parameter --name "$token_path"/"$instance_id" --with-decryption --region "$region" | jq -r ".Parameter | .Value") +done + +echo "Delete GH Runner token from AWS SSM" +aws ssm delete-parameter --name "$token_path"/"$instance_id" --region "$region" + +if [ -z "$run_as" ]; then + echo "No user specified, using default ec2-user account" + run_as="ec2-user" +fi + +if [[ "$run_as" == "root" ]]; then + echo "run_as is set to root - export RUNNER_ALLOW_RUNASROOT=1" + export RUNNER_ALLOW_RUNASROOT=1 +fi + +sudo chown -R "$run_as" /opt/actions-runner + +info_arch=$(uname -m) +info_os=$(sw_vers -productName 2>/dev/null || echo "macOS") +info_ver=$(sw_vers -productVersion 2>/dev/null || echo "unknown") + +tee /opt/actions-runner/.setup_info <&1 + + if ($LASTEXITCODE -eq 0) { + Write-Host "Successfully tagged instance with agent ID: $agentId" + return $true + } else { + Write-Host "Warning: Failed to tag instance with agent ID - $tagResult" + return $true + } + } + catch { + Write-Host "Warning: Error processing .runner file - $($_.Exception.Message)" + return $true + } +} + +## Retrieve instance metadata + +Write-Host "Retrieving TOKEN from AWS API" +$token=Invoke-RestMethod -Method PUT -Uri "http://169.254.169.254/latest/api/token" -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "180"} +if ( ! $token ) { + $retrycount=0 + do { + echo "Failed to retrieve token. Retrying in 5 seconds." + Start-Sleep 5 + $token=Invoke-RestMethod -Method PUT -Uri "http://169.254.169.254/latest/api/token" -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "180"} + $retrycount=$retrycount + 1 + if ( $retrycount -gt 40 ) + { + break + } + } until ($token) +} + +$ami_id=Invoke-RestMethod -Uri "http://169.254.169.254/latest/meta-data/ami-id" -Headers @{"X-aws-ec2-metadata-token" = $token} + +$metadata=Invoke-RestMethod -Uri "http://169.254.169.254/latest/dynamic/instance-identity/document" -Headers @{"X-aws-ec2-metadata-token" = $token} + +$Region = $metadata.region +Write-Host "Retrieved REGION from AWS API ($Region)" + +$InstanceId = $metadata.instanceId +Write-Host "Retrieved InstanceId from AWS API ($InstanceId)" + +$tags=aws ec2 describe-tags --region "$Region" --filters "Name=resource-id,Values=$InstanceId" | ConvertFrom-Json +Write-Host "Retrieved tags from AWS API" + +$environment=$tags.Tags.where( {$_.Key -eq 'ghr:environment'}).value +Write-Host "Retrieved ghr:environment tag - ($environment)" + +$runner_name_prefix=$tags.Tags.where( {$_.Key -eq 'ghr:runner_name_prefix'}).value +Write-Host "Retrieved ghr:runner_name_prefix tag - ($runner_name_prefix)" + +$ssm_config_path=$tags.Tags.where( {$_.Key -eq 'ghr:ssm_config_path'}).value +Write-Host "Retrieved ghr:ssm_config_path tag - ($ssm_config_path)" + +$parameters=$(aws ssm get-parameters-by-path --path "$ssm_config_path" --region "$Region" --query "Parameters[*].{Name:Name,Value:Value}") | ConvertFrom-Json +Write-Host "Retrieved parameters from AWS SSM" + +$run_as=$parameters.where( {$_.Name -eq "$ssm_config_path/run_as"}).value +Write-Host "Retrieved $ssm_config_path/run_as parameter - ($run_as)" + +$enable_cloudwatch_agent=$parameters.where( {$_.Name -eq "$ssm_config_path/enable_cloudwatch"}).value +Write-Host "Retrieved $ssm_config_path/enable_cloudwatch parameter - ($enable_cloudwatch_agent)" + +$agent_mode=$parameters.where( {$_.Name -eq "$ssm_config_path/agent_mode"}).value +Write-Host "Retrieved $ssm_config_path/agent_mode parameter - ($agent_mode)" + +$disable_default_labels=$parameters.where( {$_.Name -eq "$ssm_config_path/disable_default_labels"}).value +Write-Host "Retrieved $ssm_config_path/disable_default_labels parameter - ($disable_default_labels)" + +$enable_jit_config=$parameters.where( {$_.Name -eq "$ssm_config_path/enable_jit_config"}).value +Write-Host "Retrieved $ssm_config_path/enable_jit_config parameter - ($enable_jit_config)" + +$token_path=$parameters.where( {$_.Name -eq "$ssm_config_path/token_path"}).value +Write-Host "Retrieved $ssm_config_path/token_path parameter - ($token_path)" + + +if ($enable_cloudwatch_agent -eq "true") +{ + Write-Host "Enabling CloudWatch Agent" + & 'C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1' -a fetch-config -m ec2 -s -c "ssm:$ssm_config_path/cloudwatch_agent_config_runner" +} + +## Configure the runner + +Write-Host "Get GH Runner config from AWS SSM" +$config = $null +$i = 0 +do { + $config = (aws ssm get-parameters --names "$token_path/$InstanceId" --with-decryption --region $Region --query "Parameters[*].{Name:Name,Value:Value}" | ConvertFrom-Json)[0].value + Write-Host "Waiting for GH Runner config to become available in AWS SSM ($i/30)" + Start-Sleep 1 + $i++ +} while (($null -eq $config) -and ($i -lt 30)) + +Write-Host "Delete GH Runner token from AWS SSM" +aws ssm delete-parameter --name "$token_path/$InstanceId" --region $Region + +# Create or update user +if (-not($run_as)) { + Write-Host "No user specified, using default ec2-user account" + $run_as="ec2-user" +} +Add-Type -AssemblyName "System.Web" +$password = [System.Web.Security.Membership]::GeneratePassword(24, 4) +$securePassword = ConvertTo-SecureString $password -AsPlainText -Force +$username = $run_as +if (!(Get-LocalUser -Name $username -ErrorAction Ignore)) { + New-LocalUser -Name $username -Password $securePassword + Write-Host "Created new user ($username)" +} +else { + Set-LocalUser -Name $username -Password $securePassword + Write-Host "Changed password for user ($username)" +} +# Add user to groups +foreach ($group in @("Administrators", "docker-users")) { + if ((Get-LocalGroup -Name "$group" -ErrorAction Ignore) -and + !(Get-LocalGroupMember -Group "$group" -Member $username -ErrorAction Ignore)) { + Add-LocalGroupMember -Group "$group" -Member $username + Write-Host "Added $username to $group group" + } +} + +# Disable User Access Control (UAC) +# TODO investigate if this is needed or if its overkill - https://github.com/github-aws-runners/terraform-aws-github-runner/issues/1505 +Set-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 0 -Force +Write-Host "Disabled User Access Control (UAC)" + +$runnerExtraOptions = "" +if ($disable_default_labels -eq "true") { + $runnerExtraOptions += "--no-default-labels" +} + +if ($enable_jit_config -eq "false" -or $agent_mode -ne "ephemeral") { + $configCmd = ".\config.cmd --unattended --name $runner_name_prefix$InstanceId --work `"_work`" $runnerExtraOptions $config" + Write-Host "Configure GH Runner (non ephmeral / no JIT) as user $run_as" + Invoke-Expression $configCmd + + # Tag instance with GitHub runner agent ID for non-JIT runners + Tag-InstanceWithRunnerId +} + +$jsonBody = @( + @{ + group='Runner Image' + detail="AMI id: $ami_id" + } +) +ConvertTo-Json -InputObject $jsonBody | Set-Content -Path "$pwd\.setup_info" + + +Write-Host "Starting the runner in $agent_mode mode" +Write-Host "Starting runner after $(((get-date) - (gcim Win32_OperatingSystem).LastBootUpTime).tostring("hh':'mm':'ss''"))" + +if ($agent_mode -eq "ephemeral") { + if ($enable_jit_config -eq "true") { + Write-Host "Starting with jit config" + Invoke-Expression ".\run.cmd --jitconfig $${config}" + } + else { + Write-Host "Starting without jit config" + Invoke-Expression ".\run.cmd" + } + Write-Host "Runner has finished" + + if ($enable_cloudwatch_agent) + { + Write-Host "Stopping CloudWatch Agent" + & 'C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1' -a stop + } + + Write-Host "Terminating instance" + aws ec2 terminate-instances --instance-ids "$InstanceId" --region "$Region" +} else { + Write-Host "Installing the runner as a service" + + $action = New-ScheduledTaskAction -WorkingDirectory "$pwd" -Execute "run.cmd" + $trigger = Get-CimClass "MSFT_TaskRegistrationTrigger" -Namespace "Root/Microsoft/Windows/TaskScheduler" + Register-ScheduledTask -TaskName "runnertask" -Action $action -Trigger $trigger -User $username -Password $password -RunLevel Highest -Force + Write-Host "Starting runner after $(((get-date) - (gcim Win32_OperatingSystem).LastBootUpTime).tostring("hh':'mm':'ss''"))" +} diff --git a/modules/compute-providers/ec2/templates/start-runner.sh b/modules/compute-providers/ec2/templates/start-runner.sh new file mode 100644 index 0000000000..7f2c0f82c5 --- /dev/null +++ b/modules/compute-providers/ec2/templates/start-runner.sh @@ -0,0 +1,280 @@ +#!/bin/bash + +# https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html +# https://docs.aws.amazon.com/xray/latest/devguide/scorekeep-scripts.html +create_xray_start_segment() { + START_TIME=$(date -d "$(uptime -s)" +%s) + TRACE_ID=$1 + INSTANCE_ID=$2 + SEGMENT_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') + SEGMENT_DOC="{\"trace_id\": \"$TRACE_ID\", \"id\": \"$SEGMENT_ID\", \"start_time\": $START_TIME, \"in_progress\": true, \"name\": \"Runner\",\"origin\": \"AWS::EC2::Instance\", \"aws\": {\"ec2\":{\"instance_id\":\"$INSTANCE_ID\"}}}" + HEADER='{"format": "json", "version": 1}' + TRACE_DATA="$HEADER\n$SEGMENT_DOC" + echo "$HEADER" > document.txt + echo "$SEGMENT_DOC" >> document.txt + UDP_IP="127.0.0.1" + UDP_PORT=2000 + cat document.txt > /dev/udp/$UDP_IP/$UDP_PORT + echo "$SEGMENT_DOC" +} + +create_xray_success_segment() { + local SEGMENT_DOC=$1 + if [ -z "$SEGMENT_DOC" ]; then + echo "No segment doc provided" + return + fi + SEGMENT_DOC=$(echo "$SEGMENT_DOC" | jq '. | del(.in_progress)') + END_TIME=$(date +%s) + SEGMENT_DOC=$(echo "$SEGMENT_DOC" | jq -c ". + {\"end_time\": $END_TIME}") + HEADER="{\"format\": \"json\", \"version\": 1}" + TRACE_DATA="$HEADER\n$SEGMENT_DOC" + echo "$HEADER" > document.txt + echo "$SEGMENT_DOC" >> document.txt + UDP_IP="127.0.0.1" + UDP_PORT=2000 + cat document.txt > /dev/udp/$UDP_IP/$UDP_PORT + echo "$SEGMENT_DOC" +} + +create_xray_error_segment() { + local SEGMENT_DOC="$1" + if [ -z "$SEGMENT_DOC" ]; then + echo "No segment doc provided" + return + fi + MESSAGE="$2" + ERROR="{\"exceptions\": [{\"message\": \"$MESSAGE\"}]}" + SEGMENT_DOC=$(echo "$SEGMENT_DOC" | jq '. | del(.in_progress)') + END_TIME=$(date +%s) + SEGMENT_DOC=$(echo "$SEGMENT_DOC" | jq -c ". + {\"end_time\": $END_TIME, \"error\": true, \"cause\": $ERROR }") + HEADER="{\"format\": \"json\", \"version\": 1}" + TRACE_DATA="$HEADER\n$SEGMENT_DOC" + echo "$HEADER" > document.txt + echo "$SEGMENT_DOC" >> document.txt + UDP_IP="127.0.0.1" + UDP_PORT=2000 + cat document.txt > /dev/udp/$UDP_IP/$UDP_PORT + echo "$SEGMENT_DOC" +} + +tag_instance_with_runner_id() { + echo "Checking for .runner file to extract agent ID" + + if [[ ! -f "/opt/actions-runner/.runner" ]]; then + echo "Warning: .runner file not found" + return 0 + fi + + echo "Found .runner file, extracting agent ID" + local agent_id + agent_id=$(jq -r '.agentId' /opt/actions-runner/.runner 2>/dev/null || echo "") + + if [[ -z "$agent_id" || "$agent_id" == "null" ]]; then + echo "Warning: Could not extract agent ID from .runner file" + return 0 + fi + + echo "Tagging instance with GitHub runner agent ID: $agent_id" + if aws ec2 create-tags \ + --region "$region" \ + --resources "$instance_id" \ + --tags Key=ghr:github_runner_id,Value="$agent_id"; then + echo "Successfully tagged instance with agent ID: $agent_id" + return 0 + else + echo "Warning: Failed to tag instance with agent ID" + return 0 + fi +} + +cleanup() { + local exit_code="$1" + local error_location="$2" + local error_lineno="$3" + + if [ "$exit_code" -ne 0 ]; then + echo "ERROR: runner-start-failed with exit code $exit_code occurred on $error_location" + create_xray_error_segment "$SEGMENT" "runner-start-failed with exit code $exit_code occurred on $error_location - $error_lineno" + fi + # allows to flush the cloud watch logs and traces + sleep 10 + if [ "$agent_mode" = "ephemeral" ] || [ "$exit_code" -ne 0 ]; then + echo "Stopping CloudWatch service" + systemctl stop amazon-cloudwatch-agent.service || true + echo "Terminating instance" + aws ec2 terminate-instances \ + --instance-ids "$instance_id" \ + --region "$region" \ + || true + fi +} + +trap 'cleanup $? $LINENO $BASH_LINENO' EXIT + +echo "Retrieving TOKEN from AWS API" +token=$(curl -f -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 180" || true) +if [ -z "$token" ]; then + retrycount=0 + until [ -n "$token" ]; do + echo "Failed to retrieve token. Retrying in 5 seconds." + sleep 5 + token=$(curl -f -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 180" || true) + retrycount=$((retrycount + 1)) + if [ $retrycount -gt 40 ]; then + break + fi + done +fi + +ami_id=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/ami-id) + +region=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region) +echo "Retrieved REGION from AWS API ($region)" + +instance_id=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/instance-id) +echo "Retrieved INSTANCE_ID from AWS API ($instance_id)" + +instance_type=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/instance-type) +availability_zone=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/placement/availability-zone) + +%{ if metadata_tags == "enabled" } +environment=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/tags/instance/ghr:environment) +ssm_config_path=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/tags/instance/ghr:ssm_config_path) +runner_name_prefix=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/tags/instance/ghr:runner_name_prefix || echo "") +xray_trace_id=$(curl -f -H "X-aws-ec2-metadata-token: $token" -v http://169.254.169.254/latest/meta-data/tags/instance/ghr:trace_id || echo "") + +%{ else } +tags=$(aws ec2 describe-tags --region "$region" --filters "Name=resource-id,Values=$instance_id") +echo "Retrieved tags from AWS API ($tags)" + +environment=$(echo "$tags" | jq -r '.Tags[] | select(.Key == "ghr:environment") | .Value') +ssm_config_path=$(echo "$tags" | jq -r '.Tags[] | select(.Key == "ghr:ssm_config_path") | .Value') +runner_name_prefix=$(echo "$tags" | jq -r '.Tags[] | select(.Key == "ghr:runner_name_prefix") | .Value' || echo "") +xray_trace_id=$(echo "$tags" | jq -r '.Tags[] | select(.Key == "ghr:trace_id") | .Value' || echo "") + +%{ endif } + +echo "Retrieved ghr:environment tag - ($environment)" +echo "Retrieved ghr:ssm_config_path tag - ($ssm_config_path)" +echo "Retrieved ghr:runner_name_prefix tag - ($runner_name_prefix)" + +parameters=$(aws ssm get-parameters-by-path --path "$ssm_config_path" --region "$region" --query "Parameters[*].{Name:Name,Value:Value}") +echo "Retrieved parameters from AWS SSM ($parameters)" + +run_as=$(echo "$parameters" | jq -r '.[] | select(.Name == "'$ssm_config_path'/run_as") | .Value') +echo "Retrieved /$ssm_config_path/run_as parameter - ($run_as)" + +enable_cloudwatch_agent=$(echo "$parameters" | jq --arg ssm_config_path "$ssm_config_path" -r '.[] | select(.Name == "'$ssm_config_path'/enable_cloudwatch") | .Value') +echo "Retrieved /$ssm_config_path/enable_cloudwatch parameter - ($enable_cloudwatch_agent)" + +agent_mode=$(echo "$parameters" | jq --arg ssm_config_path "$ssm_config_path" -r '.[] | select(.Name == "'$ssm_config_path'/agent_mode") | .Value') +echo "Retrieved /$ssm_config_path/agent_mode parameter - ($agent_mode)" + +disable_default_labels=$(echo "$parameters" | jq --arg ssm_config_path "$ssm_config_path" -r '.[] | select(.Name == "'$ssm_config_path'/disable_default_labels") | .Value') +echo "Retrieved /$ssm_config_path/disable_default_labels parameter - ($disable_default_labels)" + +enable_jit_config=$(echo "$parameters" | jq --arg ssm_config_path "$ssm_config_path" -r '.[] | select(.Name == "'$ssm_config_path'/enable_jit_config") | .Value') +echo "Retrieved /$ssm_config_path/enable_jit_config parameter - ($enable_jit_config)" + +token_path=$(echo "$parameters" | jq --arg ssm_config_path "$ssm_config_path" -r '.[] | select(.Name == "'$ssm_config_path'/token_path") | .Value') +echo "Retrieved /$ssm_config_path/token_path parameter - ($token_path)" + +if [[ "$xray_trace_id" != "" ]]; then + # run xray service + curl https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray-daemon-linux-3.x.zip -o aws-xray-daemon-linux-3.x.zip + unzip aws-xray-daemon-linux-3.x.zip -d aws-xray-daemon-linux-3.x + chmod +x ./aws-xray-daemon-linux-3.x/xray + ./aws-xray-daemon-linux-3.x/xray -o -n "$region" & + + + SEGMENT=$(create_xray_start_segment "$xray_trace_id" "$instance_id") + echo "$SEGMENT" +fi + +if [[ "$enable_cloudwatch_agent" == "true" ]]; then + echo "Cloudwatch is enabled" + amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c "ssm:$ssm_config_path/cloudwatch_agent_config_runner" +fi + +## Configure the runner + +echo "Get GH Runner config from AWS SSM" +config=$(aws ssm get-parameter --name "$token_path"/"$instance_id" --with-decryption --region "$region" | jq -r ".Parameter | .Value") +while [[ -z "$config" ]]; do + echo "Waiting for GH Runner config to become available in AWS SSM" + sleep 1 + config=$(aws ssm get-parameter --name "$token_path"/"$instance_id" --with-decryption --region "$region" | jq -r ".Parameter | .Value") +done + +echo "Delete GH Runner token from AWS SSM" +aws ssm delete-parameter --name "$token_path"/"$instance_id" --region "$region" + +if [ -z "$run_as" ]; then + echo "No user specified, using default ec2-user account" + run_as="ec2-user" +fi + +if [[ "$run_as" == "root" ]]; then + echo "run_as is set to root - export RUNNER_ALLOW_RUNASROOT=1" + export RUNNER_ALLOW_RUNASROOT=1 +fi + +chown -R $run_as /opt/actions-runner + +info_arch=$(uname -p) +info_os=$( ( lsb_release -ds || cat /etc/*release || uname -om ) 2>/dev/null | head -n1 | cut -d "=" -f2- | tr -d '"') + +tee /opt/actions-runner/.setup_info </dev/null 2>&1; then + echo "Homebrew detected; you can install extra dependencies via brew if needed" +fi + +user_name=ec2-user + +${install_runner} + +${post_install} + +# Register runner job hooks +# Ref: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/running-scripts-before-or-after-a-job +%{ if hook_job_started != "" } +cat > /opt/actions-runner/hook_job_started.sh <<'EOF' +${hook_job_started} +EOF +echo ACTIONS_RUNNER_HOOK_JOB_STARTED=/opt/actions-runner/hook_job_started.sh | tee -a /opt/actions-runner/.env +%{ endif } + +%{ if hook_job_completed != "" } +cat > /opt/actions-runner/hook_job_completed.sh <<'EOF' +${hook_job_completed} +EOF +echo ACTIONS_RUNNER_HOOK_JOB_COMPLETED=/opt/actions-runner/hook_job_completed.sh | tee -a /opt/actions-runner/.env +%{ endif } + +${start_runner} diff --git a/modules/compute-providers/ec2/templates/user-data.ps1 b/modules/compute-providers/ec2/templates/user-data.ps1 new file mode 100644 index 0000000000..a1e3a4da66 --- /dev/null +++ b/modules/compute-providers/ec2/templates/user-data.ps1 @@ -0,0 +1,47 @@ + +$ErrorActionPreference = "Continue" +$VerbosePreference = "Continue" +Start-Transcript -Path "C:\UserData.log" -Append + +${pre_install} + +# Install Chocolatey +[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 +$env:chocolateyUseWindowsCompression = 'true' +Invoke-WebRequest https://chocolatey.org/install.ps1 -UseBasicParsing | Invoke-Expression + +# Add Chocolatey to powershell profile +$ChocoProfileValue = @' +$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1" +if (Test-Path($ChocolateyProfile)) { + Import-Module "$ChocolateyProfile" +} + +refreshenv +'@ +# Write it to the $profile location +Set-Content -Path "$PsHome\Microsoft.PowerShell_profile.ps1" -Value $ChocoProfileValue -Force +# Source it +. "$PsHome\Microsoft.PowerShell_profile.ps1" + + +refreshenv + +Write-Host "Installing cloudwatch agent..." +Invoke-WebRequest -Uri https://s3.amazonaws.com/amazoncloudwatch-agent/windows/amd64/latest/amazon-cloudwatch-agent.msi -OutFile C:\amazon-cloudwatch-agent.msi +$cloudwatchParams = '/i', 'C:\amazon-cloudwatch-agent.msi', '/qn', '/L*v', 'C:\CloudwatchInstall.log' +Start-Process "msiexec.exe" $cloudwatchParams -Wait -NoNewWindow +Remove-Item C:\amazon-cloudwatch-agent.msi + + +# Install dependent tools +Write-Host "Installing additional development tools" +choco install git awscli -y +refreshenv + +${install_runner} +${post_install} +${start_runner} + +Stop-Transcript + diff --git a/modules/compute-providers/ec2/templates/user-data.sh b/modules/compute-providers/ec2/templates/user-data.sh new file mode 100644 index 0000000000..ca69f26d34 --- /dev/null +++ b/modules/compute-providers/ec2/templates/user-data.sh @@ -0,0 +1,81 @@ +#!/bin/bash -e + +install_with_retry() { + max_attempts=5 + attempt_count=0 + success=false + while [ $success = false ] && [ $attempt_count -le $max_attempts ]; do + echo "Attempting $attempt_count/$max_attempts: Installing $*" + dnf install -y $* + if [ $? -eq 0 ]; then + success=true + else + echo "Failed to install $1 - retrying" + attempt_count=$(( attempt_count + 1 )) + sleep 5 + fi + done +} + +exec > >(tee /var/log/user-data.log | logger -t user-data -s 2>/dev/console) 2>&1 + +# AWS suggest to create a log for debug purpose based on https://aws.amazon.com/premiumsupport/knowledge-center/ec2-linux-log-user-data/ +# As side effect all command, set +x disable debugging explicitly. +# +# An alternative for masking tokens could be: exec > >(sed 's/--token\ [^ ]* /--token\ *** /g' > /var/log/user-data.log) 2>&1 + +set +x + +%{ if enable_debug_logging } +set -x +%{ endif } + +${pre_install} + +max_attempts=5 +attempt_count=0 +success=false +while [ $success = false ] && [ $attempt_count -le $max_attempts ]; do + echo "Attempting $attempt_count/$max_attempts: upgrade-minimal" + dnf upgrade-minimal -y +if [ $? -eq 0 ]; then + success=true + else + echo "Failed to run `dnf upgrad-minimal -y` - retrying" + attempt_count=$(( attempt_count + 1 )) + sleep 5 + fi +done + +# Install docker +install_with_retry docker + +service docker start +usermod -a -G docker ec2-user + +install_with_retry amazon-cloudwatch-agent jq git +install_with_retry --allowerasing curl + +user_name=ec2-user + +${install_runner} + +${post_install} + +# Register runner job hooks +# Ref: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/running-scripts-before-or-after-a-job +%{ if hook_job_started != "" } +cat > /opt/actions-runner/hook_job_started.sh <<'EOF' +${hook_job_started} +EOF +echo ACTIONS_RUNNER_HOOK_JOB_STARTED=/opt/actions-runner/hook_job_started.sh | tee -a /opt/actions-runner/.env +%{ endif } + +%{ if hook_job_completed != "" } +cat > /opt/actions-runner/hook_job_completed.sh <<'EOF' +${hook_job_completed} +EOF +echo ACTIONS_RUNNER_HOOK_JOB_COMPLETED=/opt/actions-runner/hook_job_completed.sh | tee -a /opt/actions-runner/.env +%{ endif } + +${start_runner} diff --git a/modules/compute-providers/ec2/tests/provider.tftest.hcl b/modules/compute-providers/ec2/tests/provider.tftest.hcl new file mode 100644 index 0000000000..bc92537279 --- /dev/null +++ b/modules/compute-providers/ec2/tests/provider.tftest.hcl @@ -0,0 +1,451 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{}" + } + } + + mock_data "aws_ami" { + defaults = { + id = "ami-1234567890abcdef0" + name = "runner-test" + creation_date = "2026-01-01T00:00:00.000Z" + deprecation_time = "" + } + } + + mock_data "aws_caller_identity" { + defaults = { + account_id = "123456789012" + } + } +} + +override_data { + target = data.aws_iam_policy_document.scale_up + values = { + json = "{\"Action\":\"ec2:RunInstances\",\"PassRole\":\"arn:aws:iam::123456789012:role/provider-test-runner\"}" + } +} + +override_data { + target = data.aws_iam_policy_document.pool + values = { + json = "{\"Action\":\"iam:PassRole\"}" + } +} + +variables { + aws_region = "eu-west-1" + prefix = "provider-test" + + config = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + ami = { + filter = { state = ["available"] } + owners = ["amazon"] + id_ssm_parameter = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/ami-id" + } + kms_key = null + } + binaries_syncer = { + enabled = true + s3 = { + arn = "arn:aws:s3:::runner-distribution" + id = "runner-distribution" + key = "runner.zip" + } + } + cloudwatch_agent = { + enabled = true + } + ssm_enabled = true + managed_security_group_enabled = true + } + + runner = { + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/provider-test-runner" + name = "provider-test-runner" + } + managed_policy_arns = { + readonly = "arn:aws:iam::aws:policy/ReadOnlyAccess" + } + } + } + + ssm = { + paths = { + root = "/github-runner/provider-test" + tokens = "tokens" + config = "config" + } + } +} + +run "separates_control_plane_contract_from_ec2_resources" { + command = plan + + assert { + condition = toset(keys(output.provider)) == toset(["environment_variables", "policies", "resources"]) + error_message = "The EC2 provider contract must expose only integration and resource data; its module identity must not be repeated in the output." + } + + assert { + condition = output.provider.environment_variables.scale_up["INSTANCE_TYPES"] == "m5.large" + error_message = "The provider contract must expose EC2 scale-up environment variables." + } + + assert { + condition = ( + length(output.provider.environment_variables.scale_down) == 0 + && !contains(keys(output.provider.environment_variables.pool), "RUNNER_BOOT_TIME_IN_MINUTES") + ) + error_message = "The EC2 provider must not expose webhook-owned runner boot-time configuration." + } + + assert { + condition = strcontains(output.provider.policies.scale_up.iam_policy_json, "ec2:RunInstances") + error_message = "The EC2 provider must own EC2 scale-up permissions." + } + + assert { + condition = !strcontains(output.provider.policies.scale_up.iam_policy_json, "sqs:ReceiveMessage") + error_message = "The EC2 provider must not own common build-queue permissions." + } + + assert { + condition = strcontains(output.provider.policies.pool.iam_policy_json, "iam:PassRole") + error_message = "The EC2 provider must expose pool permissions for its runner role." + } + + assert { + condition = strcontains(output.provider.policies.scale_up.iam_policy_json, "arn:aws:iam::123456789012:role/provider-test-runner") + error_message = "The EC2 provider must use the common runner role ARN for PassRole." + } + + assert { + condition = output.provider.policies.scale_up.managed_policy_enabled + error_message = "An external AMI SSM parameter must enable the scale-up managed policy attachment at plan time." + } + + assert { + condition = output.provider.policies.pool.managed_policy_enabled + error_message = "An external AMI SSM parameter must enable the pool managed policy attachment at plan time." + } + + assert { + condition = ( + contains(flatten([ + for statement in data.aws_iam_policy_document.scale_up.statement : [ + for condition in statement.condition : condition.variable + ] + ]), "ec2:ResourceTag/ghr:environment") + && contains(flatten([ + for statement in data.aws_iam_policy_document.scale_down.statement : [ + for condition in statement.condition : condition.variable + ] + ]), "ec2:ResourceTag/ghr:environment") + && !contains(flatten([ + for statement in data.aws_iam_policy_document.scale_up.statement : [ + for condition in statement.condition : condition.variable + ] + ]), "ec2:ResourceTag/gh:environment") + && !contains(flatten([ + for statement in data.aws_iam_policy_document.scale_down.statement : [ + for condition in statement.condition : condition.variable + ] + ]), "ec2:ResourceTag/gh:environment") + ) + error_message = "EC2 scale policies must authorize resources by the protected ghr:environment tag." + } + + assert { + condition = toset(keys(output.provider.policies)) == toset(["runner", "scale_up", "scale_down", "pool"]) + error_message = "The EC2 provider must expose policies grouped by their owning common component." + } + + assert { + condition = toset(keys(output.provider.policies.runner.inline_policies)) == toset([ + "ssm_parameters", + "describe_tags", + "create_tags", + "terminate_self", + "session_manager", + "distribution_bucket", + "cloudwatch", + ]) + error_message = "The EC2 provider must return the enabled runner permission documents." + } + + assert { + condition = output.provider.policies.runner.managed_policy_arns["readonly"] == "arn:aws:iam::aws:policy/ReadOnlyAccess" + error_message = "The EC2 provider must return common managed runner policy inputs with its provider policies." + } + + assert { + condition = toset(keys(output.provider.resources)) == toset(["launch_template", "runners_log_groups", "logfiles"]) + error_message = "EC2-specific artifacts must remain nested under provider resources." + } + + assert { + condition = aws_iam_instance_profile.runner[0].role == "provider-test-runner" + error_message = "The EC2 instance profile must use the common runner role name." + } + +} + +run "accepts_partial_typed_compute_options" { + command = plan + + variables { + config = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + ami = { + filter = { state = ["available"] } + owners = ["amazon"] + id_ssm_parameter = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/ami-id" + } + kms_key = null + } + binaries_syncer = { + enabled = false + s3 = null + } + cloudwatch_agent = { + enabled = false + } + managed_security_group_enabled = true + overrides = { + name_runner = "custom-runner" + } + metadata_options = { + http_tokens = "optional" + } + } + } + + assert { + condition = local.name_runner == "custom-runner" && local.name_sg == "provider-test-action-runner" + error_message = "Partial name overrides must retain defaults for omitted attributes." + } + + assert { + condition = ( + aws_launch_template.runner.metadata_options[0].http_tokens == "optional" + && aws_launch_template.runner.metadata_options[0].http_endpoint == "enabled" + && aws_launch_template.runner.metadata_options[0].http_put_response_hop_limit == 1 + && aws_launch_template.runner.metadata_options[0].instance_metadata_tags == "enabled" + ) + error_message = "Partial metadata options must retain typed defaults for omitted attributes." + } + + assert { + condition = toset(keys(output.provider.policies.runner.inline_policies)) == toset([ + "ssm_parameters", + "describe_tags", + "create_tags", + "terminate_self", + ]) + error_message = "Disabled optional EC2 features must remove only their corresponding runner policies." + } +} + +run "separates_provider_runner_and_ssm_tags" { + command = plan + + variables { + config = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + ami = { + filter = { state = ["available"] } + owners = ["amazon"] + id_ssm_parameter = null + kms_key = null + } + binaries_syncer = { + enabled = false + s3 = null + } + cloudwatch_agent = { + enabled = true + } + managed_security_group_enabled = true + tags = { + Name = "runner-name" + Scope = "runner" + RunnerOnly = "runner" + "ghr:environment" = "runner-override" + "ghr:ssm_config_path" = "/runner/override" + "ghr:runner_name_prefix" = "runner-override" + } + } + tags = { + Name = "provider-name" + Scope = "provider" + } + runner = { + name_prefix = "required-prefix" + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/provider-test-runner" + name = "provider-test-runner" + } + } + } + ssm = { + paths = { + root = "/github-runner/provider-test" + tokens = "tokens" + config = "config" + } + parameters = { + tags = { + Name = "ssm-name" + Scope = "ssm" + SsmOnly = "ssm" + "ghr:ami_name" = "ssm-override" + "ghr:ami_creation_date" = "ssm-override" + "ghr:ami_deprecation_time" = "ssm-override" + } + } + } + observability = { + logs = { + tags = { + Name = "log-name" + Scope = "log" + LogOnly = "log" + } + } + } + } + + assert { + condition = ( + aws_launch_template.runner.tags["Name"] == "provider-name" + && aws_launch_template.runner.tags["Scope"] == "provider" + && !contains(keys(aws_launch_template.runner.tags), "RunnerOnly") + && !contains(keys(aws_launch_template.runner.tags), "SsmOnly") + && !contains(keys(aws_launch_template.runner.tags), "ghr:environment") + && !contains(keys(aws_launch_template.runner.tags), "ghr:ssm_config_path") + && !contains(keys(aws_launch_template.runner.tags), "ghr:runner_name_prefix") + ) + error_message = "Non-runner EC2 resources must use provider tags without runner or SSM component tags." + } + + assert { + condition = toset([ + for tag_specification in aws_launch_template.runner.tag_specifications : tag_specification.resource_type + ]) == toset(["instance", "volume", "network-interface", "spot-instances-request"]) + error_message = "The launch template must define runner tags for every supported runner resource type." + } + + assert { + condition = alltrue([ + for tag_specification in aws_launch_template.runner.tag_specifications : ( + tag_specification.tags["Name"] == "runner-name" + && tag_specification.tags["Scope"] == "runner" + && tag_specification.tags["RunnerOnly"] == "runner" + && !contains(keys(tag_specification.tags), "SsmOnly") + && tag_specification.tags["ghr:environment"] == "provider-test" + && tag_specification.tags["ghr:ssm_config_path"] == "/github-runner/provider-test/config" + && tag_specification.tags["ghr:runner_name_prefix"] == "required-prefix" + ) + ]) + error_message = "Runner resource tags must apply runner overrides while protecting mandatory bootstrap tags." + } + + assert { + condition = ( + aws_ssm_parameter.runner_config_run_as.tags["Name"] == "ssm-name" + && aws_ssm_parameter.runner_config_run_as.tags["Scope"] == "ssm" + && aws_ssm_parameter.runner_config_run_as.tags["SsmOnly"] == "ssm" + && !contains(keys(aws_ssm_parameter.runner_config_run_as.tags), "RunnerOnly") + && !contains(keys(aws_ssm_parameter.runner_config_run_as.tags), "ghr:environment") + ) + error_message = "EC2 SSM parameters must merge SSM component tags over provider tags." + } + + assert { + condition = alltrue([ + for log_group in aws_cloudwatch_log_group.gh_runners : ( + log_group.tags["Name"] == "log-name" + && log_group.tags["Scope"] == "log" + && log_group.tags["LogOnly"] == "log" + && !contains(keys(log_group.tags), "RunnerOnly") + && !contains(keys(log_group.tags), "SsmOnly") + ) + ]) + error_message = "EC2 log groups must merge shared log tags over provider tags without runner or SSM tags." + } + + assert { + condition = ( + aws_ssm_parameter.runner_ami_id[0].tags["Name"] == "ssm-name" + && aws_ssm_parameter.runner_ami_id[0].tags["Scope"] == "ssm" + && aws_ssm_parameter.runner_ami_id[0].tags["SsmOnly"] == "ssm" + && aws_ssm_parameter.runner_ami_id[0].tags["ghr:ami_name"] == "runner-test" + && aws_ssm_parameter.runner_ami_id[0].tags["ghr:ami_creation_date"] == "2026-01-01T00:00:00.000Z" + && aws_ssm_parameter.runner_ami_id[0].tags["ghr:ami_deprecation_time"] == "" + ) + error_message = "The managed AMI parameter must preserve authoritative AMI metadata over SSM component tags." + } +} + +run "rejects_external_instance_profile_with_managed_role" { + command = plan + + variables { + config = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + instance_profile = { + name = "external-runner-profile" + } + binaries_syncer = { + enabled = false + } + } + + runner = { + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/provider-test-runner" + name = "provider-test-runner" + managed = true + } + } + } + } + + expect_failures = [terraform_data.validate_config] +} + +run "requires_distribution_object_when_sync_is_enabled" { + command = plan + + variables { + config = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + binaries_syncer = { + enabled = true + s3 = null + } + } + } + + expect_failures = [terraform_data.validate_config] +} diff --git a/modules/compute-providers/ec2/trust-policy/README.md b/modules/compute-providers/ec2/trust-policy/README.md new file mode 100644 index 0000000000..58d0f0e67d --- /dev/null +++ b/modules/compute-providers/ec2/trust-policy/README.md @@ -0,0 +1,41 @@ +# EC2 runner trust policy + +This internal submodule builds the EC2 runner-role trust policy independently from EC2 resources that consume the runner role. It preserves the default EC2 service trust and optionally merges an additional IAM trust policy document supplied by the common runner configuration. + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.4.0 | +| [aws](#requirement\_aws) | >= 6.33 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.33 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_iam_policy_document.assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [additional\_trust\_policy\_json](#input\_additional\_trust\_policy\_json) | Optional IAM policy document merged with the default EC2 runner-role trust policy. | `string` | `null` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [assume\_role\_policy](#output\_assume\_role\_policy) | EC2 runner-role trust policy with the optional additional trust policy merged into it. | + diff --git a/modules/compute-providers/ec2/trust-policy/assume-role.tf b/modules/compute-providers/ec2/trust-policy/assume-role.tf new file mode 100644 index 0000000000..bea81c1b9e --- /dev/null +++ b/modules/compute-providers/ec2/trust-policy/assume-role.tf @@ -0,0 +1,18 @@ +data "aws_iam_policy_document" "default" { + statement { + effect = "Allow" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["ec2.amazonaws.com"] + } + } +} + +data "aws_iam_policy_document" "assume_role" { + source_policy_documents = compact([ + data.aws_iam_policy_document.default.json, + var.additional_trust_policy_json, + ]) +} diff --git a/modules/compute-providers/ec2/trust-policy/outputs.tf b/modules/compute-providers/ec2/trust-policy/outputs.tf new file mode 100644 index 0000000000..0c28bf1661 --- /dev/null +++ b/modules/compute-providers/ec2/trust-policy/outputs.tf @@ -0,0 +1,4 @@ +output "assume_role_policy" { + description = "EC2 runner-role trust policy with the optional additional trust policy merged into it." + value = data.aws_iam_policy_document.assume_role.json +} diff --git a/modules/compute-providers/ec2/trust-policy/tests/trust-policy.tftest.hcl b/modules/compute-providers/ec2/trust-policy/tests/trust-policy.tftest.hcl new file mode 100644 index 0000000000..e764e63fd4 --- /dev/null +++ b/modules/compute-providers/ec2/trust-policy/tests/trust-policy.tftest.hcl @@ -0,0 +1,67 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{}" + } + } +} + +run "returns_default_ec2_trust_policy" { + command = plan + + assert { + condition = toset(data.aws_iam_policy_document.default.statement[0].actions) == toset(["sts:AssumeRole"]) + error_message = "The default EC2 runner role trust policy must allow sts:AssumeRole." + } + + assert { + condition = anytrue([ + for principal in data.aws_iam_policy_document.default.statement[0].principals : + principal.type == "Service" && toset(principal.identifiers) == toset(["ec2.amazonaws.com"]) + ]) + error_message = "The default EC2 runner role trust policy must trust the EC2 service principal." + } + + assert { + condition = ( + length(data.aws_iam_policy_document.assume_role.source_policy_documents) == 1 + && output.assume_role_policy == data.aws_iam_policy_document.assume_role.json + ) + error_message = "The submodule must return the final EC2 assume-role policy." + } +} + +run "merges_additional_trust_policy" { + command = plan + + variables { + additional_trust_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Sid = "TrustedAccount" + Effect = "Allow" + Action = "sts:AssumeRole" + Principal = { AWS = "arn:aws:iam::123456789012:root" } + }] + }) + } + + assert { + condition = ( + length(data.aws_iam_policy_document.assume_role.source_policy_documents) == 2 + && data.aws_iam_policy_document.assume_role.source_policy_documents[1] == var.additional_trust_policy_json + && output.assume_role_policy == data.aws_iam_policy_document.assume_role.json + ) + error_message = "The submodule must merge the additional trust policy into the final assume-role policy." + } +} + +run "rejects_invalid_additional_trust_policy" { + command = plan + + variables { + additional_trust_policy_json = "not-json" + } + + expect_failures = [var.additional_trust_policy_json] +} diff --git a/modules/compute-providers/ec2/trust-policy/variables.tf b/modules/compute-providers/ec2/trust-policy/variables.tf new file mode 100644 index 0000000000..875fa44f4a --- /dev/null +++ b/modules/compute-providers/ec2/trust-policy/variables.tf @@ -0,0 +1,10 @@ +variable "additional_trust_policy_json" { + description = "Optional IAM policy document merged with the default EC2 runner-role trust policy." + type = string + default = null + + validation { + condition = var.additional_trust_policy_json == null ? true : can(jsondecode(var.additional_trust_policy_json)) + error_message = "additional_trust_policy_json must be valid JSON when set." + } +} diff --git a/modules/compute-providers/ec2/trust-policy/versions.tf b/modules/compute-providers/ec2/trust-policy/versions.tf new file mode 100644 index 0000000000..3ef011ea0a --- /dev/null +++ b/modules/compute-providers/ec2/trust-policy/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.4.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.33" + } + } +} diff --git a/modules/compute-providers/ec2/validations.tf b/modules/compute-providers/ec2/validations.tf new file mode 100644 index 0000000000..ff59bafc13 --- /dev/null +++ b/modules/compute-providers/ec2/validations.tf @@ -0,0 +1,53 @@ +resource "terraform_data" "validate_config" { + lifecycle { + precondition { + condition = contains(["spot", "on-demand"], var.config.instance_target_capacity_type) + error_message = "compute_provider.ec2.instance_target_capacity_type must be spot or on-demand." + } + + precondition { + condition = contains( + ["lowest-price", "diversified", "capacity-optimized", "capacity-optimized-prioritized", "price-capacity-optimized", "prioritized"], + var.config.instance_allocation_strategy, + ) + error_message = "compute_provider.ec2.instance_allocation_strategy is not supported." + } + + precondition { + condition = var.config.credit_specification == null ? true : contains(["standard", "unlimited"], var.config.credit_specification) + error_message = "compute_provider.ec2.credit_specification must be null, standard, or unlimited." + } + + precondition { + condition = var.config.cpu_options == null ? true : ( + (var.config.cpu_options.amd_sev_snp == null ? true : contains(["enabled", "disabled"], var.config.cpu_options.amd_sev_snp)) && + (var.config.cpu_options.nested_virtualization == null ? true : contains(["enabled", "disabled"], var.config.cpu_options.nested_virtualization)) + ) + error_message = "compute_provider.ec2.cpu_options amd_sev_snp and nested_virtualization must be enabled or disabled when set." + } + + precondition { + condition = !var.config.binaries_syncer.enabled || var.config.binaries_syncer.s3 != null + error_message = "compute_provider.ec2.binaries_syncer.s3 must be set when compute_provider.ec2.binaries_syncer.enabled is true." + } + + precondition { + condition = var.config.instance_profile == null || !var.runner.iam.role.managed + error_message = "runner.iam.role must be set when compute_provider.ec2.instance_profile selects an external instance profile." + } + } +} + +resource "terraform_data" "validate_runner" { + lifecycle { + precondition { + condition = contains(["linux", "osx", "windows"], var.runner.os) + error_message = "runner.os must be linux, osx, or windows." + } + + precondition { + condition = length(var.runner.name_prefix) <= 45 + error_message = "runner.name_prefix must be at most 45 characters." + } + } +} diff --git a/modules/compute-providers/ec2/variables.tf b/modules/compute-providers/ec2/variables.tf new file mode 100644 index 0000000000..c686049d79 --- /dev/null +++ b/modules/compute-providers/ec2/variables.tf @@ -0,0 +1,365 @@ +variable "aws_partition" { + description = "AWS partition used to construct IAM ARNs." + type = string + default = "aws" +} + +variable "aws_region" { + description = "AWS region used by compute-provider resources and policy documents." + type = string +} + +variable "prefix" { + description = "Prefix used to identify resources created for the runner configuration." + type = string + default = "github-actions" +} + +variable "tags" { + description = "Base tags available to taggable compute-provider resources. Provider-specific tags override this map within their documented scopes." + type = map(string) + default = {} +} + +variable "config" { + description = <<-EOT + EC2 compute-provider configuration. Paths match `compute_provider.ec2` in the runner configuration. + + - `ami`: Optional AMI discovery and encryption configuration. Null selects defaults for `runner.os` and `runner.architecture`. + - `ami.filter`: AMI filter names mapped to accepted values and merged over the provider defaults. + - `ami.owners`: AWS account IDs or aliases allowed to own the selected AMI. + - `ami.id_ssm_parameter`: Optional externally managed SSM parameter containing the AMI ID. Its object presence is the plan-time ownership discriminator. + - `ami.id_ssm_parameter.arn`: ARN of the external AMI-ID parameter. The ARN may remain unknown until apply. + - `ami.kms_key`: Optional customer-managed KMS key required for encrypted AMIs or snapshots. Its object presence is the plan-time policy discriminator. + - `ami.kms_key.arn`: ARN of the AMI KMS key. The ARN may remain unknown until apply. + - `vpc_id`: VPC in which runner networking resources are created. + - `subnet_ids`: Subnets from which the control plane may launch runners. + - `overrides.name_runner`: Optional Name tag override for runner compute resources. + - `overrides.name_sg`: Optional Name tag override for the managed security group. + - `instance_profile`: Optional externally managed instance profile. Its object presence is the plan-time ownership discriminator. + - `instance_profile.name`: Name of the external instance profile. The name may remain unknown until apply. + - `instance_profile_path`: IAM path for the provider-managed instance profile. Null derives the path from `prefix`. + - `binaries_syncer.enabled`: Uses the synchronized runner distribution from S3 during bootstrap. + - `binaries_syncer.s3`: S3 object containing the synchronized runner distribution. Required when synchronization is enabled. + - `binaries_syncer.s3.arn`: Runner-distribution bucket ARN used by IAM policies. + - `binaries_syncer.s3.id`: Runner-distribution bucket name used in the bootstrap URI. + - `binaries_syncer.s3.key`: Runner-distribution object key. + - `block_device_mappings`: EBS mappings added to the launch template. + - `block_device_mappings[].delete_on_termination`: Deletes the volume when its runner terminates. + - `block_device_mappings[].device_name`: Device name exposed to the runner instance. + - `block_device_mappings[].encrypted`: Enables EBS encryption. + - `block_device_mappings[].iops`: Provisioned IOPS for volume types that support configurable IOPS. + - `block_device_mappings[].kms_key_id`: KMS key ID or ARN used to encrypt the volume. + - `block_device_mappings[].snapshot_id`: Snapshot used to initialize the volume. + - `block_device_mappings[].throughput`: Provisioned throughput for volume types that support it. + - `block_device_mappings[].volume_initialization_rate`: Fixed initialization rate for supported snapshot-backed volumes. + - `block_device_mappings[].volume_size`: EBS volume size in GiB. + - `block_device_mappings[].volume_type`: EBS volume type. + - `ebs_optimized`: Requests EBS-optimized instances. + - `instance_target_capacity_type`: Primary capacity type, either `spot` or `on-demand`. + - `instance_allocation_strategy`: EC2 Fleet allocation strategy. + - `instance_type_priorities`: Optional numeric priorities keyed by instance type. + - `instance_max_spot_price`: Optional maximum hourly Spot price. + - `instance_types`: EC2 instance types available to the control plane. + - `user_data`: Runner bootstrap user-data configuration. + - `user_data.enabled`: Enables launch-template user data. + - `user_data.template`: Optional path to a custom user-data template. + - `user_data.content`: Optional complete user-data content used instead of a template. + - `user_data.pre_install`: Script inserted before runner installation. + - `user_data.post_install`: Script inserted after runner installation. + - `user_data.debug_logging_enabled`: Enables verbose user-data tracing, which can expose secrets. + - `ssm_enabled`: Includes Session Manager permissions in the provider's runner policy group. + - `create_service_linked_role_spot`: Allows scale-up to create the EC2 Spot service-linked role. + - `cloudwatch_agent.enabled`: Enables CloudWatch agent configuration for runner instances. + - `cloudwatch_agent.config`: Optional complete CloudWatch agent configuration. + - `managed_security_group_enabled`: Creates and attaches the provider-managed security group. + - `log_files`: Optional files collected by the CloudWatch agent. Null uses provider defaults. + - `log_files[].log_group_name`: CloudWatch log-group name before optional prefixing. + - `log_files[].prefix_log_group`: Prefixes the log-group name with the runner configuration path. + - `log_files[].file_path`: File or glob read by the CloudWatch agent. + - `log_files[].log_stream_name`: CloudWatch log-stream name template. + - `log_files[].log_class`: CloudWatch log-group class for the collected file. + - `key_name`: Optional EC2 key-pair name. + - `additional_security_group_ids`: Existing security groups attached to runners. + - `detailed_monitoring_enabled`: Enables detailed EC2 monitoring. + - `egress_rules`: Rules created on the managed security group. + - `egress_rules[].cidr_blocks`: IPv4 CIDR destinations. + - `egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations. + - `egress_rules[].prefix_list_ids`: AWS prefix-list destinations. + - `egress_rules[].from_port`: First destination port in the permitted range. + - `egress_rules[].protocol`: IP protocol name or number. Use `-1` for all protocols. + - `egress_rules[].security_groups`: Destination security-group IDs. + - `egress_rules[].self`: Allows traffic to the managed security group itself. + - `egress_rules[].to_port`: Last destination port in the permitted range. + - `egress_rules[].description`: Optional rule description. + - `tags`: Runner instance, volume, network-interface, and eligible Spot-request tags. Provider-required bootstrap tags take final precedence. + - `metadata_options`: Instance Metadata Service configuration. + - `metadata_options.instance_metadata_tags`: Exposes instance tags through Instance Metadata Service when enabled. + - `metadata_options.http_endpoint`: Enables or disables the Instance Metadata Service endpoint. + - `metadata_options.http_tokens`: Controls whether IMDSv2 session tokens are optional or required. + - `metadata_options.http_put_response_hop_limit`: Network hop limit for Instance Metadata Service token responses. + - `credit_specification`: CPU credit mode for burstable instance types. + - `cpu_options`: CPU topology and processor-feature configuration. + - `cpu_options.core_count`: Number of CPU cores exposed to the runner instance. + - `cpu_options.threads_per_core`: Number of hardware threads exposed per CPU core. + - `cpu_options.amd_sev_snp`: Enables or disables AMD SEV-SNP on supported instance types. + - `cpu_options.nested_virtualization`: Enables or disables nested virtualization on supported instance types. + - `placement`: EC2 placement configuration. + - `placement.affinity`: Dedicated Host affinity setting. + - `placement.availability_zone`: Availability Zone in which runner instances are placed. + - `placement.group_id`: Placement-group ID. + - `placement.group_name`: Placement-group name. + - `placement.host_id`: Dedicated Host ID. + - `placement.host_resource_group_arn`: ARN of the host resource group used for placement. + - `placement.spread_domain`: Spread-domain placement value. + - `placement.tenancy`: Instance tenancy, such as `default`, `dedicated`, or `host`. + - `placement.partition_number`: Placement-group partition number. + - `license_specifications`: License Manager configurations added to the launch template. + - `license_specifications[].license_configuration_arn`: ARN of an AWS License Manager license configuration. + - `associate_public_ipv4_address`: Associates a public IPv4 address with runner network interfaces. + - `enable_on_demand_failover_for_errors`: EC2 errors that trigger on-demand fallback after a Spot failure. + - `scale_errors`: EC2 errors treated as retryable scale-up failures. + - `use_dedicated_host`: Enables the dedicated-host launch path. + EOT + + type = object({ + ami = optional(object({ + filter = optional(map(list(string)), { state = ["available"] }) + owners = optional(list(string), ["amazon"]) + id_ssm_parameter = optional(object({ + arn = string + }), null) + kms_key = optional(object({ + arn = string + }), null) + }), null) + vpc_id = string + subnet_ids = list(string) + overrides = optional(object({ + name_runner = optional(string, "") + name_sg = optional(string, "") + }), {}) + instance_profile = optional(object({ + name = string + }), null) + instance_profile_path = optional(string, null) + binaries_syncer = optional(object({ + enabled = optional(bool, true) + s3 = optional(object({ + arn = string + id = string + key = string + }), null) + }), {}) + block_device_mappings = optional(list(object({ + delete_on_termination = optional(bool, true) + device_name = optional(string, "/dev/xvda") + encrypted = optional(bool, true) + iops = optional(number) + kms_key_id = optional(string) + snapshot_id = optional(string) + throughput = optional(number) + volume_initialization_rate = optional(number) + volume_size = number + volume_type = optional(string, "gp3") + })), [{ volume_size = 30 }]) + ebs_optimized = optional(bool, false) + instance_target_capacity_type = optional(string, "spot") + instance_allocation_strategy = optional(string, "lowest-price") + instance_type_priorities = optional(map(number), null) + instance_max_spot_price = optional(string, null) + instance_types = list(string) + user_data = optional(object({ + enabled = optional(bool, true) + template = optional(string, null) + content = optional(string, null) + pre_install = optional(string, "") + post_install = optional(string, "") + debug_logging_enabled = optional(bool, false) + }), {}) + ssm_enabled = optional(bool, false) + create_service_linked_role_spot = optional(bool, false) + cloudwatch_agent = optional(object({ + enabled = optional(bool, true) + config = optional(string, null) + }), {}) + managed_security_group_enabled = optional(bool, true) + log_files = optional(list(object({ + log_group_name = string + prefix_log_group = bool + file_path = string + log_stream_name = string + log_class = optional(string, "STANDARD") + })), null) + key_name = optional(string, null) + additional_security_group_ids = optional(list(string), []) + detailed_monitoring_enabled = optional(bool, false) + egress_rules = optional(list(object({ + cidr_blocks = list(string) + ipv6_cidr_blocks = list(string) + prefix_list_ids = list(string) + from_port = number + protocol = string + security_groups = list(string) + self = bool + to_port = number + description = string + })), [{ + cidr_blocks = ["0.0.0.0/0"] + ipv6_cidr_blocks = ["::/0"] + prefix_list_ids = null + from_port = 0 + protocol = "-1" + security_groups = null + self = null + to_port = 0 + description = null + }]) + tags = optional(map(string), {}) + metadata_options = optional(object({ + instance_metadata_tags = optional(string, "enabled") + http_endpoint = optional(string, "enabled") + http_tokens = optional(string, "required") + http_put_response_hop_limit = optional(number, 1) + }), {}) + credit_specification = optional(string, null) + cpu_options = optional(object({ + core_count = optional(number) + threads_per_core = optional(number) + amd_sev_snp = optional(string) + nested_virtualization = optional(string) + }), null) + placement = optional(object({ + affinity = optional(string) + availability_zone = optional(string) + group_id = optional(string) + group_name = optional(string) + host_id = optional(string) + host_resource_group_arn = optional(string) + spread_domain = optional(string) + tenancy = optional(string) + partition_number = optional(number) + }), null) + license_specifications = optional(list(object({ + license_configuration_arn = string + })), []) + associate_public_ipv4_address = optional(bool, false) + enable_on_demand_failover_for_errors = optional(list(string), []) + scale_errors = optional(list(string), [ + "UnfulfillableCapacity", + "MaxSpotInstanceCountExceeded", + "TargetCapacityLimitExceededException", + "RequestLimitExceeded", + "ResourceLimitExceeded", + "MaxSpotInstanceCountExceeded", + "MaxSpotFleetRequestCountExceeded", + "InsufficientInstanceCapacity", + "InsufficientCapacityOnHost", + ]) + use_dedicated_host = optional(bool, false) + }) + + nullable = false +} + +variable "runner" { + description = <<-EOT + Provider-neutral runner settings consumed by compute providers. + + - `os`: Runner operating system. Supported values are `linux`, `osx`, and `windows`. + - `architecture`: Runner distribution architecture. + - `name_prefix`: Prefix added to registered runner names. + - `run_as_root`: Runs the runner service as root. + - `run_as`: Operating-system user used when `run_as_root` is false. + - `hooks.job_started`: Script installed as the runner job-started hook. + - `hooks.job_completed`: Script installed as the runner job-completed hook. + - `iam.role.arn`: Resolved runner-role ARN referenced by provider policies and resources. + - `iam.role.name`: Resolved runner-role name used by provider resources. + - `iam.role.managed`: Whether runner-config manages the resolved runner role. + - `iam.managed_policy_arns`: Common managed-policy ARNs returned with the provider-specific runner policies for attachment by runner-config. + - `iam.path`: IAM path available to provider-managed IAM resources. Null derives the path from `prefix`. + EOT + type = object({ + os = optional(string, "linux") + architecture = optional(string, "x64") + name_prefix = optional(string, "") + run_as_root = optional(bool, false) + run_as = optional(string, "ec2-user") + hooks = optional(object({ + job_started = optional(string, "") + job_completed = optional(string, "") + }), {}) + iam = object({ + role = object({ + arn = string + name = string + managed = optional(bool, true) + }) + managed_policy_arns = optional(map(string), {}) + path = optional(string, null) + }) + }) + + nullable = false +} + +variable "github" { + description = <<-EOT + GitHub Enterprise Server settings available to compute-provider bootstrap data. + + - `enterprise_server.url`: Optional GitHub Enterprise Server base URL. Null selects GitHub.com. + - `enterprise_server.ssl_verify`: Enables TLS certificate verification for GitHub Enterprise Server. + EOT + type = object({ + enterprise_server = optional(object({ + url = optional(string, null) + ssl_verify = optional(bool, true) + }), {}) + }) + default = {} + nullable = false +} + +variable "ssm" { + description = <<-EOT + Parameter Store paths and tag scopes available to compute-provider bootstrap resources. + + - `paths.root`: Root Parameter Store path for the runner configuration. + - `paths.tokens`: Path segment used for registration tokens and just-in-time configuration. + - `paths.config`: Path segment used for persistent runner and provider configuration. + - `tags`: Shared SSM tags that override module-level `tags`. + - `parameters.tags`: Parameter-specific tags that override module-level and shared SSM tags. + EOT + type = object({ + paths = object({ + root = string + tokens = string + config = string + }) + tags = optional(map(string), {}) + parameters = optional(object({ + tags = optional(map(string), {}) + }), {}) + }) + + nullable = false +} + +variable "observability" { + description = <<-EOT + CloudWatch Logs settings available to compute-provider runner log groups. + + - `logs.retention_in_days`: Retention period for provider-owned runner log groups. + - `logs.kms_key_id`: Optional KMS key ID or ARN used to encrypt runner log groups. + - `logs.tags`: Shared log-group tags that override module-level `tags`. + EOT + type = object({ + logs = optional(object({ + retention_in_days = optional(number, 180) + kms_key_id = optional(string, null) + tags = optional(map(string), {}) + }), {}) + }) + default = {} + nullable = false +} diff --git a/modules/compute-providers/ec2/versions.tf b/modules/compute-providers/ec2/versions.tf new file mode 100644 index 0000000000..3ef011ea0a --- /dev/null +++ b/modules/compute-providers/ec2/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.4.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.33" + } + } +} diff --git a/modules/multi-runner/README.md b/modules/multi-runner/README.md index 21fc8f441b..ed02883f89 100644 --- a/modules/multi-runner/README.md +++ b/modules/multi-runner/README.md @@ -2,13 +2,14 @@ > This module replaces the top-level module to make it easy to create with one deployment multiple type of runners. -This module creates many runners with one or more GitHub Apps. The module utilizes the internal modules and deploys parts of the stack for each runner defined. +This module creates many runners with one or more GitHub Apps. It uses internal modules to deploy the resources for each runner configuration. ### GitHub App round-robin -To distribute GitHub API rate limit usage, this module supports configuring multiple GitHub Apps via the `additional_github_apps` variable. The control-plane lambdas (scale-up, scale-down, pool, job-retry) randomly select an app for each API call, spreading the load across all configured apps. +To distribute GitHub API rate limit usage, this module supports configuring multiple GitHub Apps. Stable v1 uses `additional_github_apps`; v2 uses the authoritative `experimental.github.additional_apps`, which defaults to `[]`. The control-plane lambdas (scale-up, scale-down, pool, job-retry) randomly select an app for each API call, spreading the load across all configured apps. + +The **primary app** (`github_app` in v1 and `experimental.github.app` in v2) is special: -The **primary app** (`github_app`) is special: - Its **webhook secret** is used to validate incoming GitHub webhook payloads. Only the primary app needs a webhook URL configured in GitHub. - Its **app ID and private key** are included in the round-robin pool alongside the additional apps. @@ -18,9 +19,69 @@ The **webhook lambda** does not participate in round-robin: it only validates in The module takes a configuration as input containing a matcher for the labels. The [webhook](https://github-aws-runners.github.io/terraform-aws-github-runner/modules/internal/webhook/) lambda is using the configuration to delegate events based on the labels in the workflow job and sent them to a dedicated queue based on the configuration. Events on each queue are processed by a dedicated lambda per configuration to scale runners. +## Provider boundary + +See [Experimental compute-provider refactor](https://github-aws-runners.github.io/terraform-aws-github-runner/modules/internal/compute-provider-refactor/) for the motivation, ownership contract, opt-in flow, state guarantees, and migration phases. + +The multi-runner module owns provider-neutral runner-configuration normalization, queues, shared runner-binary discovery, and webhook routing. Stable `multi_runner_config` entries continue to use the existing `modules/runners` module at their historical `module.runners["configuration"]` addresses. + +A non-empty `experimental.multi_runner_config` opts the whole module instance into v2 and takes priority over the stable top-level `multi_runner_config`; entries from the maps are never combined. V2 uses `modules/runner-config` at `module.runner_configs["configuration"]`; a module-level moved block maps the former `module.runner_stacks` address to this composition name without recreating existing v2 resources. Sibling `experimental.tags`, `roles`, `runner`, `github`, `lambda`, `orchestration`, `ssm`, `observability`, and `compute_provider` blocks provide global defaults, while each runner configuration can override supported configuration-owned values. The global translated values also configure the singleton GitHub App Parameter Store module, webhook, runner-binary syncer, termination watcher, and AMI housekeeper. Migrated v2 consumers do not fall back to matching flat inputs; those flat values seed stable-mode translation only. Per-configuration overrides affect only that runner configuration, never a singleton shared component. A nullable configuration field inherits its global value. Within v2 queue and runner-config scopes, tags merge from global to configuration and then from broad component scopes to narrow ones. `experimental.tags` is also the base tag map for the translated shared components. + +The implementation has one canonical configuration pipeline in `config.experimental.translation.tf`. A non-empty experimental runner-configuration map selects v2; otherwise the file projects flat globals and stable `multi_runner_config` entries into the same schema. That selection produces `local.raw_translated_experimental`, from which the same file derives `local.translated_experimental_base`, applying schema defaults, configuration-over-global precedence, tag merges, IAM ownership, paths, observability, queues, and provider defaults before plan-shaping discovery. Provider selection and the shared runner-binary syncer and discovery consume this base. After discovery, the translation file derives the final `local.translated_experimental`, including labels, runner-config GitHub client settings, the webhook-owned runner-control artifact, Lambda principals and shared artifact bucket, SSM KMS, and the discovered EC2 binaries object. The remaining shared components, queues, and runner implementations consume this final canonical representation. Stable runner configurations are adapted back into the existing `module.runners["configuration"]` call, so their Terraform addresses remain unchanged. The `module.runner_configs` call directly iterates the gated final runner configurations, inlines the environment tag and live GitHub App and build-queue references under `orchestration.webhook`, and forwards the remaining canonical objects, including the wrapped `compute_provider = { ec2 = ... }` contract. + +V2 requires `experimental.github.app`, and `experimental.github.additional_apps` defaults to `[]`. These nested values are authoritative end-to-end for the shared Parameter Store module and v2 runner configurations; flat `github_app` and `additional_github_apps` seed stable-mode translation only. `experimental.orchestration.webhook.github.repository_white_list` defaults to `[]` and filters the shared webhook when populated. `experimental.github.enterprise_server.url` defaults to `null` and configures both v2 runner-config GitHub clients and the shared termination watcher. `experimental.github.enterprise_server.ssl_verify` and `experimental.github.user_agent` remain runner-config client settings and default to `true` and `github-aws-runners`. The shared webhook does not make GitHub API requests. + +Shared singleton resources use the translated global contract without accepting per-configuration overrides. The shared webhook and its webhook-secret parameter retain their historical singleton addresses and are always created; only build-queue and matcher membership is filtered to runner configurations that select `orchestration.webhook`, so future non-webhook providers do not change the singleton lifecycle. The shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper consume global Lambda runtime, architecture, networking, role, tags, logging, and tracing settings; `lambda.principals` additionally configures runner-config, runner-binary-syncer, termination-watcher, and AMI-housekeeper roles, but not the webhook role. Global metrics also configure the termination watcher. Global `experimental.lambda` contains only that shared Lambda substrate: the artifact bucket, runtime, architecture, principals, networking, tags, and role defaults. Workflow-job webhook control-plane defaults live under `experimental.orchestration.webhook`. The runner-control artifact shared by scale, pool, and job-retry comes from `experimental.orchestration.webhook.lambda.artifact.{zip,s3}`; the S3 wrapper supplies `key` and optional `object_version` for the shared `experimental.lambda.artifact.s3.bucket`. Each runner configuration's SSM housekeeper independently resolves `multi_runner_config[].ssm.housekeeper.lambda.artifact` over the global `experimental.ssm.housekeeper.lambda.artifact`; an S3 selection combines its key and optional object version with the same shared artifact bucket, a zip selection uses its local path, and no selection uses runner-config's packaged runner control-plane archive. The module validates that zip and S3 are mutually exclusive and that an S3 wrapper has a non-null shared bucket and key. Stable-mode translation maps the legacy runner artifact into both canonical runner-control and SSM-housekeeper component contracts while preserving S3-over-zip precedence. The shared bucket alone selects no component. Each artifact-capable singleton—including the ingress webhook—uses it only when its separate nested `artifact.s3` wrapper supplies that component's key and optional object version. The runner-binary syncer uses the parallel `experimental.compute_provider.ec2.runner_binaries.syncer.artifact.{zip,s3}` selector; its S3 key and optional object version also resolve against the shared bucket. `experimental.orchestration.webhook` owns runner lifecycle, repository filtering, queue selection, EventBridge routing, accepted event types, matcher-parameter tier, queue defaults, and webhook/scale/pool Lambda component defaults. Its `lambda.webhook` block owns the ingress webhook's separate artifact selection, API Gateway access logs, sizing, and component tags. `compute_provider.ec2.instance_termination_watcher`, `compute_provider.ec2.ami.housekeeper`, and `compute_provider.ec2.runner_binaries` own their component-specific behavior, artifacts, sizing, schedules, and related settings. Only `prefix`, `aws_partition`, and `aws_region` remain active flat-only inputs; legacy `iam_overrides` remains in the input schema but has no active consumer. + +Global `ssm.paths.root` is the base for the shared GitHub App and webhook parameters and for configuration-owned parameters. The shared resources append `ssm.paths.app` (default `app`) or `ssm.paths.webhook` (default `webhook`); normalization appends the configuration key only to runner-configuration roots. The default derived base is `/github-action-runners/${prefix}`, and runner-configuration token/config segments default to `runners/tokens` and `runners/config`. Global `ssm.kms_key_id` is an optional KMS-key ARN that encrypts the shared GitHub App parameters, configures the webhook, and adds matching decrypt permissions to every runner configuration. It does not select encryption for runtime-created runner-configuration parameters. Provider-owned runner-config IAM omits the KMS statement when the key is null and still accepts an ARN whose value is unknown until apply; the unchanged shared webhook retains its legacy policy handling. + +Each runner configuration selects exactly one typed `orchestration` provider and exactly one typed `compute_provider`; the corresponding global blocks supply defaults without selecting providers. `runner-config` validates both selections, owns the common runner role and SSM housekeeper, and connects compute-provider capabilities to the selected orchestration provider. `orchestration-providers/webhook` owns scale-up, scale-down, pool, and job-retry resources. The EC2 provider owns EC2 policy requirements, the instance profile, launch template, bootstrap resources, and provider-specific Lambda fragments. Provider-block selection must be known during planning because it determines the module graph. These child modules are internal implementation boundaries rather than standalone public entry points. EC2 remains the only Terraform-managed runner provider; MicroVM, CodeBuild, and other provider modules are future work. + +In v2, common runner-role configuration belongs under `runner.iam`; EC2's optional external instance-profile selection belongs under `compute_provider.ec2.instance_profile`. Provider policy documents are generated internally and attached by runner-config when it creates the role. An external role remains unmanaged and must already contain the required policies. + +Phase 1 supports both input contracts with deterministic precedence. When `experimental.multi_runner_config` is empty, the stable top-level `multi_runner_config` follows the unchanged legacy path. When the experimental map is non-empty, it becomes the complete runner map and stable entries are ignored. The maps are not merged. + +Global `experimental.orchestration.webhook.queue` owns the v2 defaults for build-queue delay, retention, visibility, redrive, tags, and encryption. `delay_webhook_event` defaults to `30`, `job_queue_retention_in_seconds` to `86400`, `visibility_timeout_seconds` to `180`, and `tags` to `{}`. Redrive defaults to disabled with a null `maxReceiveCount`; a null configuration wrapper or leaf inherits the matching global value, and an enabled result requires `maxReceiveCount` greater than zero. Configuration fields under `multi_runner_config[].orchestration.webhook.queue` override the corresponding global queue defaults, and configuration tags merge over global queue tags. Encryption remains global-only. Omitting the whole encryption block selects SQS-managed encryption and null KMS attributes. When supplying the block explicitly, provide all three leaves and use null for inactive KMS or SQS-managed settings. A non-null `kms_master_key_id` must be a KMS key ARN—not a key ID or alias—because it also becomes an IAM resource; a computed ARN may remain unknown until apply. This block configures the multi-runner build queues and their dead-letter queues, not runner-config job-retry queues. Its CMK is independent from `experimental.ssm.kms_key_id` and is forwarded separately to each webhook runner configuration: provider-owned IAM grants scale-up `kms:Decrypt` and job-retry `kms:Decrypt` plus `kms:GenerateDataKey`. The shared webhook module is intentionally unchanged, so its producer role does not derive queue-CMK permissions from this field; ensure the key policy or caller-managed IAM covers producer access when required. + +For v2, `multi_runner_config[].orchestration.webhook.queue.visibility_timeout_seconds` controls build-queue visibility independently from `multi_runner_config[].orchestration.webhook.lambda.scale.up.timeout`. Keep visibility at least six times the resolved scale-up Lambda timeout; the module validates this relationship. The v1 translation preserves the flat behavior by using `runners_scale_up_lambda_timeout` for build-queue visibility and `queue_encryption` for encryption. + +Global `experimental.compute_provider.ec2.runner_binaries` owns the shared distribution-bucket and syncer defaults. It covers runner-configuration enablement, bucket encryption, tags, versioning and access logging, plus the syncer artifact, Lambda sizing, and schedule. `runner_binaries.enabled` defaults to `true`, while a nullable per-configuration `compute_provider.ec2.binaries_syncer.enabled` overrides that default; enabled distributions are created once per unique operating-system and architecture pair. The resolved enable value, `s3.encryption.enabled`, the nullness of `s3.encryption.kms_master_key_id`, and the nullness of `s3.logging.bucket` must be known during planning because they determine module or resource shape. A distribution CMK grants the syncer access, but runner roles do not derive `kms:Decrypt` from it; attach that permission separately when using a CMK. + +### V2 tagging + +For v2 runner configurations, `experimental.tags` are merged with configuration `tags`. Shared `lambda.tags`, `orchestration.webhook.queue.tags`, and configuration-resolved `observability.logs.tags` are then merged with component tags such as `runner.tags`, `orchestration.webhook.lambda.scale.up.tags`, `orchestration.webhook.lambda.scale.down.tags`, `orchestration.webhook.lambda.webhook.tags`, `orchestration.webhook.lambda.pool.tags`, `orchestration.webhook.job_retry.tags`, and the nested SSM tag scopes. Narrower scopes win repeated keys. Queue tags apply to the configuration build queue and dead-letter queue owned by multi-runner. The shared GitHub App Parameter Store module merges `experimental.tags` with `ssm.tags`; the webhook merges `lambda.tags` with `orchestration.webhook.lambda.webhook.tags`; the runner-binary syncer, termination watcher, and AMI housekeeper use global `tags` and `lambda.tags`, while `compute_provider.ec2.runner_binaries.s3.tags` adds distribution-bucket-only tags. Observability log tags remain configuration-owned runner-config log-group tags. In stable mode, translation preserves the existing flat behavior. + +The output contracts are separated so a single map never contains two incompatible entry schemas. In v1 mode, entries remain exclusively in `runners_map` with their existing flat shape and `runners_map_v2` is empty. In v2 mode, entries are exposed exclusively through `runners_map_v2`, with demand-control resources canonically grouped under `orchestration.webhook`, while `runners_map` is empty. Use `runners_map_v2["configuration"].runner.role` for the common runner role and `runners_map_v2["configuration"].orchestration.webhook.scale_up.lambda`, `.log_group`, and `.role` for scale-up resources. The same resource shape is used for `scale_down` and an enabled `pool`; `pool` is null when it is disabled. Existing flat `scale_up`, `scale_down`, and `pool` output aliases remain available for compatibility. Provider-specific resources are grouped under the selected provider key, which also identifies the compute provider. For EC2, launch-template and runner-log resources remain under `runners_map_v2["configuration"].provider.ec2`. + +### Multi-runner v2 migration roadmap + +Here, v1 and v2 refer to the stable top-level `multi_runner_config` and `experimental.multi_runner_config`, not module release versions. The migration is intentionally split across releases so configuration migration, state migration, and interface removal do not happen at the same time. + +#### Phase 1 — Add v2 as a module-level opt-in (current) + +Both input contracts are available in the same module release. An empty `experimental.multi_runner_config` keeps every stable top-level `multi_runner_config` entry on the existing `modules/runners` implementation at `module.runners["configuration"]`, retaining its flat `runners_map` output and Terraform addresses. Internally, the flat input is projected through `local.translated_experimental_base` and finalized as `local.translated_experimental`; `runners.tf` adapts those canonical runner configurations to the existing module call instead of forwarding the original v1 object. A non-empty experimental map selects `module.runner_configs["configuration"]` and the nested `runners_map_v2` output shape; it takes priority over stable entries, and the maps are not combined. + +Compatibility guarantee: upgrading while leaving `experimental.multi_runner_config` empty requires no state migration and must not move or replace legacy runner resources. Phase 1 does not support mixing implementations or migrating an existing v1 deployment by enabling v2; existing deployments should wait for phase 2 state mapping. The v2 opt-in is for new or explicitly experimental deployments. + +#### Phase 2 — Translate v1 and migrate state + +`multi_runner_config` remains accepted but is deprecated, and its existing translated representation becomes the dispatch source for `runner-config`. Existing users can therefore migrate the implementation and state without first combining v1 and v2 inputs. This phase will include tested `moved` blocks wherever Terraform can express the mapping and exact state-migration instructions for remaining addresses. The legacy flat output shape remains available as a compatibility adapter while users update configuration and output references. + +Compatibility guarantee: users can migrate implementation state before rewriting their configuration. With equivalent inputs, the documented migration must produce a plan without unintended runner-resource destruction or replacement. + +#### Phase 3 — Remove v1 from multi-runner + +After the announced migration window, a breaking release removes `multi_runner_config`, its translation, and the legacy flat output adapter from the multi-runner module. Only the v2 provider-oriented contract remains. Phase 3 will not introduce another state-address migration. + +Compatibility guarantee: phase 3 will not be released together with phase 2. Users will have at least one released migration version in which v1 is still accepted before its removal. + +#### Future — Retire the legacy runners module + +Removing `modules/runners` is a separate future change. It requires its own compatibility analysis, migration instructions, and deprecation window for direct and top-level consumers; it is not part of this provider-boundary refactor. + For each configuration: -- When enabled, the [distribution syncer](https://github-aws-runners.github.io/terraform-aws-github-runner/modules/internal/runner-binaries-syncer/) is deployed for each unique combination of OS and architecture. +- When globally enabled or enabled by a per-configuration override, the [distribution syncer](https://github-aws-runners.github.io/terraform-aws-github-runner/modules/internal/runner-binaries-syncer/) is deployed for each unique combination of OS and architecture. - For each configuration a queue is created and [runner module](https://github-aws-runners.github.io/terraform-aws-github-runner/modules/internal/runners/) is deployed ## Matching @@ -99,7 +160,7 @@ module "multi-runner" { | Name | Version | |------|---------| -| [terraform](#requirement\_terraform) | >= 1.3 | +| [terraform](#requirement\_terraform) | >= 1.4.0 | | [aws](#requirement\_aws) | >= 6.33 | | [random](#requirement\_random) | ~> 3.0 | @@ -109,6 +170,7 @@ module "multi-runner" { |------|---------| | [aws](#provider\_aws) | >= 6.33 | | [random](#provider\_random) | ~> 3.0 | +| [terraform](#provider\_terraform) | n/a | ## Modules @@ -117,6 +179,7 @@ module "multi-runner" { | [ami\_housekeeper](#module\_ami\_housekeeper) | ../ami-housekeeper | n/a | | [instance\_termination\_watcher](#module\_instance\_termination\_watcher) | ../termination-watcher | n/a | | [runner\_binaries](#module\_runner\_binaries) | ../runner-binaries-syncer | n/a | +| [runner\_configs](#module\_runner\_configs) | ../runner-config | n/a | | [runners](#module\_runners) | ../runners | n/a | | [ssm](#module\_ssm) | ../ssm | n/a | | [webhook](#module\_webhook) | ../webhook | n/a | @@ -130,7 +193,9 @@ module "multi-runner" { | [aws_sqs_queue_policy.build_queue_dlq_policy](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sqs_queue_policy) | resource | | [aws_sqs_queue_policy.build_queue_policy](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sqs_queue_policy) | resource | | [random_string.random](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/string) | resource | -| [aws_iam_policy_document.deny_insecure_transport](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [terraform_data.validate_experimental](https://registry.terraform.io/providers/hashicorp/terraform/latest/docs/resources/data) | resource | +| [aws_iam_policy_document.deny_insecure_transport_build](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.deny_insecure_transport_build_dlq](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | ## Inputs @@ -151,9 +216,10 @@ module "multi-runner" { | [enable\_ami\_housekeeper](#input\_enable\_ami\_housekeeper) | Option to disable the lambda to clean up old AMIs. | `bool` | `false` | no | | [enable\_managed\_runner\_security\_group](#input\_enable\_managed\_runner\_security\_group) | Enabling the default managed security group creation. Unmanaged security groups can be specified via `runner_additional_security_group_ids`. | `bool` | `true` | no | | [eventbridge](#input\_eventbridge) | Enable the use of EventBridge by the module. By enabling this feature events will be put on the EventBridge by the webhook instead of directly dispatching to queues for scaling. |
object({
enable = optional(bool, true)
accept_events = optional(list(string), [])
})
| `{}` | no | +| [experimental](#input\_experimental) | Opt-in experimental features. Omit this object to retain only the stable `multi_runner_config` behavior. Experimental schemas can change before they become stable.

Set `experimental.multi_runner_config` to opt into provider-oriented runner configurations. A non-empty experimental map completely replaces the stable top-level `multi_runner_config`; an empty map keeps stable entries on the unchanged `runners` module.

Sibling blocks provide global v2 defaults. Global and per-configuration values use `configuration override > experimental global v2 default` precedence. Migrated v2 consumers do not inherit a matching flat module input. Singleton shared components consume the global translated values documented below; per-configuration overrides affect only their runner configuration. Component-specific inputs without a nested counterpart continue consuming their existing flat inputs. Tag maps merge from broad to narrow instead of replacing the broader map.
Nullable per-configuration values inherit their experimental global value, so only defaults that apply to every runner configuration should be placed in a global block. When a runner configuration selects an external `runner.iam.role`, inherited managed policies and additional trust policy JSON are intentionally suppressed because this module does not manage that role.
Plan-shaping ownership wrappers remain nullable where their object presence controls Terraform graph shape. `ssm.kms_key_id` is instead an ARN-valued scalar; provider-owned IAM omits null KMS statements while still accepting an ARN whose value is unknown until apply. The unchanged shared webhook retains its legacy policy handling.

Global experimental fields support the following nested properties. These values apply directly when `experimental.multi_runner_config` is non-empty; in stable mode, flat inputs are translated into the same global shape.

- `tags`: Base tags for v2 build queues, runner configurations, the shared GitHub App Parameter Store module, webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `{}`.
- `roles.path`: Default IAM path for module-managed v2 runner and Lambda roles and for the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper Lambda roles. The default is null.
- `roles.permissions_boundary`: Default permissions-boundary ARN for module-managed v2 runner and Lambda roles and for the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper Lambda roles. The default is null.
- `runner.os`: Default runner operating system. The default is null; every runner configuration must resolve this field globally or locally.
- `runner.architecture`: Default runner distribution architecture. The default is null; every runner configuration must resolve this field globally or locally.
- `runner.disable_default_labels`: Omits the default self-hosted, operating-system, and architecture labels when true. The default is `false`.
- `runner.extra_labels`: Default additional labels combined with each runner configuration's matcher labels. The default is `[]`.
- `runner.group_name`: Default GitHub runner group. The default is `Default`.
- `runner.name_prefix`: Default prefix added to registered runner names. The default is an empty string.
- `runner.run_as_root`: Runs the runner service as root when supported by the provider. The default is `false`.
- `runner.run_as`: Default operating-system user when `run_as_root` is false. The default is `ec2-user`.
- `runner.auto_update_disabled`: Disables the GitHub runner application's built-in updater. The default is `false`.
- `runner.tags`: Default tags for common runner resources, currently the module-managed runner IAM role. The default is `{}`.
- `runner.hooks.job_started`: Default script content installed as the runner job-started hook. The default is an empty string.
- `runner.hooks.job_completed`: Default script content installed as the runner job-completed hook. The default is an empty string.
- `runner.iam.role`: Optional externally managed runner-role wrapper. The default is null; wrapper presence selects external role ownership during planning.
- `runner.iam.role.arn`: ARN of the externally managed runner role.
- `runner.iam.managed_policy_arns`: Named managed-policy ARNs attached to module-managed runner roles. The default is `{}`. Keep this map empty when the global `runner.iam.role` selects an external role; a runner configuration that explicitly selects its own external role suppresses the inherited map.
- `runner.iam.additional_trust_policy_json`: Optional IAM policy document merged with the provider trust policy for module-managed runner roles. The default is null. Keep it null when the global `runner.iam.role` selects an external role; a runner configuration that explicitly selects its own external role suppresses the inherited value.
- `runner.iam.path`: Runner-role IAM path. The default is null, which falls back to `roles.path`.
- `runner.iam.permissions_boundary`: Runner-role permissions-boundary ARN. The default is null, which falls back to `roles.permissions_boundary`.
- `github.app`: Primary GitHub App credentials persisted or selected by the shared Parameter Store module and used by v2 runner configurations. The default is null, but a non-empty v2 map requires this object.
- `github.app.key_base64`: Base64-encoded GitHub App private key supplied directly.
- `github.app.key_base64_ssm`: Existing Parameter Store private-key parameter wrapper. Set this or `key_base64`.
- `github.app.key_base64_ssm.arn`: ARN of the existing private-key parameter.
- `github.app.key_base64_ssm.name`: Name of the existing private-key parameter.
- `github.app.id`: GitHub App ID supplied directly.
- `github.app.id_ssm`: Existing Parameter Store app-ID parameter wrapper. Set this or `id`.
- `github.app.id_ssm.arn`: ARN of the existing app-ID parameter.
- `github.app.id_ssm.name`: Name of the existing app-ID parameter.
- `github.app.webhook_secret`: GitHub App webhook secret supplied directly.
- `github.app.webhook_secret_ssm`: Existing Parameter Store webhook-secret parameter wrapper. Set this or `webhook_secret`.
- `github.app.webhook_secret_ssm.arn`: ARN of the existing webhook-secret parameter.
- `github.app.webhook_secret_ssm.name`: Name of the existing webhook-secret parameter.
- `github.additional_apps`: Additional GitHub App credentials persisted or selected by the shared Parameter Store module and used for API request distribution. The default is `[]`.
- `github.additional_apps[].key_base64`: Base64-encoded private key supplied directly for an additional app.
- `github.additional_apps[].key_base64_ssm`: Existing Parameter Store private-key parameter wrapper. Set this or `key_base64`.
- `github.additional_apps[].key_base64_ssm.arn`: ARN of the existing additional-app private-key parameter.
- `github.additional_apps[].key_base64_ssm.name`: Name of the existing additional-app private-key parameter.
- `github.additional_apps[].id`: Additional GitHub App ID supplied directly.
- `github.additional_apps[].id_ssm`: Existing Parameter Store app-ID parameter wrapper. Set this or `id`.
- `github.additional_apps[].id_ssm.arn`: ARN of the existing additional-app ID parameter.
- `github.additional_apps[].id_ssm.name`: Name of the existing additional-app ID parameter.
- `github.additional_apps[].installation_id`: Optional installation ID supplied directly for an additional app.
- `github.additional_apps[].installation_id_ssm`: Optional existing Parameter Store installation-ID parameter wrapper.
- `github.additional_apps[].installation_id_ssm.arn`: ARN of the existing installation-ID parameter.
- `github.additional_apps[].installation_id_ssm.name`: Name of the existing installation-ID parameter.
- `github.enterprise_server.url`: GitHub Enterprise Server URL used by v2 runner-config GitHub clients and the shared termination watcher. The default is null.
- `github.enterprise_server.ssl_verify`: Enables TLS certificate verification for v2 runner-config GitHub clients. The default is `true`.
- `github.user_agent`: HTTP User-Agent used by v2 runner-config GitHub clients. The default is `github-aws-runners`.
- `lambda.artifact.s3.bucket`: Optional shared S3 bucket containing Lambda deployment artifacts for v2 runner configurations and their SSM housekeepers, the webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is null. A component selects an object from this bucket only when its own `artifact.s3` wrapper is present.
- `lambda.runtime`: Runtime for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `nodejs24.x`.
- `lambda.architecture`: Architecture for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `arm64`.
- `lambda.principals`: Additional principals allowed to assume v2 runner-config, runner-binary syncer, termination-watcher, and AMI-housekeeper Lambda roles. The default is `[]`; list membership must be known during planning because it creates IAM principal blocks.
- `lambda.principals[].type`: IAM principal type.
- `lambda.principals[].identifiers`: IAM principal identifiers for the type.
- `lambda.subnet_ids`: Subnets for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `[]`.
- `lambda.security_group_ids`: Security groups for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `[]`.
- `lambda.tags`: Default tags for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `{}`.
- `lambda.role.path`: IAM path for module-managed v2 Lambda roles and the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper roles. The default is null, which falls back to `roles.path`.
- `lambda.role.permissions_boundary`: Permissions-boundary ARN for module-managed v2 Lambda roles and the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper roles. The default is null, which falls back to `roles.permissions_boundary`.
- `orchestration.webhook`: Global defaults for the workflow-job webhook control plane. This is a defaults namespace; every runner configuration still selects its demand controller independently under `multi_runner_config[].orchestration`, where exactly one typed provider block must be non-null.
- `orchestration.webhook.queue_selection_strategy`: Queue-selection strategy when multiple runner configurations match a job equally well. The default is `first`, which deterministically selects the first matching queue by priority. `random` spreads jobs across equally matched queues. `all` dispatches to every matching queue, favoring startup speed at the cost of multiple runner launches and registrations for one job.
- `orchestration.webhook.eventbridge.enable`: Routes accepted webhook events through EventBridge when true. The default is `true`, and the value must be known during planning because it selects the webhook implementation.
- `orchestration.webhook.eventbridge.accept_events`: EventBridge event types accepted by the shared webhook. The default is `[]`, which accepts all supported events.
- `orchestration.webhook.matcher_config_parameter_store_tier`: Parameter Store tier for the shared matcher configuration. The default is `Standard`; valid values are `Standard` and `Advanced`. The value must be known during planning because it determines the matcher-parameter chunks.
- `orchestration.webhook.github.repository_white_list`: Repository full names allowed to use the shared webhook. The default is `[]`, which disables repository filtering.
- `orchestration.webhook.runner.boot_time_in_minutes`: Default expected runner boot duration used by webhook scale-down and pool controls. The default is `5`.
- `orchestration.webhook.runner.ephemeral`: Registers webhook-orchestrated runners in ephemeral mode by default. The default is `false`.
- `orchestration.webhook.runner.jit_config_enabled`: Explicit default for just-in-time runner configuration. The default is null, which follows the resolved `ephemeral` mode.
- `orchestration.webhook.runner.maximum_count`: Default maximum number of runners managed by the webhook orchestration provider per runner configuration. The default is null; every webhook runner configuration must resolve this field globally or locally.
- `orchestration.webhook.lambda.artifact`: Shared runner-control-plane artifact used by webhook scale, pool, and job-retry components. Set at most one of `zip` or `s3`; when both are null, the packaged runner archive is used.
- `orchestration.webhook.lambda.artifact.zip`: Optional local path to the shared runner-control-plane Lambda archive. The default is null.
- `orchestration.webhook.lambda.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for runner-control-plane Lambdas, must be known during planning, and requires a non-null shared bucket and key.
- `orchestration.webhook.lambda.artifact.s3.key`: Object key of the shared runner-control-plane Lambda archive.
- `orchestration.webhook.lambda.artifact.s3.object_version`: Optional object version of the shared runner-control-plane Lambda archive. The default is null.
- `orchestration.webhook.lambda.scale.up.memory_size`: Scale-up Lambda memory in MB. The default is `512`.
- `orchestration.webhook.lambda.scale.up.timeout`: Scale-up Lambda timeout in seconds. The default is `30`.
- `orchestration.webhook.lambda.scale.up.reserved_concurrent_executions`: Reserved concurrency for scale-up. The default is `1`; use `-1` for unreserved concurrency.
- `orchestration.webhook.lambda.scale.up.job_queued_check_enabled`: Enables queued-job verification before scaling. The default is null, which follows the resolved runner mode.
- `orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size`: Maximum build-queue records delivered per scale-up invocation. The default is `10`.
- `orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds`: Maximum build-queue batching window. The default is `0`.
- `orchestration.webhook.lambda.scale.up.tags`: Default tags for scale-up resources. The default is `{}`.
- `orchestration.webhook.lambda.scale.down.memory_size`: Scale-down Lambda memory in MB. The default is `512`.
- `orchestration.webhook.lambda.scale.down.timeout`: Scale-down Lambda timeout in seconds. The default is `60`.
- `orchestration.webhook.lambda.scale.down.schedule_expression`: EventBridge schedule for scale-down. The default is `cron(*/5 * * * ? *)`.
- `orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes`: Minimum runner age before scale-down may terminate it. The default is null, which selects the operating-system default.
- `orchestration.webhook.lambda.scale.down.idle_config`: Default time-based desired idle-runner configurations. The default is `[]`.
- `orchestration.webhook.lambda.scale.down.idle_config[].cron`: Cron expression identifying when the idle configuration applies.
- `orchestration.webhook.lambda.scale.down.idle_config[].timeZone`: IANA time zone used to evaluate the cron expression.
- `orchestration.webhook.lambda.scale.down.idle_config[].idleCount`: Number of idle runners retained during the matching period.
- `orchestration.webhook.lambda.scale.down.idle_config[].evictionStrategy`: Selection strategy used when excess idle runners are removed. The default is `oldest_first`.
- `orchestration.webhook.lambda.scale.down.tags`: Default tags for scale-down resources. The default is `{}`.
- `orchestration.webhook.lambda.webhook.artifact`: Shared-webhook artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used.
- `orchestration.webhook.lambda.webhook.artifact.zip`: Optional local path to the shared-webhook Lambda archive. The default is null.
- `orchestration.webhook.lambda.webhook.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for the webhook and requires a non-null shared bucket and key.
- `orchestration.webhook.lambda.webhook.artifact.s3.key`: Object key of the shared-webhook Lambda archive.
- `orchestration.webhook.lambda.webhook.artifact.s3.object_version`: Optional object version of the shared-webhook Lambda archive. The default is null.
- `orchestration.webhook.lambda.webhook.api_gateway_access_log_settings`: Optional API Gateway access-log destination and format for the shared webhook. The default is null, and wrapper presence must be known during planning because it controls the access-log block.
- `orchestration.webhook.lambda.webhook.api_gateway_access_log_settings.destination_arn`: CloudWatch Logs destination ARN for API Gateway access logs.
- `orchestration.webhook.lambda.webhook.api_gateway_access_log_settings.format`: API Gateway access-log format.
- `orchestration.webhook.lambda.webhook.memory_size`: Shared-webhook Lambda memory in MB. The default is `256`.
- `orchestration.webhook.lambda.webhook.timeout`: Shared-webhook Lambda timeout in seconds. The default is `10`.
- `orchestration.webhook.lambda.webhook.tags`: Additional tags for the shared webhook Lambda, merged after `lambda.tags`. The default is `{}`.
- `orchestration.webhook.lambda.pool.memory_size`: Pool Lambda memory in MB. The default is `512`.
- `orchestration.webhook.lambda.pool.timeout`: Pool Lambda timeout in seconds. The default is `60`.
- `orchestration.webhook.lambda.pool.reserved_concurrent_executions`: Reserved concurrency for the pool Lambda. The default is `1`; use `-1` for unreserved concurrency.
- `orchestration.webhook.lambda.pool.config`: Default scheduled target pool sizes. The default is `[]`, which disables the pool component.
- `orchestration.webhook.lambda.pool.config[].schedule_expression`: Scheduler expression that activates the target size.
- `orchestration.webhook.lambda.pool.config[].schedule_expression_timezone`: Optional IANA time zone used to evaluate the schedule.
- `orchestration.webhook.lambda.pool.config[].size`: Desired runner-pool size for the schedule.
- `orchestration.webhook.lambda.pool.include_busy_runners`: Includes busy runners when reconciling scheduled pool capacity. The default is `false`.
- `orchestration.webhook.lambda.pool.runner_owner`: Optional GitHub organization or repository owner used for pooled runners. The default is null.
- `orchestration.webhook.lambda.pool.tags`: Default tags for pool resources. The default is `{}`.
- `orchestration.webhook.queue.delay_webhook_event`: Default delay in seconds applied to accepted webhook jobs. The default is `30`.
- `orchestration.webhook.queue.job_queue_retention_in_seconds`: Default build-queue message retention period in seconds. The default is `86400`.
- `orchestration.webhook.queue.visibility_timeout_seconds`: Default build-queue visibility timeout. The default is `180`; set it to at least six times every resolved `orchestration.webhook.lambda.scale.up.timeout` that inherits it.
- `orchestration.webhook.queue.redrive_build_queue.enabled`: Creates and attaches a dead-letter queue to every v2 build queue by default. The default is `false`.
- `orchestration.webhook.queue.redrive_build_queue.maxReceiveCount`: Default number of receives before a message moves to the dead-letter queue. The default is null while redrive is disabled and must resolve to a value greater than zero when redrive is enabled.
- `orchestration.webhook.queue.tags`: Default tags for v2 build queues and dead-letter queues. The default is `{}`.
- `orchestration.webhook.queue.encryption`: Global at-rest encryption configuration for the multi-runner build queues and their dead-letter queues. It does not configure runner-config job-retry queues. Omitting the whole block selects SQS-managed encryption and defaults the two KMS attributes to null. When supplying the block explicitly, provide all three leaf attributes and use null for the inactive mode.
- `orchestration.webhook.queue.encryption.kms_data_key_reuse_period_seconds`: KMS data-key reuse period in seconds. This key is required syntactically in an explicit `queue.encryption` object but may be null; it is used only with `kms_master_key_id`.
- `orchestration.webhook.queue.encryption.kms_master_key_id`: KMS key ARN used for queue encryption. This AWS-facing field name is retained for compatibility, but non-null values must be key ARNs because runner-config IAM policies cannot use key IDs or aliases as resources. The field is required syntactically in an explicit `queue.encryption` object but may be null, and a computed ARN may remain unknown until apply. It is independent from `ssm.kms_key_id` and is forwarded separately to each webhook runner configuration so runner-config scale-up and job-retry roles receive only the build-queue KMS permissions they require.
- `orchestration.webhook.queue.encryption.sqs_managed_sse_enabled`: Selects the non-KMS mode: `true` enables SQS-managed encryption and `false` explicitly disables queue encryption. This key is required syntactically in an explicit `queue.encryption` object and must be null when `kms_master_key_id` is set. Omitting the whole encryption block defaults it to `true`.
- `ssm.paths.root`: Base Parameter Store path for shared GitHub App and webhook parameters and for all v2 runner configurations. The schema default is null, which derives `/github-action-runners/`; normalization appends the configuration key only for configuration-owned paths.
- `ssm.paths.app`: Shared GitHub App credential path segment below `ssm.paths.root`. The default is `app`.
- `ssm.paths.webhook`: Shared webhook matcher-configuration path segment below `ssm.paths.root`. The default is `webhook`.
- `ssm.paths.tokens`: Runner registration-token and JIT-configuration path segment below each runner-configuration root. The default is `runners/tokens`.
- `ssm.paths.config`: Persistent runner-configuration path segment below each runner-configuration root. The default is `runners/config`.
- `ssm.kms_key_id`: Optional global KMS key ARN that encrypts shared GitHub App parameters, configures the webhook and termination watcher, and adds matching decrypt permissions to every v2 runner configuration. The default is null and its value may be unknown until apply. It does not select encryption for runtime-created runner-configuration parameters.
- `ssm.tags`: Default tags for the shared GitHub App Parameter Store module and runner-configuration-owned SSM resources. The default is `{}`.
- `ssm.parameters.tags`: Default tags for Terraform-managed and runtime-created runner-configuration parameters. The default is `{}`.
- `ssm.housekeeper.schedule_expression`: Default EventBridge schedule for each runner-configuration SSM housekeeper. The default is `rate(1 day)`.
- `ssm.housekeeper.state`: Default EventBridge rule state for each runner-configuration SSM housekeeper. The default is `ENABLED`.
- `ssm.housekeeper.tags`: Default tags for SSM housekeeper resources. The default is `{}`.
- `ssm.housekeeper.lambda.artifact`: Default SSM-housekeeper artifact selection. Set at most one of `zip` or `s3`; when both are null, runner-config uses its packaged runner control-plane archive.
- `ssm.housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive. The default is null.
- `ssm.housekeeper.lambda.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for the SSM housekeeper, must be known during planning, and requires a non-null shared bucket and key.
- `ssm.housekeeper.lambda.artifact.s3.key`: Object key of the SSM-housekeeper Lambda archive.
- `ssm.housekeeper.lambda.artifact.s3.object_version`: Optional object version of the SSM-housekeeper Lambda archive. The default is null.
- `ssm.housekeeper.lambda.memory_size`: Default SSM housekeeper Lambda memory in MB. The default is `512`.
- `ssm.housekeeper.lambda.timeout`: Default SSM housekeeper Lambda timeout in seconds. The default is `60`.
- `ssm.housekeeper.config.tokenPath`: Optional cleanup path shared by every runner configuration. The default is null; omit it so each runner configuration derives its isolated token path.
- `ssm.housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed. The default is `1`.
- `ssm.housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true. The default is `false`.
- `observability.logs.level`: Application log level for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `info`.
- `observability.logs.retention_in_days`: CloudWatch Logs retention for v2 runner-config resources and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `180`.
- `observability.logs.kms_key_id`: Optional KMS key ID or ARN for v2 runner-config log groups and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is null.
- `observability.logs.class`: CloudWatch log-group class for v2 runner-config resources and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `STANDARD`.
- `observability.logs.tags`: Default tags for v2 runner-config log groups. The default is `{}`; shared singleton functions receive `tags` and `lambda.tags` instead.
- `observability.tracing.mode`: Optional Lambda tracing mode for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is null; its nullness must be known during planning because it controls X-Ray IAM and tracing blocks.
- `observability.tracing.capture_http_requests`: Enables HTTP request capture in the tracing helper for v2 runner-config functions and translated shared consumers. The default is `false`.
- `observability.tracing.capture_error`: Enables error capture in the tracing helper for v2 runner-config functions and translated shared consumers. The default is `false`.
- `observability.metrics.enable`: Enables module-emitted metrics for v2 runner configurations and the shared termination watcher. The default is `false`.
- `observability.metrics.namespace`: CloudWatch namespace for v2 runner-config and termination-watcher metrics. The default is `GitHub Runners`.
- `observability.metrics.metric.enable_github_app_rate_limit`: Emits GitHub App rate-limit metrics when metrics are enabled. The default is `true`.
- `observability.metrics.metric.enable_job_retry`: Emits job-retry metrics when metrics are enabled. The default is `true`.
- `observability.metrics.metric.enable_spot_termination`: Emits Spot termination metrics from the shared termination watcher when metrics are enabled. The default is `true`.
- `observability.metrics.metric.enable_spot_termination_warning`: Emits Spot termination-warning metrics from the shared termination watcher when metrics are enabled. The default is `true`.
- `compute_provider.ec2.vpc_id`: Shared VPC default for v2 EC2 runner configurations. The default is null; every EC2 runner configuration must resolve this field globally or locally.
- `compute_provider.ec2.subnet_ids`: Shared subnet default for v2 EC2 runner configurations. The default is null; every EC2 runner configuration must resolve this field globally or locally.
- `compute_provider.ec2.managed_security_group_enabled`: Creates the module-managed runner security group by default. The default is `true`.
- `compute_provider.ec2.egress_rules`: Shared runner security-group egress rules. The default is one IPv4/IPv6 allow-all rule; v2 does not inherit flat `runner_egress_rules`.
- `compute_provider.ec2.egress_rules[].cidr_blocks`: IPv4 CIDR destinations for an egress rule.
- `compute_provider.ec2.egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations for an egress rule.
- `compute_provider.ec2.egress_rules[].prefix_list_ids`: Prefix-list destinations for an egress rule.
- `compute_provider.ec2.egress_rules[].from_port`: Start of the egress rule port range.
- `compute_provider.ec2.egress_rules[].protocol`: Egress rule protocol; `-1` allows every protocol.
- `compute_provider.ec2.egress_rules[].security_groups`: Destination security-group IDs for an egress rule.
- `compute_provider.ec2.egress_rules[].self`: Allows traffic to the managed security group itself when true.
- `compute_provider.ec2.egress_rules[].to_port`: End of the egress rule port range.
- `compute_provider.ec2.egress_rules[].description`: Optional egress rule description.
- `compute_provider.ec2.additional_security_group_ids`: Existing security groups attached to every v2 EC2 runner configuration unless overridden. The default is `[]`.
- `compute_provider.ec2.cloudwatch_agent.config`: Optional complete CloudWatch agent configuration inherited by v2 EC2 runner configurations. The default is null; enablement remains configuration-owned.
- `compute_provider.ec2.instance_profile_path`: IAM path for module-managed EC2 instance profiles. The default is null.
- `compute_provider.ec2.key_name`: Optional EC2 key-pair name inherited by v2 EC2 runner configurations. The default is null.
- `compute_provider.ec2.associate_public_ipv4_address`: Associates public IPv4 addresses with v2 EC2 runners unless overridden. The default is `false`.
- `compute_provider.ec2.tags`: Default tags for runtime EC2 resources. The default is `{}` and runner-configuration EC2 tags take precedence.
- `compute_provider.ec2.ami.housekeeper`: Global configuration for the shared AMI-housekeeper Lambda.
- `compute_provider.ec2.ami.housekeeper.enabled`: Creates the shared AMI housekeeper when true. The default is `false`, and the value must be known during planning because it controls the module instance.
- `compute_provider.ec2.ami.housekeeper.cleanup_config`: AMI cleanup selection and safety settings. The default is `{}`, which resolves the leaf defaults described below in the AMI-housekeeper module.
- `compute_provider.ec2.ami.housekeeper.cleanup_config.maxItems`: Optional maximum number of AMIs queried for cleanup. The default is null, which applies no maximum.
- `compute_provider.ec2.ami.housekeeper.cleanup_config.minimumDaysOld`: Minimum AMI age in days before cleanup. The effective default is `30`.
- `compute_provider.ec2.ami.housekeeper.cleanup_config.amiFilters`: AMI filters, each containing `Name` and `Values`. The effective default selects images with `state = available` and `image-type = machine`.
- `compute_provider.ec2.ami.housekeeper.cleanup_config.launchTemplateNames`: Optional launch-template names whose referenced AMIs are retained. The default is null, which selects no launch templates.
- `compute_provider.ec2.ami.housekeeper.cleanup_config.ssmParameterNames`: Optional Parameter Store names whose referenced AMIs are retained. The default is null, which selects no parameters.
- `compute_provider.ec2.ami.housekeeper.cleanup_config.dryRun`: Reports eligible AMIs without deregistering them when true. The effective default is `false`.
- `compute_provider.ec2.ami.housekeeper.artifact`: AMI-housekeeper artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used.
- `compute_provider.ec2.ami.housekeeper.artifact.zip`: Optional local path to the AMI-housekeeper Lambda archive. The default is null.
- `compute_provider.ec2.ami.housekeeper.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 and requires a non-null shared bucket and key.
- `compute_provider.ec2.ami.housekeeper.artifact.s3.key`: Object key of the AMI-housekeeper Lambda archive.
- `compute_provider.ec2.ami.housekeeper.artifact.s3.object_version`: Optional object version of the AMI-housekeeper Lambda archive. The default is null.
- `compute_provider.ec2.ami.housekeeper.lambda.memory_size`: AMI-housekeeper Lambda memory in MB. The default is `256`.
- `compute_provider.ec2.ami.housekeeper.lambda.timeout`: AMI-housekeeper Lambda timeout in seconds. The default is `300`.
- `compute_provider.ec2.ami.housekeeper.schedule.expression`: AMI-housekeeper EventBridge schedule expression. The default is `cron(11 7 * * ? *)`.
- `compute_provider.ec2.instance_termination_watcher`: Global configuration for the shared EC2 instance-termination watcher.
- `compute_provider.ec2.instance_termination_watcher.enabled`: Creates the shared EC2 termination watcher when true. The default is `false`, and the value must be known during planning because it controls the module instance.
- `compute_provider.ec2.instance_termination_watcher.features.enable_spot_termination_handler`: Enables the Spot termination-event handler. The default is `true`, and the value must be known during planning because it controls child resources.
- `compute_provider.ec2.instance_termination_watcher.features.enable_spot_termination_notification_watcher`: Enables the Spot interruption-warning watcher. The default is `true`, and the value must be known during planning because it controls child resources.
- `compute_provider.ec2.instance_termination_watcher.enable_runner_deregistration`: Deregisters terminated runners from GitHub when true. The default is `true`, and the value must be known during planning because it controls deregistration resources.
- `compute_provider.ec2.instance_termination_watcher.environment_variables`: Additional termination-watcher Lambda environment variables. The default is `{}`.
- `compute_provider.ec2.instance_termination_watcher.artifact`: Termination-watcher artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used.
- `compute_provider.ec2.instance_termination_watcher.artifact.zip`: Optional local path to the termination-watcher Lambda archive. The default is null.
- `compute_provider.ec2.instance_termination_watcher.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 and requires a non-null shared bucket and key.
- `compute_provider.ec2.instance_termination_watcher.artifact.s3.key`: Object key of the termination-watcher Lambda archive.
- `compute_provider.ec2.instance_termination_watcher.artifact.s3.object_version`: Optional object version of the termination-watcher Lambda archive. The default is null.
- `compute_provider.ec2.instance_termination_watcher.lambda.memory_size`: Optional watcher Lambda memory in MB. The default is null, which delegates to the termination-watcher module.
- `compute_provider.ec2.instance_termination_watcher.lambda.timeout`: Optional watcher Lambda timeout in seconds. The default is null, which delegates to the termination-watcher module.
- `compute_provider.ec2.runner_binaries`: Global configuration for the shared runner-distribution buckets and syncers, created once per unique enabled runner operating-system and architecture pair.
- `compute_provider.ec2.runner_binaries.enabled`: Default for whether EC2 runner configurations use the synchronized runner distribution. The default is `true`; a runner configuration may override it through `compute_provider.ec2.binaries_syncer.enabled`. Every resolved enable value must be known during planning because it determines the syncer module instances.
- `compute_provider.ec2.runner_binaries.s3`: Settings for each shared runner-distribution bucket.
- `compute_provider.ec2.runner_binaries.s3.encryption`: Server-side encryption settings for each distribution bucket.
- `compute_provider.ec2.runner_binaries.s3.encryption.enabled`: Creates an explicit distribution-bucket encryption configuration when true. The default is `true`, and the value must be known during planning because it controls resource shape. Keep `kms_master_key_id` null when this is false.
- `compute_provider.ec2.runner_binaries.s3.encryption.bucket_key_enabled`: Optional S3 Bucket Key setting. The default is null.
- `compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm`: Server-side encryption algorithm. The default is `AES256`; valid values are `AES256`, `aws:kms`, and `aws:kms:dsse`. When `kms_master_key_id` is set, use one of the KMS algorithms.
- `compute_provider.ec2.runner_binaries.s3.encryption.kms_master_key_id`: Optional KMS key identifier for the distribution bucket. The default is null, and its nullness must be known during planning because it controls the syncer KMS policy. The syncer receives KMS access, but runner roles do not derive `kms:Decrypt` from this field; grant runner roles decrypt access separately when using a CMK.
- `compute_provider.ec2.runner_binaries.s3.tags`: Additional tags for each distribution bucket. The default is `{}`; these merge after global `tags`.
- `compute_provider.ec2.runner_binaries.s3.versioning`: Distribution-bucket versioning state. The default is `Disabled`; valid values are `Disabled`, `Enabled`, and `Suspended`. After enabling versioning, Terraform cannot return the bucket to `Disabled`; use `Suspended` instead.
- `compute_provider.ec2.runner_binaries.s3.logging`: Optional access-logging settings for each distribution bucket.
- `compute_provider.ec2.runner_binaries.s3.logging.bucket`: Existing target bucket for access logs. The default is null, and its nullness must be known during planning because it controls the logging resource.
- `compute_provider.ec2.runner_binaries.s3.logging.prefix`: Optional access-log prefix. The default is null, which uses the distribution-bucket name when logging is enabled. A non-null prefix requires `logging.bucket`.
- `compute_provider.ec2.runner_binaries.syncer`: Component-specific settings for the shared runner-binary syncer Lambda.
- `compute_provider.ec2.runner_binaries.syncer.artifact`: Syncer Lambda artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used.
- `compute_provider.ec2.runner_binaries.syncer.artifact.zip`: Optional local path to the syncer Lambda archive. The default is null.
- `compute_provider.ec2.runner_binaries.syncer.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 and requires a non-null shared bucket and key.
- `compute_provider.ec2.runner_binaries.syncer.artifact.s3.key`: Object key of the syncer Lambda archive. Required when the `s3` wrapper is present.
- `compute_provider.ec2.runner_binaries.syncer.artifact.s3.object_version`: Optional object version of the syncer Lambda archive. The default is null.
- `compute_provider.ec2.runner_binaries.syncer.lambda`: Syncer Lambda sizing settings. Runtime, architecture, networking, role, tags, logging, and tracing come from their global experimental blocks.
- `compute_provider.ec2.runner_binaries.syncer.lambda.memory_size`: Memory allocated to the syncer Lambda in MB. The default is `256`.
- `compute_provider.ec2.runner_binaries.syncer.lambda.timeout`: Syncer Lambda timeout in seconds. The default is `300`.
- `compute_provider.ec2.runner_binaries.syncer.schedule`: EventBridge schedule settings for the syncer Lambda.
- `compute_provider.ec2.runner_binaries.syncer.schedule.expression`: EventBridge schedule expression. The default is `cron(27 * * * ? *)`.
- `compute_provider.ec2.runner_binaries.syncer.schedule.state`: EventBridge rule state. The default is `ENABLED`; valid values are `DISABLED`, `ENABLED`, and `ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS`.

Each `experimental.multi_runner_config` entry supports the following nested fields:

- `multi_runner_config[].tags`: Configuration-wide tags. These override global `experimental.tags`; narrower component and compute-provider tag maps take precedence for their resources. Flat `tags` are not merged into v2 queues or runner configurations.
- `multi_runner_config[].runner.os`: Runner operating system.
- `multi_runner_config[].runner.architecture`: Runner distribution architecture.
- `multi_runner_config[].runner.disable_default_labels`: Prevents GitHub default labels from being registered.
- `multi_runner_config[].runner.extra_labels`: Additional labels combined with `orchestration.webhook.matcherConfig.labelMatchers` for webhook runner configurations. Default self-hosted, operating-system, and architecture labels are also included unless `runner.disable_default_labels` is true.
- `multi_runner_config[].runner.group_name`: GitHub runner group used during registration.
- `multi_runner_config[].runner.name_prefix`: Prefix added to registered runner names.
- `multi_runner_config[].runner.run_as_root`: Runs the runner service as root when supported by the compute provider.
- `multi_runner_config[].runner.run_as`: Operating-system user used when `run_as_root` is false.
- `multi_runner_config[].runner.auto_update_disabled`: Disables the GitHub runner application's built-in updater.
- `multi_runner_config[].runner.tags`: Tags for common runner resources, currently the managed runner IAM role. These override entry-level `tags`.
- `multi_runner_config[].runner.hooks.job_started`: Script content installed as the runner job-started hook.
- `multi_runner_config[].runner.hooks.job_completed`: Script content installed as the runner job-completed hook.
- `multi_runner_config[].runner.iam.role`: Optional externally managed runner-role wrapper. When set, inherited managed policies and trust additions are suppressed.
- `multi_runner_config[].runner.iam.role.arn`: ARN of an externally managed runner role. When set, `runner-config` does not create or modify that role.
- `multi_runner_config[].runner.iam.managed_policy_arns`: Named managed-policy ARNs attached to the module-managed runner role. Keep this empty or null when the runner configuration selects an external `runner.iam.role`.
- `multi_runner_config[].runner.iam.additional_trust_policy_json`: Optional IAM policy document merged with the selected compute provider's default runner-role trust policy. Keep it null when the runner configuration selects an external `runner.iam.role`.
- `multi_runner_config[].runner.iam.path`: IAM path for the module-managed runner role.
- `multi_runner_config[].runner.iam.permissions_boundary`: Permissions-boundary ARN for the module-managed runner role.
- `multi_runner_config[].lambda`: Lambda runtime, architecture, networking, tags, and role substrate shared by orchestration and the runner-configuration SSM housekeeper. Scale function settings belong under `orchestration.webhook.lambda`.
- `multi_runner_config[].lambda.runtime`: Per-configuration runtime override for runner-config Lambda functions.
- `multi_runner_config[].lambda.architecture`: Per-configuration architecture override for runner-config Lambda functions.
- `multi_runner_config[].lambda.subnet_ids`: Per-configuration subnet override for runner-config Lambda functions.
- `multi_runner_config[].lambda.security_group_ids`: Per-configuration security-group override for runner-config Lambda functions.
- `multi_runner_config[].lambda.tags`: Per-configuration tags for control-plane Lambda functions. Component tags override this map.
- `multi_runner_config[].lambda.role.path`: Per-configuration IAM path for module-managed Lambda roles. Null inherits `experimental.lambda.role.path`, then `experimental.roles.path`.
- `multi_runner_config[].lambda.role.permissions_boundary`: Per-configuration permissions-boundary ARN for module-managed Lambda roles. Null inherits `experimental.lambda.role.permissions_boundary`, then `experimental.roles.permissions_boundary`.
- `multi_runner_config[].orchestration`: Demand-controller selection. Exactly one typed provider block must be non-null. Only `webhook` is supported today; additional providers can be added without moving the webhook contract.
- `multi_runner_config[].orchestration.webhook`: Selects the workflow-job webhook control plane, including its SQS build queue, scale-up, scheduled scale-down/pool, and optional job-retry resources.
- `multi_runner_config[].orchestration.webhook.runner.boot_time_in_minutes`: Expected runner boot duration used by webhook scale-down and pool controls. Null inherits `experimental.orchestration.webhook.runner.boot_time_in_minutes`.
- `multi_runner_config[].orchestration.webhook.runner.ephemeral`: Registers webhook-orchestrated runners in ephemeral mode. Null inherits `experimental.orchestration.webhook.runner.ephemeral`.
- `multi_runner_config[].orchestration.webhook.runner.jit_config_enabled`: Explicitly enables or disables just-in-time configuration. Null inherits the global webhook value; if both are null, behavior follows the resolved webhook `ephemeral` mode.
- `multi_runner_config[].orchestration.webhook.runner.maximum_count`: Maximum number of runners managed by the webhook orchestration provider for this configuration. Null inherits `experimental.orchestration.webhook.runner.maximum_count`.
- `multi_runner_config[].orchestration.webhook.github.organization_runners`: Registers runners at organization scope when true; otherwise repository-scoped registration is used.
- `multi_runner_config[].orchestration.webhook.matcherConfig.labelMatchers`: Groups of labels used to match webhook jobs to this configuration.
- `multi_runner_config[].orchestration.webhook.matcherConfig.exactMatch`: Deprecated one-way match. When true, every workflow-job label must appear in a configured label group, but that group may contain additional labels.
- `multi_runner_config[].orchestration.webhook.matcherConfig.bidirectionalLabelMatch`: Requires an exact two-way set match between workflow-job labels and a configured label group, with no extra or missing labels.
- `multi_runner_config[].orchestration.webhook.matcherConfig.priority`: Ordering used when multiple configurations match the same job.
- `multi_runner_config[].orchestration.webhook.matcherConfig.enableDynamicLabels`: Enables runtime interpretation of supported dynamic AWS labels.
- `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy`: Optional policy restricting values accepted from dynamic AWS labels.
- `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.blocked_keys`: Dynamic-label keys rejected for this runner configuration. The default is `[]`.
- `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys`: Per-key allow, deny, and maximum-value restrictions. The default is `{}`.
- `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys..allowed`: Values explicitly allowed for the dynamic-label key. The default is `[]`.
- `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys..denied`: Values explicitly denied for the dynamic-label key. The default is `[]`.
- `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys..max`: Optional maximum accepted value for the dynamic-label key. The default is null.
- `multi_runner_config[].orchestration.webhook.queue.delay_webhook_event`: Delay in seconds applied to webhook job messages. Null inherits the global queue default.
- `multi_runner_config[].orchestration.webhook.queue.job_queue_retention_in_seconds`: Build-queue message retention period in seconds. Null inherits the global queue default.
- `multi_runner_config[].orchestration.webhook.queue.visibility_timeout_seconds`: Build-queue visibility timeout. Null inherits the global queue default; the resolved value must be at least six times the resolved `orchestration.webhook.lambda.scale.up.timeout` so Lambda has enough time to retry throttled invocations.
- `multi_runner_config[].orchestration.webhook.queue.redrive_build_queue.enabled`: Creates and attaches a dead-letter queue for the build queue. A null wrapper or null leaf inherits the corresponding global value.
- `multi_runner_config[].orchestration.webhook.queue.redrive_build_queue.maxReceiveCount`: Number of receives before a build message moves to the dead-letter queue. A null wrapper or null leaf inherits the corresponding global value, and the resolved value must be greater than zero when redrive is enabled.
- `multi_runner_config[].orchestration.webhook.queue.tags`: Tags for configuration-owned queue resources. These merge after global queue tags and entry-level `tags`; component tags override this map.
- `multi_runner_config[].orchestration.webhook.lambda.scale.up.memory_size`: Memory allocated to the scale-up Lambda in MB.
- `multi_runner_config[].orchestration.webhook.lambda.scale.up.timeout`: Scale-up Lambda timeout in seconds.
- `multi_runner_config[].orchestration.webhook.lambda.scale.up.reserved_concurrent_executions`: Reserved concurrency for the scale-up Lambda. Use `-1` for unreserved concurrency.
- `multi_runner_config[].orchestration.webhook.lambda.scale.up.job_queued_check_enabled`: Enables the queued-job verification before scaling. Null inherits the global value; if both are null, behavior follows the resolved runner mode.
- `multi_runner_config[].orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size`: Maximum build-queue records delivered to one scale-up Lambda invocation.
- `multi_runner_config[].orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds`: Maximum batching window for build-queue records.
- `multi_runner_config[].orchestration.webhook.lambda.scale.up.tags`: Tags for scale-up resources. These override entry-level and shared Lambda, queue, and log-group tags within their resource scopes.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.memory_size`: Memory allocated to the scale-down Lambda in MB.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.timeout`: Scale-down Lambda timeout in seconds.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.schedule_expression`: EventBridge schedule expression that invokes scale-down.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes`: Minimum runner age before scale-down may terminate it. Null inherits the global value; if both are null, the operating-system default is selected.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config`: Time-based desired idle-runner configurations.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].cron`: Cron expression identifying when the idle configuration applies.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].timeZone`: IANA time zone used to evaluate `cron`.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].idleCount`: Number of idle runners to retain during the matching period.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].evictionStrategy`: Selection strategy used when excess idle runners are removed.
- `multi_runner_config[].orchestration.webhook.lambda.scale.down.tags`: Tags for scale-down resources. These override entry-level and shared Lambda and log-group tags within their resource scopes.
- `multi_runner_config[].orchestration.webhook.lambda.pool.memory_size`: Memory allocated to the pool Lambda in MB.
- `multi_runner_config[].orchestration.webhook.lambda.pool.timeout`: Pool Lambda timeout in seconds.
- `multi_runner_config[].orchestration.webhook.lambda.pool.reserved_concurrent_executions`: Reserved concurrency for the pool Lambda. Use `-1` for unreserved concurrency.
- `multi_runner_config[].orchestration.webhook.lambda.pool.config`: Scheduled target pool sizes. An empty list disables the pool component.
- `multi_runner_config[].orchestration.webhook.lambda.pool.config[].schedule_expression`: Scheduler expression that activates the target size.
- `multi_runner_config[].orchestration.webhook.lambda.pool.config[].schedule_expression_timezone`: Optional IANA time zone used to evaluate the schedule.
- `multi_runner_config[].orchestration.webhook.lambda.pool.config[].size`: Desired number of runners for the schedule.
- `multi_runner_config[].orchestration.webhook.lambda.pool.include_busy_runners`: Includes busy runners when reconciling scheduled pool capacity.
- `multi_runner_config[].orchestration.webhook.lambda.pool.runner_owner`: Optional GitHub organization or repository owner used when creating pooled runners.
- `multi_runner_config[].orchestration.webhook.lambda.pool.tags`: Tags for pool resources. These override entry-level and shared Lambda and log-group tags within their resource scopes.
- `multi_runner_config[].orchestration.webhook.job_retry.enabled`: Creates the retry queue, Lambda function, event-source mapping, and related IAM resources.
- `multi_runner_config[].orchestration.webhook.job_retry.delay_in_seconds`: Initial delay before a queued-job retry check.
- `multi_runner_config[].orchestration.webhook.job_retry.delay_backoff`: Multiplier applied to the delay after each unsuccessful check.
- `multi_runner_config[].orchestration.webhook.job_retry.max_attempts`: Maximum retry-check attempts before the message is no longer republished.
- `multi_runner_config[].orchestration.webhook.job_retry.tags`: Tags for job-retry resources. These override entry-level and shared Lambda, queue, and log-group tags within their resource scopes.
- `multi_runner_config[].orchestration.webhook.job_retry.lambda.memory_size`: Memory allocated to the job-retry Lambda in MB.
- `multi_runner_config[].orchestration.webhook.job_retry.lambda.reserved_concurrent_executions`: Reserved concurrency for the job-retry Lambda. Use `-1` for unreserved concurrency.
- `multi_runner_config[].orchestration.webhook.job_retry.lambda.timeout`: Job-retry Lambda timeout in seconds and visibility timeout for its retry queue.
- `multi_runner_config[].ssm.paths.root`: Base Parameter Store root for this runner configuration. The configuration key is always appended to preserve configuration isolation. The omitted global root derives `/github-action-runners/`.
- `multi_runner_config[].ssm.paths.tokens`: Path segment below the runner-configuration root used for runner registration tokens and just-in-time configuration.
- `multi_runner_config[].ssm.paths.config`: Path segment below the runner-configuration root used for persistent runner configuration.
- `multi_runner_config[].ssm.tags`: Shared tags for runner-configuration-owned SSM resources. These override entry-level `tags`.
- `multi_runner_config[].ssm.parameters.tags`: Tags for Terraform-managed and runtime-created runner configuration parameters. These override `ssm.tags`.
- `multi_runner_config[].ssm.housekeeper.schedule_expression`: EventBridge schedule expression that invokes the runner-configuration SSM housekeeper.
- `multi_runner_config[].ssm.housekeeper.state`: EventBridge rule state for the runner-configuration SSM housekeeper. Valid values are `DISABLED`, `ENABLED`, and `ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS`.
- `multi_runner_config[].ssm.housekeeper.tags`: Tags for SSM housekeeper resources. These override entry-level, shared Lambda, shared log, and `ssm.tags` values.
- `multi_runner_config[].ssm.housekeeper.lambda.artifact`: Per-configuration SSM-housekeeper artifact selection. A selected `zip` or `s3` source overrides the global `ssm.housekeeper.lambda.artifact`; when neither level selects a source, runner-config uses its packaged runner control-plane archive.
- `multi_runner_config[].ssm.housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive.
- `multi_runner_config[].ssm.housekeeper.lambda.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for this SSM housekeeper, must be known during planning, and requires a non-null shared bucket and key.
- `multi_runner_config[].ssm.housekeeper.lambda.artifact.s3.key`: Object key of this runner configuration's SSM-housekeeper Lambda archive.
- `multi_runner_config[].ssm.housekeeper.lambda.artifact.s3.object_version`: Optional object version of this runner configuration's SSM-housekeeper Lambda archive.
- `multi_runner_config[].ssm.housekeeper.lambda.memory_size`: Memory allocated to the SSM housekeeper Lambda in MB.
- `multi_runner_config[].ssm.housekeeper.lambda.timeout`: SSM housekeeper Lambda timeout in seconds.
- `multi_runner_config[].ssm.housekeeper.config.tokenPath`: Optional cleanup path. A global value is shared by every runner configuration, so omit it to derive each configuration's isolated token path.
- `multi_runner_config[].ssm.housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed.
- `multi_runner_config[].ssm.housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true.
- `multi_runner_config[].observability.logs.level`: Application log level for runner-configuration control-plane functions.
- `multi_runner_config[].observability.logs.retention_in_days`: CloudWatch Logs retention period for runner-configuration resources.
- `multi_runner_config[].observability.logs.kms_key_id`: Optional KMS key ID or ARN used to encrypt runner-configuration CloudWatch log groups.
- `multi_runner_config[].observability.logs.class`: CloudWatch log-group class for runner-configuration resources.
- `multi_runner_config[].observability.logs.tags`: Shared tags for runner-configuration CloudWatch log groups. Component tags override this map.
- `multi_runner_config[].observability.tracing.mode`: Optional Lambda tracing mode. Its nullness must be known during planning because it controls X-Ray IAM and tracing blocks.
- `multi_runner_config[].observability.tracing.capture_http_requests`: Enables HTTP request capture in the tracing helper.
- `multi_runner_config[].observability.tracing.capture_error`: Enables error capture in the tracing helper.
- `multi_runner_config[].observability.metrics.enable`: Enables module-emitted metrics.
- `multi_runner_config[].observability.metrics.namespace`: CloudWatch namespace used for emitted metrics.
- `multi_runner_config[].observability.metrics.metric.enable_github_app_rate_limit`: Emits GitHub App rate-limit metrics.
- `multi_runner_config[].observability.metrics.metric.enable_job_retry`: Emits job-retry metrics.
- `multi_runner_config[].compute_provider`: Typed compute-provider blocks. Exactly one block must be non-null, and the populated block selects the provider. Its presence must be known during planning; values inside it may remain unknown until apply.
- `multi_runner_config[].compute_provider.ec2`: EC2-specific configuration.
- `multi_runner_config[].compute_provider.ec2.metadata_options.instance_metadata_tags`: Exposes instance tags through Instance Metadata Service when enabled.
- `multi_runner_config[].compute_provider.ec2.metadata_options.http_endpoint`: Enables or disables the Instance Metadata Service endpoint.
- `multi_runner_config[].compute_provider.ec2.metadata_options.http_tokens`: Controls whether IMDSv2 session tokens are optional or required.
- `multi_runner_config[].compute_provider.ec2.metadata_options.http_put_response_hop_limit`: Network hop limit for Instance Metadata Service token responses.
- `multi_runner_config[].compute_provider.ec2.ami.filter`: EC2 AMI filters combined with the default AMI-name filter.
- `multi_runner_config[].compute_provider.ec2.ami.owners`: AWS account IDs or aliases allowed to own the selected AMI.
- `multi_runner_config[].compute_provider.ec2.ami.id_ssm_parameter`: Optional externally managed SSM parameter containing the AMI ID. The wrapper's presence selects external ownership at plan time.
- `multi_runner_config[].compute_provider.ec2.ami.id_ssm_parameter.arn`: ARN of the externally managed SSM parameter. The ARN may be unknown until apply.
- `multi_runner_config[].compute_provider.ec2.ami.kms_key`: Optional KMS key required to launch encrypted AMIs or snapshots. The wrapper's presence selects the KMS policy at plan time.
- `multi_runner_config[].compute_provider.ec2.ami.kms_key.arn`: ARN of the KMS key. The ARN may be unknown until apply.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings`: EBS mappings added to the runner launch template.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].delete_on_termination`: Deletes the volume when its runner instance terminates.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].device_name`: Device name exposed to the runner instance.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].encrypted`: Enables EBS encryption.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].iops`: Provisioned IOPS for supported volume types.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].kms_key_id`: KMS key ID or ARN used to encrypt the volume.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].snapshot_id`: Snapshot used to initialize the volume.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].throughput`: Provisioned throughput for supported volume types.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].volume_initialization_rate`: Fixed initialization rate in MiB/s for supported snapshot-backed volumes.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].volume_size`: Volume size in GiB.
- `multi_runner_config[].compute_provider.ec2.block_device_mappings[].volume_type`: EBS volume type.
- `multi_runner_config[].compute_provider.ec2.create_service_linked_role_spot`: Allows scale-up to create the EC2 Spot service-linked role.
- `multi_runner_config[].compute_provider.ec2.credit_specification`: CPU credit mode for burstable instance types.
- `multi_runner_config[].compute_provider.ec2.ebs_optimized`: Requests EBS-optimized runner instances.
- `multi_runner_config[].compute_provider.ec2.cloudwatch_agent.enabled`: Installs and configures the CloudWatch agent through the default bootstrap flow.
- `multi_runner_config[].compute_provider.ec2.cloudwatch_agent.config`: Optional complete CloudWatch agent configuration.
- `multi_runner_config[].compute_provider.ec2.binaries_syncer.enabled`: Enables use of the shared synchronized runner distribution from S3. Null inherits `experimental.compute_provider.ec2.runner_binaries.enabled`.
- `multi_runner_config[].compute_provider.ec2.detailed_monitoring_enabled`: Enables detailed EC2 monitoring for runner instances.
- `multi_runner_config[].compute_provider.ec2.ssm_enabled`: Attaches runner permissions and policies required for AWS Systems Manager access.
- `multi_runner_config[].compute_provider.ec2.user_data.enabled`: Enables launch-template user data.
- `multi_runner_config[].compute_provider.ec2.user_data.template`: Optional path to a custom user-data template.
- `multi_runner_config[].compute_provider.ec2.user_data.content`: Optional complete user-data content used instead of rendering a template.
- `multi_runner_config[].compute_provider.ec2.user_data.pre_install`: Script content inserted before runner installation in the default template.
- `multi_runner_config[].compute_provider.ec2.user_data.post_install`: Script content inserted after runner installation in the default template.
- `multi_runner_config[].compute_provider.ec2.user_data.debug_logging_enabled`: Enables verbose user-data tracing, which can expose secrets in logs.
- `multi_runner_config[].compute_provider.ec2.instance_allocation_strategy`: EC2 Fleet allocation strategy used to select capacity.
- `multi_runner_config[].compute_provider.ec2.instance_max_spot_price`: Optional maximum hourly Spot price.
- `multi_runner_config[].compute_provider.ec2.instance_target_capacity_type`: Primary capacity type, either `spot` or `on-demand`.
- `multi_runner_config[].compute_provider.ec2.instance_type_priorities`: Optional numeric priorities keyed by instance type.
- `multi_runner_config[].compute_provider.ec2.instance_types`: EC2 instance types available to the scale-up and pool functions.
- `multi_runner_config[].compute_provider.ec2.additional_security_group_ids`: Existing security groups attached to runner instances.
- `multi_runner_config[].compute_provider.ec2.managed_security_group_enabled`: Creates the module-managed runner security group when true.
- `multi_runner_config[].compute_provider.ec2.egress_rules`: Runner security-group egress rules. Null inherits `experimental.compute_provider.ec2.egress_rules`, whose default is the built-in IPv4/IPv6 allow-all rule. Flat `runner_egress_rules` is not inherited by v2.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].cidr_blocks`: IPv4 CIDR destinations for the runner-configuration egress rule.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations for the runner-configuration egress rule.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].prefix_list_ids`: Prefix-list destinations for the runner-configuration egress rule.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].from_port`: Start of the runner-configuration egress rule port range.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].protocol`: Runner-configuration egress rule protocol; `-1` allows every protocol.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].security_groups`: Destination security-group IDs for the runner-configuration egress rule.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].self`: Allows traffic to the managed security group itself when true.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].to_port`: End of the runner-configuration egress rule port range.
- `multi_runner_config[].compute_provider.ec2.egress_rules[].description`: Optional runner-configuration egress rule description.
- `multi_runner_config[].compute_provider.ec2.instance_profile_path`: IAM path for the module-managed EC2 instance profile.
- `multi_runner_config[].compute_provider.ec2.key_name`: Optional EC2 key-pair name for runner instances.
- `multi_runner_config[].compute_provider.ec2.associate_public_ipv4_address`: Associates a public IPv4 address with runner instances.
- `multi_runner_config[].compute_provider.ec2.instance_profile.name`: Name of an externally managed instance profile. Setting it also requires `runner.iam.role`.
- `multi_runner_config[].compute_provider.ec2.enable_on_demand_failover_for_errors`: EC2 error codes that trigger an on-demand fallback after a Spot launch failure.
- `multi_runner_config[].compute_provider.ec2.scale_errors`: EC2 error codes treated as retryable scale-up failures.
- `multi_runner_config[].compute_provider.ec2.subnet_ids`: Subnets from which scale-up may launch runners. A null configuration value inherits the experimental global value.
- `multi_runner_config[].compute_provider.ec2.vpc_id`: VPC in which runner networking resources are created. A null configuration value inherits the experimental global value.
- `multi_runner_config[].compute_provider.ec2.cpu_options.core_count`: Number of CPU cores exposed to the runner instance.
- `multi_runner_config[].compute_provider.ec2.cpu_options.threads_per_core`: Number of hardware threads exposed per CPU core.
- `multi_runner_config[].compute_provider.ec2.cpu_options.amd_sev_snp`: Enables or disables AMD SEV-SNP on supported instance types.
- `multi_runner_config[].compute_provider.ec2.cpu_options.nested_virtualization`: Enables or disables nested virtualization on supported instance types.
- `multi_runner_config[].compute_provider.ec2.placement.affinity`: Host affinity setting.
- `multi_runner_config[].compute_provider.ec2.placement.availability_zone`: Availability Zone in which the instance is placed.
- `multi_runner_config[].compute_provider.ec2.placement.group_id`: Placement-group ID.
- `multi_runner_config[].compute_provider.ec2.placement.group_name`: Placement-group name.
- `multi_runner_config[].compute_provider.ec2.placement.host_id`: Dedicated Host ID.
- `multi_runner_config[].compute_provider.ec2.placement.host_resource_group_arn`: ARN of the host resource group used for placement.
- `multi_runner_config[].compute_provider.ec2.placement.spread_domain`: Spread-domain placement value.
- `multi_runner_config[].compute_provider.ec2.placement.tenancy`: Instance tenancy.
- `multi_runner_config[].compute_provider.ec2.placement.partition_number`: Placement-group partition number.
- `multi_runner_config[].compute_provider.ec2.license_specifications[].license_configuration_arn`: ARN of a License Manager license configuration.
- `multi_runner_config[].compute_provider.ec2.use_dedicated_host`: Enables the dedicated-host launch path required for macOS runners.
- `multi_runner_config[].compute_provider.ec2.log_files`: Optional log files collected by the CloudWatch agent.
- `multi_runner_config[].compute_provider.ec2.log_files[].log_group_name`: CloudWatch log-group name before optional prefixing.
- `multi_runner_config[].compute_provider.ec2.log_files[].prefix_log_group`: Prefixes the log-group name with the runner configuration path when true.
- `multi_runner_config[].compute_provider.ec2.log_files[].file_path`: File or glob read by the CloudWatch agent.
- `multi_runner_config[].compute_provider.ec2.log_files[].log_stream_name`: CloudWatch log-stream name template.
- `multi_runner_config[].compute_provider.ec2.log_files[].log_class`: CloudWatch log-group class for the collected file.
- `multi_runner_config[].compute_provider.ec2.tags`: Tags for runtime EC2 instances, volumes, network interfaces, and eligible Spot requests. These override entry-level tags and the generated runner `Name`; provider-required bootstrap tags take final precedence. |
object({
tags = optional(map(string), {})

roles = optional(object({
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})

runner = optional(object({
os = optional(string, null)
architecture = optional(string, null)
disable_default_labels = optional(bool, false)
extra_labels = optional(list(string), [])
group_name = optional(string, "Default")
name_prefix = optional(string, "")
run_as_root = optional(bool, false)
run_as = optional(string, "ec2-user")
auto_update_disabled = optional(bool, false)
tags = optional(map(string), {})
hooks = optional(object({
job_started = optional(string, "")
job_completed = optional(string, "")
}), {})
iam = optional(object({
role = optional(object({
arn = string
}), null)
managed_policy_arns = optional(map(string), {})
additional_trust_policy_json = optional(string, null)
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
}), {})

github = optional(object({
app = optional(object({
key_base64 = optional(string)
key_base64_ssm = optional(object({
arn = string
name = string
}))
id = optional(string)
id_ssm = optional(object({
arn = string
name = string
}))
webhook_secret = optional(string)
webhook_secret_ssm = optional(object({
arn = string
name = string
}))
}), null)
additional_apps = optional(list(object({
key_base64 = optional(string)
key_base64_ssm = optional(object({ arn = string, name = string }))
id = optional(string)
id_ssm = optional(object({ arn = string, name = string }))
installation_id = optional(string)
installation_id_ssm = optional(object({ arn = string, name = string }))
})), [])
enterprise_server = optional(object({
url = optional(string, null)
ssl_verify = optional(bool, true)
}), {})
user_agent = optional(string, "github-aws-runners")
}), {})

lambda = optional(object({
artifact = optional(object({
s3 = optional(object({
bucket = optional(string, null)
}), {})
}), {})
runtime = optional(string, "nodejs24.x")
architecture = optional(string, "arm64")
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
subnet_ids = optional(list(string), [])
security_group_ids = optional(list(string), [])
tags = optional(map(string), {})
role = optional(object({
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
}), {})

orchestration = optional(object({
webhook = optional(object({
queue_selection_strategy = optional(string, "first")
eventbridge = optional(object({
enable = optional(bool, true)
accept_events = optional(list(string), [])
}), {})
matcher_config_parameter_store_tier = optional(string, "Standard")
runner = optional(object({
boot_time_in_minutes = optional(number, 5)
ephemeral = optional(bool, false)
jit_config_enabled = optional(bool, null)
maximum_count = optional(number, null)
}), {})

github = optional(object({
repository_white_list = optional(list(string), [])
}), {})

lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
scale = optional(object({
up = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 30)
reserved_concurrent_executions = optional(number, 1)
job_queued_check_enabled = optional(bool, null)
event_source_mapping = optional(object({
batch_size = optional(number, 10)
maximum_batching_window_in_seconds = optional(number, 0)
}), {})
tags = optional(map(string), {})
}), {})
down = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
schedule_expression = optional(string, "cron(*/5 * * * ? *)")
minimum_running_time_in_minutes = optional(number, null)
idle_config = optional(list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = optional(string, "oldest_first")
})), [])
tags = optional(map(string), {})
}), {})
}), {})
webhook = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
api_gateway_access_log_settings = optional(object({
destination_arn = string
format = string
}), null)
memory_size = optional(number, 256)
timeout = optional(number, 10)
tags = optional(map(string), {})
}), {})
pool = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
reserved_concurrent_executions = optional(number, 1)
config = optional(list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
})), [])
include_busy_runners = optional(bool, false)
runner_owner = optional(string, null)
tags = optional(map(string), {})
}), {})
}), {})

queue = optional(object({
delay_webhook_event = optional(number, 30)
job_queue_retention_in_seconds = optional(number, 86400)
visibility_timeout_seconds = optional(number, 180)
redrive_build_queue = optional(object({
enabled = optional(bool, false)
maxReceiveCount = optional(number, null)
}), {
enabled = false
maxReceiveCount = null
})
tags = optional(map(string), {})
encryption = optional(object({
kms_data_key_reuse_period_seconds = number
kms_master_key_id = string
sqs_managed_sse_enabled = bool
}), {
kms_data_key_reuse_period_seconds = null
kms_master_key_id = null
sqs_managed_sse_enabled = true
})
}), {})
}), {})
}), {})

ssm = optional(object({
paths = optional(object({
root = optional(string, null)
app = optional(string, "app")
webhook = optional(string, "webhook")
tokens = optional(string, "runners/tokens")
config = optional(string, "runners/config")
}), {})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
}), {})
housekeeper = optional(object({
schedule_expression = optional(string, "rate(1 day)")
state = optional(string, "ENABLED")
tags = optional(map(string), {})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
memory_size = optional(number, 512)
timeout = optional(number, 60)
}), {})
config = optional(object({
tokenPath = optional(string, null)
minimumDaysOld = optional(number, 1)
dryRun = optional(bool, false)
}), {})
}), {})
}), {})

observability = optional(object({
logs = optional(object({
level = optional(string, "info")
retention_in_days = optional(number, 180)
kms_key_id = optional(string, null)
class = optional(string, "STANDARD")
tags = optional(map(string), {})
}), {})
tracing = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
}), {})
metrics = optional(object({
enable = optional(bool, false)
namespace = optional(string, "GitHub Runners")
metric = optional(object({
enable_github_app_rate_limit = optional(bool, true)
enable_job_retry = optional(bool, true)
enable_spot_termination = optional(bool, true)
enable_spot_termination_warning = optional(bool, true)
}), {})
}), {})
}), {})

compute_provider = optional(object({
ec2 = optional(object({
vpc_id = optional(string, null)
subnet_ids = optional(list(string), null)
managed_security_group_enabled = optional(bool, true)
egress_rules = optional(list(object({
cidr_blocks = list(string)
ipv6_cidr_blocks = list(string)
prefix_list_ids = list(string)
from_port = number
protocol = string
security_groups = list(string)
self = bool
to_port = number
description = string
})), [{
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
prefix_list_ids = null
from_port = 0
protocol = "-1"
security_groups = null
self = null
to_port = 0
description = null
}])
additional_security_group_ids = optional(list(string), [])
cloudwatch_agent = optional(object({
config = optional(string, null)
}), {})
instance_profile_path = optional(string, null)
key_name = optional(string, null)
associate_public_ipv4_address = optional(bool, false)
tags = optional(map(string), {})
ami = optional(object({
housekeeper = optional(object({
enabled = optional(bool, false)
cleanup_config = optional(object({
maxItems = optional(number)
minimumDaysOld = optional(number)
amiFilters = optional(list(object({
Name = string
Values = list(string)
})))
launchTemplateNames = optional(list(string))
ssmParameterNames = optional(list(string))
dryRun = optional(bool)
}), {})
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
lambda = optional(object({
memory_size = optional(number, 256)
timeout = optional(number, 300)
}), {})
schedule = optional(object({
expression = optional(string, "cron(11 7 * * ? *)")
}), {})
}), {})
}), {})
instance_termination_watcher = optional(object({
enabled = optional(bool, false)
features = optional(object({
enable_spot_termination_handler = optional(bool, true)
enable_spot_termination_notification_watcher = optional(bool, true)
}), {})
enable_runner_deregistration = optional(bool, true)
environment_variables = optional(map(string), {})
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
lambda = optional(object({
memory_size = optional(number, null)
timeout = optional(number, null)
}), {})
}), {})
runner_binaries = optional(object({
enabled = optional(bool, true)
s3 = optional(object({
encryption = optional(object({
enabled = optional(bool, true)
bucket_key_enabled = optional(bool, null)
sse_algorithm = optional(string, "AES256")
kms_master_key_id = optional(string, null)
}), {})
tags = optional(map(string), {})
versioning = optional(string, "Disabled")
logging = optional(object({
bucket = optional(string, null)
prefix = optional(string, null)
}), {})
}), {})
syncer = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
lambda = optional(object({
memory_size = optional(number, 256)
timeout = optional(number, 300)
}), {})
schedule = optional(object({
expression = optional(string, "cron(27 * * * ? *)")
state = optional(string, "ENABLED")
}), {})
}), {})
}), {})
}), {})
}), {})

multi_runner_config = optional(map(object({
tags = optional(map(string), {})

runner = optional(object({
os = optional(string, null)
architecture = optional(string, null)
disable_default_labels = optional(bool, null)
extra_labels = optional(list(string), null)
group_name = optional(string, null)
name_prefix = optional(string, null)
run_as_root = optional(bool, null)
run_as = optional(string, null)
auto_update_disabled = optional(bool, null)
tags = optional(map(string), {})
hooks = optional(object({
job_started = optional(string, null)
job_completed = optional(string, null)
}), {})
iam = optional(object({
role = optional(object({
arn = string
}), null)
managed_policy_arns = optional(map(string), null)
additional_trust_policy_json = optional(string, null)
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
}), {})

lambda = optional(object({
runtime = optional(string, null)
architecture = optional(string, null)
subnet_ids = optional(list(string), null)
security_group_ids = optional(list(string), null)
tags = optional(map(string), {})
role = optional(object({
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
}), {})

orchestration = object({
webhook = optional(object({
runner = optional(object({
boot_time_in_minutes = optional(number, null)
ephemeral = optional(bool, null)
jit_config_enabled = optional(bool, null)
maximum_count = optional(number, null)
}), {})

github = optional(object({
organization_runners = optional(bool, false)
}), {})

matcherConfig = object({
labelMatchers = list(list(string))
exactMatch = optional(bool, false)
bidirectionalLabelMatch = optional(bool, false)
priority = optional(number, 999)
enableDynamicLabels = optional(bool, false)
awsDynamicLabelsPolicy = optional(object({
blocked_keys = optional(list(string), [])
restricted_keys = optional(map(object({
allowed = optional(list(string), [])
denied = optional(list(string), [])
max = optional(string, null)
})), {})
}), null)
})

queue = optional(object({
delay_webhook_event = optional(number, null)
job_queue_retention_in_seconds = optional(number, null)
visibility_timeout_seconds = optional(number, null)
redrive_build_queue = optional(object({
enabled = optional(bool, null)
maxReceiveCount = optional(number, null)
}), null)
tags = optional(map(string), {})
}), {})

lambda = optional(object({
scale = optional(object({
up = optional(object({
memory_size = optional(number, null)
timeout = optional(number, null)
reserved_concurrent_executions = optional(number, null)
job_queued_check_enabled = optional(bool, null)
event_source_mapping = optional(object({
batch_size = optional(number, null)
maximum_batching_window_in_seconds = optional(number, null)
}), {})
tags = optional(map(string), {})
}), {})
down = optional(object({
memory_size = optional(number, null)
timeout = optional(number, null)
schedule_expression = optional(string, null)
minimum_running_time_in_minutes = optional(number, null)
idle_config = optional(list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = optional(string, "oldest_first")
})), null)
tags = optional(map(string), {})
}), {})
}), {})
pool = optional(object({
memory_size = optional(number, null)
timeout = optional(number, null)
reserved_concurrent_executions = optional(number, null)
config = optional(list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
})), null)
include_busy_runners = optional(bool, null)
runner_owner = optional(string, null)
tags = optional(map(string), {})
}), {})
}), {})

job_retry = optional(object({
enabled = optional(bool, false)
delay_in_seconds = optional(number, 300)
delay_backoff = optional(number, 2)
max_attempts = optional(number, 1)
tags = optional(map(string), {})
lambda = optional(object({
memory_size = optional(number, 256)
reserved_concurrent_executions = optional(number, 1)
timeout = optional(number, 30)
}), {})
}), {})

}), null)

})

ssm = optional(object({
paths = optional(object({
root = optional(string, null)
tokens = optional(string, null)
config = optional(string, null)
}), {})
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
}), {})
housekeeper = optional(object({
schedule_expression = optional(string, null)
state = optional(string, null)
tags = optional(map(string), {})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
memory_size = optional(number, null)
timeout = optional(number, null)
}), {})
config = optional(object({
tokenPath = optional(string, null)
minimumDaysOld = optional(number, null)
dryRun = optional(bool, null)
}), {})
}), {})
}), {})

observability = optional(object({
logs = optional(object({
level = optional(string, null)
retention_in_days = optional(number, null)
kms_key_id = optional(string, null)
class = optional(string, null)
tags = optional(map(string), {})
}), {})
tracing = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, null)
capture_error = optional(bool, null)
}), {})
metrics = optional(object({
enable = optional(bool, null)
namespace = optional(string, null)
metric = optional(object({
enable_github_app_rate_limit = optional(bool, null)
enable_job_retry = optional(bool, null)
}), {})
}), {})
}), {})

compute_provider = object({
ec2 = optional(object({
metadata_options = optional(object({
instance_metadata_tags = optional(string, "enabled")
http_endpoint = optional(string, "enabled")
http_tokens = optional(string, "required")
http_put_response_hop_limit = optional(number, 1)
}), {})
ami = optional(object({
filter = optional(map(list(string)), { state = ["available"] })
owners = optional(list(string), ["amazon"])
id_ssm_parameter = optional(object({
arn = string
}), null)
kms_key = optional(object({
arn = string
}), null)
}), null)
block_device_mappings = optional(list(object({
delete_on_termination = optional(bool, true)
device_name = optional(string, "/dev/xvda")
encrypted = optional(bool, true)
iops = optional(number)
kms_key_id = optional(string)
snapshot_id = optional(string)
throughput = optional(number)
volume_initialization_rate = optional(number)
volume_size = number
volume_type = optional(string, "gp3")
})), [{
volume_size = 30
}])
create_service_linked_role_spot = optional(bool, false)
credit_specification = optional(string, null)
ebs_optimized = optional(bool, false)
cloudwatch_agent = optional(object({
enabled = optional(bool, true)
config = optional(string, null)
}), {})
binaries_syncer = optional(object({
enabled = optional(bool, null)
}), {})
detailed_monitoring_enabled = optional(bool, false)
ssm_enabled = optional(bool, false)
user_data = optional(object({
enabled = optional(bool, true)
template = optional(string, null)
content = optional(string, null)
pre_install = optional(string, "")
post_install = optional(string, "")
debug_logging_enabled = optional(bool, false)
}), {})
instance_allocation_strategy = optional(string, "lowest-price")
instance_max_spot_price = optional(string, null)
instance_target_capacity_type = optional(string, "spot")
instance_type_priorities = optional(map(number), null)
instance_types = list(string)
additional_security_group_ids = optional(list(string), null)
managed_security_group_enabled = optional(bool, null)
egress_rules = optional(list(object({
cidr_blocks = list(string)
ipv6_cidr_blocks = list(string)
prefix_list_ids = list(string)
from_port = number
protocol = string
security_groups = list(string)
self = bool
to_port = number
description = string
})), null)
instance_profile_path = optional(string, null)
key_name = optional(string, null)
associate_public_ipv4_address = optional(bool, null)
instance_profile = optional(object({
name = string
}), null)
enable_on_demand_failover_for_errors = optional(list(string), [])
scale_errors = optional(list(string), [
"UnfulfillableCapacity",
"MaxSpotInstanceCountExceeded",
"TargetCapacityLimitExceededException",
"RequestLimitExceeded",
"ResourceLimitExceeded",
"MaxSpotInstanceCountExceeded",
"MaxSpotFleetRequestCountExceeded",
"InsufficientInstanceCapacity",
"InsufficientCapacityOnHost",
])
subnet_ids = optional(list(string), null)
vpc_id = optional(string, null)
cpu_options = optional(object({
core_count = optional(number)
threads_per_core = optional(number)
amd_sev_snp = optional(string)
nested_virtualization = optional(string)
}), null)
placement = optional(object({
affinity = optional(string)
availability_zone = optional(string)
group_id = optional(string)
group_name = optional(string)
host_id = optional(string)
host_resource_group_arn = optional(string)
spread_domain = optional(string)
tenancy = optional(string)
partition_number = optional(number)
}), null)
license_specifications = optional(list(object({
license_configuration_arn = string
})), [])
use_dedicated_host = optional(bool, false)
log_files = optional(list(object({
log_group_name = string
prefix_log_group = bool
file_path = string
log_stream_name = string
log_class = optional(string, "STANDARD")
})), null)
tags = optional(map(string), {})
}), null)
})

})), {})
})
| `{}` | no | | [ghes\_ssl\_verify](#input\_ghes\_ssl\_verify) | GitHub Enterprise SSL verification. Set to 'false' when custom certificate (chains) is used for GitHub Enterprise Server (insecure). | `bool` | `true` | no | | [ghes\_url](#input\_ghes\_url) | GitHub Enterprise Server URL. Example: https://github.internal.co - DO NOT SET IF USING PUBLIC GITHUB. .However if you are using GitHub Enterprise Cloud with data-residency (ghe.com), set the endpoint here. Example - https://companyname.ghe.com\| | `string` | `null` | no | -| [github\_app](#input\_github\_app) | GitHub app parameters, see your github app.
You can optionally create the SSM parameters yourself and provide the ARN and name here, through the `*_ssm` attributes.
If you chose to provide the configuration values directly here,
please ensure the key is the base64-encoded `.pem` file (the output of `base64 app.private-key.pem`, not the content of `private-key.pem`).
Note: the provided SSM parameters arn and name have a precedence over the actual value (i.e `key_base64_ssm` has a precedence over `key_base64` etc). |
object({
key_base64 = optional(string)
key_base64_ssm = optional(object({
arn = string
name = string
}))
id = optional(string)
id_ssm = optional(object({
arn = string
name = string
}))
webhook_secret = optional(string)
webhook_secret_ssm = optional(object({
arn = string
name = string
}))
})
| n/a | yes | +| [github\_app](#input\_github\_app) | GitHub app parameters, see your github app.
You can optionally create the SSM parameters yourself and provide the ARN and name here, through the `*_ssm` attributes.
If you chose to provide the configuration values directly here,
please ensure the key is the base64-encoded `.pem` file (the output of `base64 app.private-key.pem`, not the content of `private-key.pem`).
Note: the provided SSM parameters arn and name have a precedence over the actual value (i.e `key_base64_ssm` has a precedence over `key_base64` etc). |
object({
key_base64 = optional(string)
key_base64_ssm = optional(object({
arn = string
name = string
}))
id = optional(string)
id_ssm = optional(object({
arn = string
name = string
}))
webhook_secret = optional(string)
webhook_secret_ssm = optional(object({
arn = string
name = string
}))
})
| `null` | no | | [iam\_overrides](#input\_iam\_overrides) | This map provides the possibility to override some IAM defaults. The following attributes are supported: `instance_profile_name` overrides the instance profile name used in the launch template. `runner_role_arn` overrides the IAM role ARN used for the runner instances. |
object({
override_instance_profile = optional(bool, null)
instance_profile_name = optional(string, null)
override_runner_role = optional(bool, null)
runner_role_arn = optional(string, null)
})
|
{
"instance_profile_name": null,
"override_instance_profile": false,
"override_runner_role": false,
"runner_role_arn": null
}
| no | | [instance\_profile\_path](#input\_instance\_profile\_path) | The path that will be added to the instance\_profile, if not set the environment name will be used. | `string` | `null` | no | | [instance\_termination\_watcher](#input\_instance\_termination\_watcher) | Configuration for the spot termination watcher lambda function. This feature is Beta, changes will not trigger a major release as long in beta.

`enable`: Enable or disable the spot termination watcher.
`enable_runner_deregistration`: Enable or disable deregistering the runner from GitHub when its EC2 instance is terminated.
`environment_variables`: Additional environment variables to merge into the Lambda configuration.
`memory_size`: Memory size limit in MB of the lambda.
`s3_key`: S3 key for syncer lambda function. Required if using S3 bucket to specify lambdas.
`s3_object_version`: S3 object version for syncer lambda function. Useful if S3 versioning is enabled on source bucket.
`timeout`: Time out of the lambda in seconds.
`zip`: File location of the lambda zip file. |
object({
enable = optional(bool, false)
features = optional(object({
enable_spot_termination_handler = optional(bool, true)
enable_spot_termination_notification_watcher = optional(bool, true)
}), {})
enable_runner_deregistration = optional(bool, true)
environment_variables = optional(map(string), {})
memory_size = optional(number, null)
s3_key = optional(string, null)
s3_object_version = optional(string, null)
timeout = optional(number, null)
zip = optional(string, null)
})
| `{}` | no | @@ -174,7 +240,7 @@ module "multi-runner" { | [logging\_retention\_in\_days](#input\_logging\_retention\_in\_days) | Specifies the number of days you want to retain log events for the lambda log group. Possible values are: 0, 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, and 3653. | `number` | `180` | no | | [matcher\_config\_parameter\_store\_tier](#input\_matcher\_config\_parameter\_store\_tier) | The tier of the parameter store for the matcher configuration. Valid values are `Standard`, and `Advanced`. | `string` | `"Standard"` | no | | [metrics](#input\_metrics) | Configuration for metrics created by the module, by default metrics are disabled to avoid additional costs. When metrics are enable all metrics are created unless explicit configured otherwise. |
object({
enable = optional(bool, false)
namespace = optional(string, "GitHub Runners")
metric = optional(object({
enable_github_app_rate_limit = optional(bool, true)
enable_job_retry = optional(bool, true)
enable_spot_termination_warning = optional(bool, true)
}), {})
})
| `{}` | no | -| [multi\_runner\_config](#input\_multi\_runner\_config) | multi\_runner\_config = {
runner\_config: {
runner\_os: "The EC2 Operating System type to use for action runner instances (linux, osx, windows)."
runner\_architecture: "The platform architecture of the runner instance\_type."
runner\_metadata\_options: "(Optional) Metadata options for the ec2 runner instances."
ami: "(Optional) AMI configuration for the action runner instances. This object allows you to specify all AMI-related settings in one place."
create\_service\_linked\_role\_spot: (Optional) create the serviced linked role for spot instances that is required by the scale-up lambda.
credit\_specification: "(Optional) The credit specification of the runner instance\_type. Can be unset, `standard` or `unlimited`.
delay\_webhook\_event: "The number of seconds the event accepted by the webhook is invisible on the queue before the scale up lambda will receive the event."
disable\_runner\_autoupdate: "Disable the auto update of the github runner agent. Be aware there is a grace period of 30 days, see also the [GitHub article](https://github.blog/changelog/2022-02-01-github-actions-self-hosted-runners-can-now-disable-automatic-updates/)"
ebs\_optimized: "The EC2 EBS optimized configuration."
enable\_ephemeral\_runners: "Enable ephemeral runners, runners will only be used once."
enable\_job\_queued\_check: Enables JIT configuration for creating runners instead of registration token based registraton. JIT configuration will only be applied for ephemeral runners. By default JIT configuration is enabled for ephemeral runners an can be disabled via this override. When running on GHES without support for JIT configuration this variable should be set to true for ephemeral runners."
enable\_on\_demand\_failover\_for\_errors: "Enable on-demand failover. For example to fall back to on demand when no spot capacity is available the variable can be set to `InsufficientInstanceCapacity`. When not defined the default behavior is to retry later."
scale\_errors: "List of AWS error codes that should trigger retry during scale up. This list replaces the module default scale-up retry errors"
enable\_organization\_runners: "Register runners to organization, instead of repo level"
enable\_runner\_binaries\_syncer: "Option to disable the lambda to sync GitHub runner distribution, useful when using a pre-build AMI."
enable\_ssm\_on\_runners: "Enable to allow access the runner instances for debugging purposes via SSM. Note that this adds additional permissions to the runner instances."
enable\_userdata: "Should the userdata script be enabled for the runner. Set this to false if you are using your own prebuilt AMI."
instance\_allocation\_strategy: "The allocation strategy for creating instances. For spot, AWS recommends `price-capacity-optimized`; for on-demand, use `lowest-price` or `prioritized`. The AWS default is `lowest-price`."
instance\_type\_priorities: "A map of instance type to priority for the `prioritized` and `capacity-optimized-prioritized` allocation strategies. Lower numbers mean higher priority. If not provided, priorities are assigned based on the order of `instance_types`."
instance\_max\_spot\_price: "Max price price for spot instances per hour. This variable will be passed to the create fleet as max spot price for the fleet."
instance\_target\_capacity\_type: "Default lifecycle used for runner instances, can be either `spot` or `on-demand`."
instance\_types: "List of instance types for the action runner. Defaults are based on runner\_os (al2023 for linux, macOS Sequoia for osx, Windows Server Core for win)."
job\_queue\_retention\_in\_seconds: "The number of seconds the job is held in the queue before it is purged"
minimum\_running\_time\_in\_minutes: "The time an ec2 action runner should be running at minimum before terminated if not busy."
pool\_runner\_owner: "The pool will deploy runners to the GitHub org ID, set this value to the org to which you want the runners deployed. Repo level is not supported."
runner\_additional\_security\_group\_ids: "List of additional security groups IDs to apply to the runner. If added outside the multi\_runner\_config block, the additional security group(s) will be applied to all runner configs. If added inside the multi\_runner\_config, the additional security group(s) will be applied to the individual runner."
runner\_as\_root: "Run the action runner under the root user. Variable `runner_run_as` will be ignored."
runner\_boot\_time\_in\_minutes: "The minimum time for an EC2 runner to boot and register as a runner."
runner\_disable\_default\_labels: "Disable default labels for the runners (os, architecture and `self-hosted`). If enabled, the runner will only have the extra labels provided in `runner_extra_labels`. In case you on own start script is used, this configuration parameter needs to be parsed via SSM."
runner\_extra\_labels: "Extra (custom) labels for the runners (GitHub). Separate each label by a comma. Labels checks on the webhook can be enforced by setting `multi_runner_config.matcherConfig.exactMatch`. GitHub read-only labels should not be provided."
runner\_group\_name: "Name of the runner group."
runner\_name\_prefix: "Prefix for the GitHub runner name."
runner\_run\_as: "Run the GitHub actions agent as user."
runners\_maximum\_count: "The maximum number of runners that will be created. Setting the variable to `-1` disables the maximum check."
scale\_down\_schedule\_expression: "Scheduler expression to check every x for scale down."
scale\_up\_reserved\_concurrent\_executions: "Amount of reserved concurrent executions for the scale-up lambda function. A value of 0 disables lambda from being triggered and -1 removes any concurrency limitations."
lambda\_event\_source\_mapping\_batch\_size: "(Optional) Maximum number of records per Lambda invocation for this runner flavor. Overrides the module-level `lambda_event_source_mapping_batch_size` when set."
lambda\_event\_source\_mapping\_maximum\_batching\_window\_in\_seconds: "(Optional) Maximum seconds to gather records before invoking Lambda for this runner flavor. Overrides the module-level `lambda_event_source_mapping_maximum_batching_window_in_seconds` when set."
userdata\_template: "Alternative user-data template, replacing the default template. By providing your own user\_data you have to take care of installing all required software, including the action runner. Variables userdata\_pre/post\_install are ignored."
enable\_jit\_config: "Overwrite the default behavior for JIT configuration. By default JIT configuration is enabled for ephemeral runners and disabled for non-ephemeral runners. In case of GHES check first if the JIT config API is available. In case you are upgrading from 3.x to 4.x you can set `enable_jit_config` to `false` to avoid a breaking change when having your own AMI."
enable\_runner\_detailed\_monitoring: "Should detailed monitoring be enabled for the runner. Set this to true if you want to use detailed monitoring. See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch-new.html for details."
enable\_cloudwatch\_agent: "Enabling the cloudwatch agent on the ec2 runner instances, the runner contains default config. Configuration can be overridden via `cloudwatch_config`."
cloudwatch\_config: "(optional) Replaces the module default cloudwatch log config. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html for details."
userdata\_pre\_install: "Script to be ran before the GitHub Actions runner is installed on the EC2 instances"
userdata\_post\_install: "Script to be ran after the GitHub Actions runner is installed on the EC2 instances"
runner\_hook\_job\_started: "Script to be ran in the runner environment at the beginning of every job"
runner\_hook\_job\_completed: "Script to be ran in the runner environment at the end of every job"
runner\_ec2\_tags: "Map of tags that will be added to the launch template instance tag specifications."
runner\_iam\_role\_managed\_policy\_arns: "Attach AWS or customer-managed IAM policies (by ARN) to the runner IAM role"
vpc\_id: "The VPC for security groups of the action runners. If not set uses the value of `var.vpc_id`."
subnet\_ids: "List of subnets in which the action runners will be launched, the subnets needs to be subnets in the `vpc_id`. If not set, uses the value of `var.subnet_ids`."
idle\_config: "List of time period that can be defined as cron expression to keep a minimum amount of runners active instead of scaling down to 0. By defining this list you can ensure that in time periods that match the cron expression within 5 seconds a runner is kept idle."
license\_specifications: "Optional EC2 License Manager license configuration ARNs for the runner launch template. Required for macOS dedicated-host runners when the host resource group uses a Mac dedicated host license configuration."
use\_dedicated\_host: "Experimental! Can be removed / changed without trigger a major release. Whether to use EC2 dedicated hosts for the runners. Needed for macos runners Note that using dedicated hosts can increase cost significantly."
runner\_log\_files: "(optional) Replaces the module default cloudwatch log config. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html for details."
block\_device\_mappings: "The EC2 instance block device configuration. Takes the following keys: `device_name`, `delete_on_termination`, `volume_type`, `volume_size`, `encrypted`, `iops`, `throughput`, `kms_key_id`, `snapshot_id`, `volume_initialization_rate`."
job\_retry: "Experimental! Can be removed / changed without trigger a major release. Configure job retries. The configuration enables job retries (for ephemeral runners). After creating the instances a message will be published to a job retry queue. The job retry check lambda is checking after a delay if the job is queued. If not the message will be published again on the scale-up (build queue). Using this feature can impact the rate limit of the GitHub app."
pool\_config: "The configuration for updating the pool. The `pool_size` to adjust to by the events triggered by the `schedule_expression`. For example you can configure a cron expression for week days to adjust the pool to 10 and another expression for the weekend to adjust the pool to 1. Use `schedule_expression_timezone` to override the schedule time zone (defaults to UTC)."
iam\_overrides: "Allows to (optionally) override the instance profile and runner role created by the module. Set `override_instance_profile` to true and provide the `instance_profile_name` to use an existing instance profile. Set `override_runner_role` to true and provide the `runner_role_arn` to use an existing role for the runner instances."
}
matcherConfig: {
labelMatchers: "The list of list of labels supported by the runner configuration. `[[self-hosted, linux, x64, example]]`"
exactMatch: "DEPRECATED: Use `bidirectionalLabelMatch` instead. If set to true all labels in the workflow job must match the GitHub labels (os, architecture and `self-hosted`). When false if __any__ workflow label matches it will trigger the webhook. Note: this only checks that workflow labels are a subset of runner labels, not the reverse."
bidirectionalLabelMatch: "If set to true, the runner labels and workflow job labels must be an exact two-way match (same set, any order, no extras or missing labels). This is stricter than `exactMatch` which only checks that workflow labels are a subset of runner labels. When false, if __any__ workflow label matches it will trigger the webhook."
priority: "If set it defines the priority of the matcher, the matcher with the lowest priority will be evaluated first. Default is 999, allowed values 0-999."
enableDynamicLabels: "Experimental! When true the dispatcher allows `ghr-*` dynamic labels for jobs routed to this runner. Default false."
awsDynamicLabelsPolicy: "Optional AWS dynamic label policy evaluated by the dispatcher. Only effective when `enableDynamicLabels = true`. Jobs whose provider dynamic labels violate every matching runner's policy are rejected with a 202 (a warning is logged). Evaluation: keys in `blocked_keys` are always rejected; keys in `restricted_keys` are allowed only when their value passes the rule; unlisted keys are allowed. Schema: `{ blocked_keys = [], restricted_keys = { = { allowed = [globs], denied = [globs], max = number|string } } }`. Keys use the dynamic label suffix, e.g. `instance-type` for `ghr-ec2-instance-type`."
}
redrive\_build\_queue: "Set options to attach (optional) a dead letter queue to the build queue, the queue between the webhook and the scale up lambda. You have the following options. 1. Disable by setting `enabled` to false. 2. Enable by setting `enabled` to `true`, `maxReceiveCount` to a number of max retries."
} |
map(object({
runner_config = object({
runner_os = string
runner_architecture = string
runner_metadata_options = optional(map(any), {
instance_metadata_tags = "enabled"
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 1
})
ami = optional(object({
filter = optional(map(list(string)), { state = ["available"] })
owners = optional(list(string), ["amazon"])
id_ssm_parameter_arn = optional(string, null)
kms_key_arn = optional(string, null)
}), null)
create_service_linked_role_spot = optional(bool, false)
credit_specification = optional(string, null)
delay_webhook_event = optional(number, 30)
disable_runner_autoupdate = optional(bool, false)
ebs_optimized = optional(bool, false)
enable_ephemeral_runners = optional(bool, false)
enable_job_queued_check = optional(bool, null)
enable_on_demand_failover_for_errors = optional(list(string), [])
scale_errors = optional(list(string), [
"UnfulfillableCapacity",
"MaxSpotInstanceCountExceeded",
"TargetCapacityLimitExceededException",
"RequestLimitExceeded",
"ResourceLimitExceeded",
"MaxSpotInstanceCountExceeded",
"MaxSpotFleetRequestCountExceeded",
"InsufficientInstanceCapacity",
"InsufficientCapacityOnHost",
])
enable_organization_runners = optional(bool, false)
enable_runner_binaries_syncer = optional(bool, true)
enable_ssm_on_runners = optional(bool, false)
enable_userdata = optional(bool, true)
instance_allocation_strategy = optional(string, "lowest-price")
instance_type_priorities = optional(map(number), null)
instance_max_spot_price = optional(string, null)
instance_target_capacity_type = optional(string, "spot")
instance_types = list(string)
job_queue_retention_in_seconds = optional(number, 86400)
minimum_running_time_in_minutes = optional(number, null)
pool_runner_owner = optional(string, null)
runner_as_root = optional(bool, false)
runner_boot_time_in_minutes = optional(number, 5)
runner_disable_default_labels = optional(bool, false)
runner_extra_labels = optional(list(string), [])
runner_group_name = optional(string, "Default")
runner_name_prefix = optional(string, "")
runner_run_as = optional(string, "ec2-user")
runners_maximum_count = number
runner_additional_security_group_ids = optional(list(string), [])
scale_down_schedule_expression = optional(string, "cron(*/5 * * * ? *)")
scale_up_reserved_concurrent_executions = optional(number, 1)
lambda_event_source_mapping_batch_size = optional(number, null)
lambda_event_source_mapping_maximum_batching_window_in_seconds = optional(number, null)
userdata_template = optional(string, null)
userdata_content = optional(string, null)
enable_jit_config = optional(bool, null)
enable_runner_detailed_monitoring = optional(bool, false)
enable_cloudwatch_agent = optional(bool, true)
cloudwatch_config = optional(string, null)
userdata_pre_install = optional(string, "")
userdata_post_install = optional(string, "")
runner_hook_job_started = optional(string, "")
runner_hook_job_completed = optional(string, "")
runner_ec2_tags = optional(map(string), {})
runner_iam_role_managed_policy_arns = optional(list(string), [])
vpc_id = optional(string, null)
subnet_ids = optional(list(string), null)
idle_config = optional(list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = optional(string, "oldest_first")
})), [])
cpu_options = optional(object({
core_count = optional(number)
threads_per_core = optional(number)
amd_sev_snp = optional(string)
nested_virtualization = optional(string)
}), null)
placement = optional(object({
affinity = optional(string)
availability_zone = optional(string)
group_id = optional(string)
group_name = optional(string)
host_id = optional(string)
host_resource_group_arn = optional(string)
spread_domain = optional(string)
tenancy = optional(string)
partition_number = optional(number)
}), null)
license_specifications = optional(list(object({
license_configuration_arn = string
})), [])
use_dedicated_host = optional(bool, false)
runner_log_files = optional(list(object({
log_group_name = string
prefix_log_group = bool
file_path = string
log_stream_name = string
log_class = optional(string, "STANDARD")
})), null)
block_device_mappings = optional(list(object({
delete_on_termination = optional(bool, true)
device_name = optional(string, "/dev/xvda")
encrypted = optional(bool, true)
iops = optional(number)
kms_key_id = optional(string)
snapshot_id = optional(string)
throughput = optional(number)
volume_initialization_rate = optional(number)
volume_size = number
volume_type = optional(string, "gp3")
})), [{
volume_size = 30
}])
pool_config = optional(list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
})), [])
job_retry = optional(object({
enable = optional(bool, false)
delay_in_seconds = optional(number, 300)
delay_backoff = optional(number, 2)
lambda_memory_size = optional(number, 256)
lambda_timeout = optional(number, 30)
max_attempts = optional(number, 1)
}), {})
iam_overrides = optional(object({
override_instance_profile = optional(bool, null)
instance_profile_name = optional(string, null)
override_runner_role = optional(bool, null)
runner_role_arn = optional(string, null)
}), {
override_instance_profile = false
instance_profile_name = null
override_runner_role = false
runner_role_arn = null
})
})
matcherConfig = object({
labelMatchers = list(list(string))
exactMatch = optional(bool, false)
bidirectionalLabelMatch = optional(bool, false)
priority = optional(number, 999)
enableDynamicLabels = optional(bool, false)
awsDynamicLabelsPolicy = optional(any, null)
})
redrive_build_queue = optional(object({
enabled = bool
maxReceiveCount = number
}), {
enabled = false
maxReceiveCount = null
})
}))
| n/a | yes | +| [multi\_runner\_config](#input\_multi\_runner\_config) | multi\_runner\_config = {
runner\_config: {
runner\_os: "The EC2 Operating System type to use for action runner instances (linux, osx, windows)."
runner\_architecture: "The platform architecture of the runner instance\_type."
runner\_metadata\_options: "(Optional) Metadata options for the ec2 runner instances."
ami: "(Optional) AMI configuration for the action runner instances. This object allows you to specify all AMI-related settings in one place."
create\_service\_linked\_role\_spot: (Optional) create the serviced linked role for spot instances that is required by the scale-up lambda.
credit\_specification: "(Optional) The credit specification of the runner instance\_type. Can be unset, `standard` or `unlimited`.
delay\_webhook\_event: "The number of seconds the event accepted by the webhook is invisible on the queue before the scale up lambda will receive the event."
disable\_runner\_autoupdate: "Disable the auto update of the github runner agent. Be aware there is a grace period of 30 days, see also the [GitHub article](https://github.blog/changelog/2022-02-01-github-actions-self-hosted-runners-can-now-disable-automatic-updates/)"
ebs\_optimized: "The EC2 EBS optimized configuration."
enable\_ephemeral\_runners: "Enable ephemeral runners, runners will only be used once."
enable\_job\_queued\_check: Enables JIT configuration for creating runners instead of registration token based registraton. JIT configuration will only be applied for ephemeral runners. By default JIT configuration is enabled for ephemeral runners an can be disabled via this override. When running on GHES without support for JIT configuration this variable should be set to true for ephemeral runners."
enable\_on\_demand\_failover\_for\_errors: "Enable on-demand failover. For example to fall back to on demand when no spot capacity is available the variable can be set to `InsufficientInstanceCapacity`. When not defined the default behavior is to retry later."
scale\_errors: "List of AWS error codes that should trigger retry during scale up. This list replaces the module default scale-up retry errors"
enable\_organization\_runners: "Register runners to organization, instead of repo level"
enable\_runner\_binaries\_syncer: "Option to disable the lambda to sync GitHub runner distribution, useful when using a pre-build AMI."
enable\_ssm\_on\_runners: "Enable to allow access the runner instances for debugging purposes via SSM. Note that this adds additional permissions to the runner instances."
enable\_userdata: "Should the userdata script be enabled for the runner. Set this to false if you are using your own prebuilt AMI."
instance\_allocation\_strategy: "The allocation strategy for creating instances. For spot, AWS recommends `price-capacity-optimized`; for on-demand, use `lowest-price` or `prioritized`. The AWS default is `lowest-price`."
instance\_type\_priorities: "A map of instance type to priority for the `prioritized` and `capacity-optimized-prioritized` allocation strategies. Lower numbers mean higher priority. If not provided, priorities are assigned based on the order of `instance_types`."
instance\_max\_spot\_price: "Max price price for spot instances per hour. This variable will be passed to the create fleet as max spot price for the fleet."
instance\_target\_capacity\_type: "Default lifecycle used for runner instances, can be either `spot` or `on-demand`."
instance\_types: "List of instance types for the action runner. Defaults are based on runner\_os (al2023 for linux, macOS Sequoia for osx, Windows Server Core for win)."
job\_queue\_retention\_in\_seconds: "The number of seconds the job is held in the queue before it is purged"
minimum\_running\_time\_in\_minutes: "The time an ec2 action runner should be running at minimum before terminated if not busy."
pool\_runner\_owner: "The pool will deploy runners to the GitHub org ID, set this value to the org to which you want the runners deployed. Repo level is not supported."
runner\_additional\_security\_group\_ids: "List of additional security groups IDs to apply to the runner. If added outside the multi\_runner\_config block, the additional security group(s) will be applied to all runner configs. If added inside the multi\_runner\_config, the additional security group(s) will be applied to the individual runner."
runner\_as\_root: "Run the action runner under the root user. Variable `runner_run_as` will be ignored."
runner\_boot\_time\_in\_minutes: "The minimum time for an EC2 runner to boot and register as a runner."
runner\_disable\_default\_labels: "Disable default labels for the runners (os, architecture and `self-hosted`). If enabled, the runner will only have the extra labels provided in `runner_extra_labels`. In case you on own start script is used, this configuration parameter needs to be parsed via SSM."
runner\_extra\_labels: "Extra (custom) labels for the runners (GitHub). Separate each label by a comma. Labels checks on the webhook can be enforced by setting `multi_runner_config.matcherConfig.exactMatch`. GitHub read-only labels should not be provided."
runner\_group\_name: "Name of the runner group."
runner\_name\_prefix: "Prefix for the GitHub runner name."
runner\_run\_as: "Run the GitHub actions agent as user."
runners\_maximum\_count: "The maximum number of runners that will be created. Setting the variable to `-1` disables the maximum check."
scale\_down\_schedule\_expression: "Scheduler expression to check every x for scale down."
scale\_up\_reserved\_concurrent\_executions: "Amount of reserved concurrent executions for the scale-up lambda function. A value of 0 disables lambda from being triggered and -1 removes any concurrency limitations."
lambda\_event\_source\_mapping\_batch\_size: "(Optional) Maximum number of records per Lambda invocation for this runner flavor. Overrides the module-level `lambda_event_source_mapping_batch_size` when set."
lambda\_event\_source\_mapping\_maximum\_batching\_window\_in\_seconds: "(Optional) Maximum seconds to gather records before invoking Lambda for this runner flavor. Overrides the module-level `lambda_event_source_mapping_maximum_batching_window_in_seconds` when set."
userdata\_template: "Alternative user-data template, replacing the default template. By providing your own user\_data you have to take care of installing all required software, including the action runner. Variables userdata\_pre/post\_install are ignored."
enable\_jit\_config: "Overwrite the default behavior for JIT configuration. By default JIT configuration is enabled for ephemeral runners and disabled for non-ephemeral runners. In case of GHES check first if the JIT config API is available. In case you are upgrading from 3.x to 4.x you can set `enable_jit_config` to `false` to avoid a breaking change when having your own AMI."
enable\_runner\_detailed\_monitoring: "Should detailed monitoring be enabled for the runner. Set this to true if you want to use detailed monitoring. See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch-new.html for details."
enable\_cloudwatch\_agent: "Enabling the cloudwatch agent on the ec2 runner instances, the runner contains default config. Configuration can be overridden via `cloudwatch_config`."
cloudwatch\_config: "(optional) Replaces the module default cloudwatch log config. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html for details."
userdata\_pre\_install: "Script to be ran before the GitHub Actions runner is installed on the EC2 instances"
userdata\_post\_install: "Script to be ran after the GitHub Actions runner is installed on the EC2 instances"
runner\_hook\_job\_started: "Script to be ran in the runner environment at the beginning of every job"
runner\_hook\_job\_completed: "Script to be ran in the runner environment at the end of every job"
runner\_ec2\_tags: "Map of tags that will be added to the launch template instance tag specifications."
runner\_iam\_role\_managed\_policy\_arns: "Attach AWS or customer-managed IAM policies (by ARN) to the runner IAM role"
vpc\_id: "The VPC for security groups of the action runners. If not set uses the value of `var.vpc_id`."
subnet\_ids: "List of subnets in which the action runners will be launched, the subnets needs to be subnets in the `vpc_id`. If not set, uses the value of `var.subnet_ids`."
idle\_config: "List of time period that can be defined as cron expression to keep a minimum amount of runners active instead of scaling down to 0. By defining this list you can ensure that in time periods that match the cron expression within 5 seconds a runner is kept idle."
license\_specifications: "Optional EC2 License Manager license configuration ARNs for the runner launch template. Required for macOS dedicated-host runners when the host resource group uses a Mac dedicated host license configuration."
use\_dedicated\_host: "Experimental! Can be removed / changed without trigger a major release. Whether to use EC2 dedicated hosts for the runners. Needed for macos runners Note that using dedicated hosts can increase cost significantly."
runner\_log\_files: "(optional) Replaces the module default cloudwatch log config. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html for details."
block\_device\_mappings: "The EC2 instance block device configuration. Takes the following keys: `device_name`, `delete_on_termination`, `volume_type`, `volume_size`, `encrypted`, `iops`, `throughput`, `kms_key_id`, `snapshot_id`, `volume_initialization_rate`."
job\_retry: "Experimental! Can be removed / changed without trigger a major release. Configure job retries. The configuration enables job retries (for ephemeral runners). After creating the instances a message will be published to a job retry queue. The job retry check lambda is checking after a delay if the job is queued. If not the message will be published again on the scale-up (build queue). Using this feature can impact the rate limit of the GitHub app."
pool\_config: "The configuration for updating the pool. The `pool_size` to adjust to by the events triggered by the `schedule_expression`. For example you can configure a cron expression for week days to adjust the pool to 10 and another expression for the weekend to adjust the pool to 1. Use `schedule_expression_timezone` to override the schedule time zone (defaults to UTC)."
iam\_overrides: "Allows to (optionally) override the instance profile and runner role created by the module. Set `override_instance_profile` to true and provide the `instance_profile_name` to use an existing instance profile. Set `override_runner_role` to true and provide the `runner_role_arn` to use an existing role for the runner instances."
}
matcherConfig: {
labelMatchers: "The list of list of labels supported by the runner configuration. `[[self-hosted, linux, x64, example]]`"
exactMatch: "DEPRECATED: Use `bidirectionalLabelMatch` instead. If set to true all labels in the workflow job must match the GitHub labels (os, architecture and `self-hosted`). When false if __any__ workflow label matches it will trigger the webhook. Note: this only checks that workflow labels are a subset of runner labels, not the reverse."
bidirectionalLabelMatch: "If set to true, the runner labels and workflow job labels must be an exact two-way match (same set, any order, no extras or missing labels). This is stricter than `exactMatch` which only checks that workflow labels are a subset of runner labels. When false, if __any__ workflow label matches it will trigger the webhook."
priority: "If set it defines the priority of the matcher, the matcher with the lowest priority will be evaluated first. Default is 999, allowed values 0-999."
enableDynamicLabels: "Experimental! When true the dispatcher allows `ghr-*` dynamic labels for jobs routed to this runner. Default false."
awsDynamicLabelsPolicy: "Optional AWS dynamic label policy evaluated by the dispatcher. Only effective when `enableDynamicLabels = true`. Jobs whose provider dynamic labels violate every matching runner's policy are rejected with a 202 (a warning is logged). Evaluation: keys in `blocked_keys` are always rejected; keys in `restricted_keys` are allowed only when their value passes the rule; unlisted keys are allowed. Schema: `{ blocked_keys = [], restricted_keys = { = { allowed = [globs], denied = [globs], max = number|string } } }`. Keys use the dynamic label suffix, e.g. `instance-type` for `ghr-ec2-instance-type`."
}
redrive\_build\_queue: "Set options to attach (optional) a dead letter queue to the build queue, the queue between the webhook and the scale up lambda. You have the following options. 1. Disable by setting `enabled` to false. 2. Enable by setting `enabled` to `true`, `maxReceiveCount` to a number of max retries."
} |
map(object({
runner_config = object({
runner_os = string
runner_architecture = string
runner_metadata_options = optional(map(any), {
instance_metadata_tags = "enabled"
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 1
})
ami = optional(object({
filter = optional(map(list(string)), { state = ["available"] })
owners = optional(list(string), ["amazon"])
id_ssm_parameter_arn = optional(string, null)
kms_key_arn = optional(string, null)
}), null)
create_service_linked_role_spot = optional(bool, false)
credit_specification = optional(string, null)
delay_webhook_event = optional(number, 30)
disable_runner_autoupdate = optional(bool, false)
ebs_optimized = optional(bool, false)
enable_ephemeral_runners = optional(bool, false)
enable_job_queued_check = optional(bool, null)
enable_on_demand_failover_for_errors = optional(list(string), [])
scale_errors = optional(list(string), [
"UnfulfillableCapacity",
"MaxSpotInstanceCountExceeded",
"TargetCapacityLimitExceededException",
"RequestLimitExceeded",
"ResourceLimitExceeded",
"MaxSpotInstanceCountExceeded",
"MaxSpotFleetRequestCountExceeded",
"InsufficientInstanceCapacity",
"InsufficientCapacityOnHost",
])
enable_organization_runners = optional(bool, false)
enable_runner_binaries_syncer = optional(bool, true)
enable_ssm_on_runners = optional(bool, false)
enable_userdata = optional(bool, true)
instance_allocation_strategy = optional(string, "lowest-price")
instance_type_priorities = optional(map(number), null)
instance_max_spot_price = optional(string, null)
instance_target_capacity_type = optional(string, "spot")
instance_types = list(string)
job_queue_retention_in_seconds = optional(number, 86400)
minimum_running_time_in_minutes = optional(number, null)
pool_runner_owner = optional(string, null)
runner_as_root = optional(bool, false)
runner_boot_time_in_minutes = optional(number, 5)
runner_disable_default_labels = optional(bool, false)
runner_extra_labels = optional(list(string), [])
runner_group_name = optional(string, "Default")
runner_name_prefix = optional(string, "")
runner_run_as = optional(string, "ec2-user")
runners_maximum_count = number
runner_additional_security_group_ids = optional(list(string), [])
scale_down_schedule_expression = optional(string, "cron(*/5 * * * ? *)")
scale_up_reserved_concurrent_executions = optional(number, 1)
lambda_event_source_mapping_batch_size = optional(number, null)
lambda_event_source_mapping_maximum_batching_window_in_seconds = optional(number, null)
userdata_template = optional(string, null)
userdata_content = optional(string, null)
enable_jit_config = optional(bool, null)
enable_runner_detailed_monitoring = optional(bool, false)
enable_cloudwatch_agent = optional(bool, true)
cloudwatch_config = optional(string, null)
userdata_pre_install = optional(string, "")
userdata_post_install = optional(string, "")
runner_hook_job_started = optional(string, "")
runner_hook_job_completed = optional(string, "")
runner_ec2_tags = optional(map(string), {})
runner_iam_role_managed_policy_arns = optional(list(string), [])
vpc_id = optional(string, null)
subnet_ids = optional(list(string), null)
idle_config = optional(list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = optional(string, "oldest_first")
})), [])
cpu_options = optional(object({
core_count = optional(number)
threads_per_core = optional(number)
amd_sev_snp = optional(string)
nested_virtualization = optional(string)
}), null)
placement = optional(object({
affinity = optional(string)
availability_zone = optional(string)
group_id = optional(string)
group_name = optional(string)
host_id = optional(string)
host_resource_group_arn = optional(string)
spread_domain = optional(string)
tenancy = optional(string)
partition_number = optional(number)
}), null)
license_specifications = optional(list(object({
license_configuration_arn = string
})), [])
use_dedicated_host = optional(bool, false)
runner_log_files = optional(list(object({
log_group_name = string
prefix_log_group = bool
file_path = string
log_stream_name = string
log_class = optional(string, "STANDARD")
})), null)
block_device_mappings = optional(list(object({
delete_on_termination = optional(bool, true)
device_name = optional(string, "/dev/xvda")
encrypted = optional(bool, true)
iops = optional(number)
kms_key_id = optional(string)
snapshot_id = optional(string)
throughput = optional(number)
volume_initialization_rate = optional(number)
volume_size = number
volume_type = optional(string, "gp3")
})), [{
volume_size = 30
}])
pool_config = optional(list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
})), [])
job_retry = optional(object({
enable = optional(bool, false)
delay_in_seconds = optional(number, 300)
delay_backoff = optional(number, 2)
lambda_memory_size = optional(number, 256)
lambda_timeout = optional(number, 30)
max_attempts = optional(number, 1)
}), {})
iam_overrides = optional(object({
override_instance_profile = optional(bool, null)
instance_profile_name = optional(string, null)
override_runner_role = optional(bool, null)
runner_role_arn = optional(string, null)
}), {
override_instance_profile = false
instance_profile_name = null
override_runner_role = false
runner_role_arn = null
})
})
matcherConfig = object({
labelMatchers = list(list(string))
exactMatch = optional(bool, false)
bidirectionalLabelMatch = optional(bool, false)
priority = optional(number, 999)
enableDynamicLabels = optional(bool, false)
awsDynamicLabelsPolicy = optional(object({
blocked_keys = optional(list(string), [])
restricted_keys = optional(map(object({
allowed = optional(list(string), [])
denied = optional(list(string), [])
max = optional(string, null)
})), {})
}), null)
})
redrive_build_queue = optional(object({
enabled = bool
maxReceiveCount = number
}), {
enabled = false
maxReceiveCount = null
})
}))
| `{}` | no | | [parameter\_store\_tags](#input\_parameter\_store\_tags) | Map of tags that will be added to all the SSM Parameter Store parameters created by the Lambda function. | `map(string)` | `{}` | no | | [pool\_lambda\_reserved\_concurrent\_executions](#input\_pool\_lambda\_reserved\_concurrent\_executions) | Amount of reserved concurrent executions for the scale-up lambda function. A value of 0 disables lambda from being triggered and -1 removes any concurrency limitations. | `number` | `1` | no | | [pool\_lambda\_timeout](#input\_pool\_lambda\_timeout) | Time out for the pool lambda in seconds. | `number` | `60` | no | @@ -202,13 +268,13 @@ module "multi-runner" { | [scale\_up\_lambda\_memory\_size](#input\_scale\_up\_lambda\_memory\_size) | Memory size limit in MB for scale\_up lambda. | `number` | `512` | no | | [ssm\_paths](#input\_ssm\_paths) | The root path used in SSM to store configuration and secrets. |
object({
root = optional(string, "github-action-runners")
app = optional(string, "app")
runners = optional(string, "runners")
webhook = optional(string, "webhook")
})
| `{}` | no | | [state\_event\_rule\_binaries\_syncer](#input\_state\_event\_rule\_binaries\_syncer) | Option to disable EventBridge Lambda trigger for the binary syncer, useful to stop automatic updates of binary distribution | `string` | `"ENABLED"` | no | -| [subnet\_ids](#input\_subnet\_ids) | List of subnets in which the action runners will be launched, the subnets needs to be subnets in the `vpc_id`. | `list(string)` | n/a | yes | +| [subnet\_ids](#input\_subnet\_ids) | List of subnets in which the action runners will be launched, the subnets needs to be subnets in the `vpc_id`. | `list(string)` | `null` | no | | [syncer\_lambda\_s3\_key](#input\_syncer\_lambda\_s3\_key) | S3 key for syncer lambda function. Required if using S3 bucket to specify lambdas. | `string` | `null` | no | | [syncer\_lambda\_s3\_object\_version](#input\_syncer\_lambda\_s3\_object\_version) | S3 object version for syncer lambda function. Useful if S3 versioning is enabled on source bucket. | `string` | `null` | no | | [tags](#input\_tags) | Map of tags that will be added to created resources. By default resources will be tagged with name and environment. | `map(string)` | `{}` | no | | [tracing\_config](#input\_tracing\_config) | Configuration for lambda tracing. |
object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
})
| `{}` | no | | [user\_agent](#input\_user\_agent) | User agent used for API calls by lambda functions. | `string` | `"github-aws-runners"` | no | -| [vpc\_id](#input\_vpc\_id) | The VPC for security groups of the action runners. | `string` | n/a | yes | +| [vpc\_id](#input\_vpc\_id) | The VPC for security groups of the action runners. | `string` | `null` | no | | [webhook\_lambda\_apigateway\_access\_log\_settings](#input\_webhook\_lambda\_apigateway\_access\_log\_settings) | Access log settings for webhook API gateway. |
object({
destination_arn = string
format = string
})
| `null` | no | | [webhook\_lambda\_memory\_size](#input\_webhook\_lambda\_memory\_size) | Memory size limit in MB for webhook lambda. | `number` | `256` | no | | [webhook\_lambda\_s3\_key](#input\_webhook\_lambda\_s3\_key) | S3 key for webhook lambda function. Required if using S3 bucket to specify lambdas. | `string` | `null` | no | @@ -223,7 +289,8 @@ module "multi-runner" { | [binaries\_syncer\_map](#output\_binaries\_syncer\_map) | n/a | | [instance\_termination\_handler](#output\_instance\_termination\_handler) | n/a | | [instance\_termination\_watcher](#output\_instance\_termination\_watcher) | n/a | -| [runners\_map](#output\_runners\_map) | n/a | +| [runners\_map](#output\_runners\_map) | Stable v1 runner resources keyed by runner configuration. Entries retain the historical flat output shape. | +| [runners\_map\_v2](#output\_runners\_map\_v2) | Experimental v2 runner resources keyed by runner configuration. The orchestration object is canonical; scale\_up, scale\_down, and pool remain compatibility aliases. | | [ssm\_parameters](#output\_ssm\_parameters) | n/a | | [webhook](#output\_webhook) | n/a | diff --git a/modules/multi-runner/ami-housekeeper.tf b/modules/multi-runner/ami-housekeeper.tf index 385e6010c9..89365d275d 100644 --- a/modules/multi-runner/ami-housekeeper.tf +++ b/modules/multi-runner/ami-housekeeper.tf @@ -1,35 +1,35 @@ module "ami_housekeeper" { - count = var.enable_ami_housekeeper ? 1 : 0 + count = try(local.translated_experimental.compute_provider.ec2.ami.housekeeper.enabled, false) ? 1 : 0 source = "../ami-housekeeper" prefix = var.prefix - tags = local.tags + tags = merge(local.translated_experimental.tags, { "ghr:environment" = var.prefix }) aws_partition = var.aws_partition - lambda_zip = var.ami_housekeeper_lambda_zip - lambda_s3_bucket = var.lambda_s3_bucket - lambda_s3_key = var.ami_housekeeper_lambda_s3_key - lambda_s3_object_version = var.ami_housekeeper_lambda_s3_object_version + lambda_zip = local.translated_experimental.compute_provider.ec2.ami.housekeeper.artifact.zip + lambda_s3_bucket = local.translated_experimental.compute_provider.ec2.ami.housekeeper.artifact.s3 == null ? null : local.translated_experimental.lambda.artifact.s3.bucket + lambda_s3_key = try(local.translated_experimental.compute_provider.ec2.ami.housekeeper.artifact.s3.key, null) + lambda_s3_object_version = try(local.translated_experimental.compute_provider.ec2.ami.housekeeper.artifact.s3.object_version, null) - lambda_architecture = var.lambda_architecture - lambda_principals = var.lambda_principals - lambda_runtime = var.lambda_runtime - lambda_security_group_ids = var.lambda_security_group_ids - lambda_subnet_ids = var.lambda_subnet_ids - lambda_memory_size = var.ami_housekeeper_lambda_memory_size - lambda_timeout = var.ami_housekeeper_lambda_timeout - lambda_tags = var.lambda_tags - tracing_config = var.tracing_config + lambda_architecture = local.translated_experimental.lambda.architecture + lambda_principals = local.translated_experimental.lambda.principals + lambda_runtime = local.translated_experimental.lambda.runtime + lambda_security_group_ids = local.translated_experimental.lambda.security_group_ids + lambda_subnet_ids = local.translated_experimental.lambda.subnet_ids + lambda_memory_size = local.translated_experimental.compute_provider.ec2.ami.housekeeper.lambda.memory_size + lambda_timeout = local.translated_experimental.compute_provider.ec2.ami.housekeeper.lambda.timeout + lambda_tags = local.translated_experimental.lambda.tags + tracing_config = local.translated_experimental.observability.tracing - logging_retention_in_days = var.logging_retention_in_days - logging_kms_key_id = var.logging_kms_key_id - log_class = var.log_class - log_level = var.log_level + logging_retention_in_days = local.translated_experimental.observability.logs.retention_in_days + logging_kms_key_id = local.translated_experimental.observability.logs.kms_key_id + log_class = local.translated_experimental.observability.logs.class + log_level = local.translated_experimental.observability.logs.level - role_path = var.role_path - role_permissions_boundary = var.role_permissions_boundary + role_path = try(coalesce(local.translated_experimental.lambda.role.path, local.translated_experimental.roles.path), null) + role_permissions_boundary = try(coalesce(local.translated_experimental.lambda.role.permissions_boundary, local.translated_experimental.roles.permissions_boundary), null) - cleanup_config = var.ami_housekeeper_cleanup_config - lambda_schedule_expression = var.ami_housekeeper_lambda_schedule_expression + cleanup_config = local.translated_experimental.compute_provider.ec2.ami.housekeeper.cleanup_config + lambda_schedule_expression = local.translated_experimental.compute_provider.ec2.ami.housekeeper.schedule.expression } diff --git a/modules/multi-runner/compute-provider.tf b/modules/multi-runner/compute-provider.tf new file mode 100644 index 0000000000..5e94067e8c --- /dev/null +++ b/modules/multi-runner/compute-provider.tf @@ -0,0 +1,16 @@ +locals { + compute_provider_types = { + for runner_key, runner_config in local.translated_experimental_base.multi_runner_config : runner_key => one([ + for provider_type, provider_config in runner_config.compute_provider : provider_type + if provider_config != null + ]) + } + + runner_config_by_provider = { + for provider_type in toset(values(local.compute_provider_types)) : + provider_type => { + for runner_key, runner_config in local.translated_experimental_base.multi_runner_config : runner_key => runner_config + if local.compute_provider_types[runner_key] == provider_type + } + } +} diff --git a/modules/multi-runner/config.experimental.translation.tf b/modules/multi-runner/config.experimental.translation.tf new file mode 100644 index 0000000000..bf3f5ff607 --- /dev/null +++ b/modules/multi-runner/config.experimental.translation.tf @@ -0,0 +1,820 @@ +# Project stable v1 inputs into the experimental schema, then resolve every +# runner configuration against the experimental global defaults. The base object remains +# schema-compatible with var.experimental; the final canonical object adds +# effective per-configuration fields and the resource-backed binary distribution consumed +# by downstream runner modules. +locals { + # A non-empty experimental map is the module-level v2 opt-in. Stable v1 and + # experimental v2 resources must never be selected in the same deployment. + use_multi_runner_config_v2 = length(var.experimental.multi_runner_config) > 0 + + raw_translated_experimental = local.use_multi_runner_config_v2 ? var.experimental : { + tags = var.tags + + roles = { + path = var.role_path + permissions_boundary = var.role_permissions_boundary + } + + runner = { + os = null + architecture = null + disable_default_labels = false + extra_labels = [] + group_name = "Default" + name_prefix = "" + run_as_root = false + run_as = "ec2-user" + auto_update_disabled = false + tags = {} + hooks = { + job_started = "" + job_completed = "" + } + iam = { + role = null + managed_policy_arns = {} + additional_trust_policy_json = null + path = null + permissions_boundary = null + } + } + + github = { + app = var.github_app + additional_apps = var.additional_github_apps + enterprise_server = { + url = var.ghes_url + ssl_verify = var.ghes_ssl_verify + } + user_agent = var.user_agent + } + + lambda = { + artifact = { + s3 = { + bucket = var.lambda_s3_bucket + } + } + runtime = var.lambda_runtime + architecture = var.lambda_architecture + principals = var.lambda_principals + subnet_ids = var.lambda_subnet_ids + security_group_ids = var.lambda_security_group_ids + tags = var.lambda_tags + role = { + path = null + permissions_boundary = null + } + } + + orchestration = { + webhook = { + queue_selection_strategy = var.queue_selection_strategy + eventbridge = var.eventbridge + matcher_config_parameter_store_tier = var.matcher_config_parameter_store_tier + runner = { + boot_time_in_minutes = 5 + ephemeral = false + jit_config_enabled = null + maximum_count = null + } + github = { + repository_white_list = var.repository_white_list + } + lambda = { + artifact = { + zip = var.lambda_s3_bucket == null ? var.runners_lambda_zip : null + s3 = var.lambda_s3_bucket == null ? null : { + key = var.runners_lambda_s3_key + object_version = var.runners_lambda_s3_object_version + } + } + scale = { + up = { + memory_size = var.scale_up_lambda_memory_size + timeout = var.runners_scale_up_lambda_timeout + reserved_concurrent_executions = 1 + job_queued_check_enabled = null + event_source_mapping = { + batch_size = var.lambda_event_source_mapping_batch_size + maximum_batching_window_in_seconds = var.lambda_event_source_mapping_maximum_batching_window_in_seconds + } + tags = {} + } + down = { + memory_size = var.scale_down_lambda_memory_size + timeout = var.runners_scale_down_lambda_timeout + schedule_expression = "cron(*/5 * * * ? *)" + minimum_running_time_in_minutes = null + idle_config = [] + tags = {} + } + } + webhook = { + artifact = { + zip = var.lambda_s3_bucket == null ? var.webhook_lambda_zip : null + s3 = var.lambda_s3_bucket == null ? null : { + key = var.webhook_lambda_s3_key + object_version = var.webhook_lambda_s3_object_version + } + } + api_gateway_access_log_settings = var.webhook_lambda_apigateway_access_log_settings + memory_size = var.webhook_lambda_memory_size + timeout = var.webhook_lambda_timeout + tags = {} + } + pool = { + memory_size = 512 + timeout = var.pool_lambda_timeout + reserved_concurrent_executions = var.pool_lambda_reserved_concurrent_executions + config = [] + include_busy_runners = false + runner_owner = null + tags = {} + } + } + queue = { + delay_webhook_event = 30 + job_queue_retention_in_seconds = 86400 + visibility_timeout_seconds = var.runners_scale_up_lambda_timeout + redrive_build_queue = { + enabled = false + maxReceiveCount = null + } + tags = {} + encryption = var.queue_encryption + } + } + } + + ssm = { + paths = { + root = "/${var.ssm_paths.root}/${var.prefix}" + app = var.ssm_paths.app + webhook = var.ssm_paths.webhook + tokens = "${var.ssm_paths.runners}/tokens" + config = "${var.ssm_paths.runners}/config" + } + kms_key_id = var.kms_key_arn + tags = {} + parameters = { + tags = var.parameter_store_tags + } + housekeeper = { + schedule_expression = var.runners_ssm_housekeeper.schedule_expression + state = var.runners_ssm_housekeeper.enabled ? "ENABLED" : "DISABLED" + tags = {} + lambda = { + artifact = { + zip = var.lambda_s3_bucket == null ? var.runners_lambda_zip : null + s3 = var.lambda_s3_bucket == null ? null : { + key = var.runners_lambda_s3_key + object_version = var.runners_lambda_s3_object_version + } + } + memory_size = var.runners_ssm_housekeeper.lambda_memory_size + timeout = var.runners_ssm_housekeeper.lambda_timeout + } + config = { + tokenPath = var.runners_ssm_housekeeper.config.tokenPath + minimumDaysOld = var.runners_ssm_housekeeper.config.minimumDaysOld + dryRun = var.runners_ssm_housekeeper.config.dryRun + } + } + } + + observability = { + logs = { + level = var.log_level + retention_in_days = var.logging_retention_in_days + kms_key_id = var.logging_kms_key_id + class = var.log_class + tags = {} + } + tracing = var.tracing_config + metrics = { + enable = var.metrics.enable + namespace = var.metrics.namespace + metric = { + enable_github_app_rate_limit = var.metrics.metric.enable_github_app_rate_limit + enable_job_retry = var.metrics.metric.enable_job_retry + enable_spot_termination = true + enable_spot_termination_warning = var.metrics.metric.enable_spot_termination_warning + } + } + } + + compute_provider = { + ec2 = { + vpc_id = var.vpc_id + subnet_ids = var.subnet_ids + managed_security_group_enabled = var.enable_managed_runner_security_group + egress_rules = var.runner_egress_rules + additional_security_group_ids = var.runner_additional_security_group_ids + cloudwatch_agent = { + config = var.cloudwatch_config + } + instance_profile_path = var.instance_profile_path + key_name = var.key_name + associate_public_ipv4_address = var.associate_public_ipv4_address + tags = {} + ami = { + housekeeper = { + enabled = var.enable_ami_housekeeper + cleanup_config = var.ami_housekeeper_cleanup_config + artifact = { + zip = var.lambda_s3_bucket == null ? var.ami_housekeeper_lambda_zip : null + s3 = var.lambda_s3_bucket == null ? null : { + key = var.ami_housekeeper_lambda_s3_key + object_version = var.ami_housekeeper_lambda_s3_object_version + } + } + lambda = { + memory_size = var.ami_housekeeper_lambda_memory_size + timeout = var.ami_housekeeper_lambda_timeout + } + schedule = { + expression = var.ami_housekeeper_lambda_schedule_expression + } + } + } + instance_termination_watcher = { + enabled = var.instance_termination_watcher.enable + features = var.instance_termination_watcher.features + enable_runner_deregistration = var.instance_termination_watcher.enable_runner_deregistration + environment_variables = var.instance_termination_watcher.environment_variables + artifact = { + zip = var.lambda_s3_bucket == null ? var.instance_termination_watcher.zip : null + s3 = var.lambda_s3_bucket == null ? null : { + key = var.instance_termination_watcher.s3_key + object_version = var.instance_termination_watcher.s3_object_version + } + } + lambda = { + memory_size = var.instance_termination_watcher.memory_size + timeout = var.instance_termination_watcher.timeout + } + } + runner_binaries = { + enabled = true + s3 = { + encryption = { + enabled = var.runner_binaries_s3_sse_configuration != null + bucket_key_enabled = try(var.runner_binaries_s3_sse_configuration.rule.bucket_key_enabled, null) + sse_algorithm = try(var.runner_binaries_s3_sse_configuration.rule.apply_server_side_encryption_by_default.sse_algorithm, "AES256") + kms_master_key_id = try(var.runner_binaries_s3_sse_configuration.rule.apply_server_side_encryption_by_default.kms_master_key_id, null) + } + tags = var.runner_binaries_s3_tags + versioning = var.runner_binaries_s3_versioning + logging = { + bucket = null + prefix = null + } + } + syncer = { + artifact = { + zip = var.lambda_s3_bucket == null ? var.runner_binaries_syncer_lambda_zip : null + s3 = var.lambda_s3_bucket == null ? null : { + key = var.syncer_lambda_s3_key + object_version = var.syncer_lambda_s3_object_version + } + } + lambda = { + memory_size = var.runner_binaries_syncer_memory_size + timeout = var.runner_binaries_syncer_lambda_timeout + } + schedule = { + expression = "cron(27 * * * ? *)" + state = var.state_event_rule_binaries_syncer + } + } + } + } + } + + multi_runner_config = { + for k, v in var.multi_runner_config : k => { + tags = {} + + runner = { + os = v.runner_config.runner_os + architecture = v.runner_config.runner_architecture + disable_default_labels = v.runner_config.runner_disable_default_labels + extra_labels = v.runner_config.runner_extra_labels + group_name = v.runner_config.runner_group_name + name_prefix = v.runner_config.runner_name_prefix + run_as_root = v.runner_config.runner_as_root + run_as = v.runner_config.runner_run_as + auto_update_disabled = v.runner_config.disable_runner_autoupdate + tags = {} + hooks = { + job_started = v.runner_config.runner_hook_job_started + job_completed = v.runner_config.runner_hook_job_completed + } + iam = { + role = v.runner_config.iam_overrides.override_runner_role == true ? { + arn = v.runner_config.iam_overrides.runner_role_arn + } : null + managed_policy_arns = { + for policy_index, policy_arn in v.runner_config.runner_iam_role_managed_policy_arns : + "legacy-${policy_index}" => policy_arn + } + additional_trust_policy_json = null + path = null + permissions_boundary = null + } + } + + lambda = { + runtime = null + architecture = null + subnet_ids = null + security_group_ids = null + tags = {} + role = { + path = null + permissions_boundary = null + } + } + + orchestration = { + webhook = { + runner = { + boot_time_in_minutes = v.runner_config.runner_boot_time_in_minutes + ephemeral = v.runner_config.enable_ephemeral_runners + jit_config_enabled = v.runner_config.enable_jit_config + maximum_count = v.runner_config.runners_maximum_count + } + + github = { + organization_runners = v.runner_config.enable_organization_runners + } + + matcherConfig = v.matcherConfig + + lambda = { + scale = { + up = { + memory_size = null + timeout = null + reserved_concurrent_executions = v.runner_config.scale_up_reserved_concurrent_executions + job_queued_check_enabled = v.runner_config.enable_job_queued_check + event_source_mapping = { + batch_size = v.runner_config.lambda_event_source_mapping_batch_size + maximum_batching_window_in_seconds = v.runner_config.lambda_event_source_mapping_maximum_batching_window_in_seconds + } + tags = {} + } + down = { + memory_size = null + timeout = null + schedule_expression = v.runner_config.scale_down_schedule_expression + minimum_running_time_in_minutes = v.runner_config.minimum_running_time_in_minutes + idle_config = v.runner_config.idle_config + tags = {} + } + } + pool = { + memory_size = null + timeout = null + reserved_concurrent_executions = null + config = v.runner_config.pool_config + include_busy_runners = false + runner_owner = v.runner_config.pool_runner_owner + tags = {} + } + } + + queue = { + delay_webhook_event = v.runner_config.delay_webhook_event + job_queue_retention_in_seconds = v.runner_config.job_queue_retention_in_seconds + visibility_timeout_seconds = var.runners_scale_up_lambda_timeout + redrive_build_queue = v.redrive_build_queue + tags = {} + } + + job_retry = { + enabled = v.runner_config.job_retry.enable + delay_in_seconds = v.runner_config.job_retry.delay_in_seconds + delay_backoff = v.runner_config.job_retry.delay_backoff + max_attempts = v.runner_config.job_retry.max_attempts + tags = {} + lambda = { + memory_size = v.runner_config.job_retry.lambda_memory_size + reserved_concurrent_executions = 1 + timeout = v.runner_config.job_retry.lambda_timeout + } + } + } + } + + ssm = { + paths = { + root = null + tokens = null + config = null + } + tags = {} + parameters = { + tags = {} + } + housekeeper = { + schedule_expression = null + state = null + tags = {} + lambda = { + artifact = { + zip = null + s3 = null + } + memory_size = null + timeout = null + } + config = { + tokenPath = null + minimumDaysOld = null + dryRun = null + } + } + } + + observability = { + logs = { + level = null + retention_in_days = null + kms_key_id = null + class = null + tags = {} + } + tracing = { + mode = null + capture_http_requests = null + capture_error = null + } + metrics = { + enable = null + namespace = null + metric = { + enable_github_app_rate_limit = null + enable_job_retry = null + } + } + } + + compute_provider = { + ec2 = { + metadata_options = { + instance_metadata_tags = tostring(v.runner_config.runner_metadata_options["instance_metadata_tags"]) + http_endpoint = tostring(v.runner_config.runner_metadata_options["http_endpoint"]) + http_tokens = tostring(v.runner_config.runner_metadata_options["http_tokens"]) + http_put_response_hop_limit = tonumber(v.runner_config.runner_metadata_options["http_put_response_hop_limit"]) + } + ami = v.runner_config.ami == null ? null : { + filter = v.runner_config.ami.filter + owners = v.runner_config.ami.owners + id_ssm_parameter = v.runner_config.ami.id_ssm_parameter_arn == null ? null : { + arn = v.runner_config.ami.id_ssm_parameter_arn + } + kms_key = v.runner_config.ami.kms_key_arn == null ? null : { + arn = v.runner_config.ami.kms_key_arn + } + } + block_device_mappings = v.runner_config.block_device_mappings + create_service_linked_role_spot = v.runner_config.create_service_linked_role_spot + credit_specification = v.runner_config.credit_specification + ebs_optimized = v.runner_config.ebs_optimized + cloudwatch_agent = { + enabled = v.runner_config.enable_cloudwatch_agent + config = v.runner_config.cloudwatch_config + } + binaries_syncer = { + enabled = v.runner_config.enable_runner_binaries_syncer + } + detailed_monitoring_enabled = v.runner_config.enable_runner_detailed_monitoring + ssm_enabled = v.runner_config.enable_ssm_on_runners + user_data = { + enabled = v.runner_config.enable_userdata + template = v.runner_config.userdata_template + content = v.runner_config.userdata_content + pre_install = v.runner_config.userdata_pre_install + post_install = v.runner_config.userdata_post_install + debug_logging_enabled = false + } + instance_allocation_strategy = v.runner_config.instance_allocation_strategy + instance_max_spot_price = v.runner_config.instance_max_spot_price + instance_target_capacity_type = v.runner_config.instance_target_capacity_type + instance_type_priorities = v.runner_config.instance_type_priorities + instance_types = v.runner_config.instance_types + additional_security_group_ids = length(v.runner_config.runner_additional_security_group_ids) == 0 ? null : v.runner_config.runner_additional_security_group_ids + managed_security_group_enabled = null + egress_rules = null + instance_profile_path = null + key_name = null + associate_public_ipv4_address = null + instance_profile = v.runner_config.iam_overrides.override_instance_profile == true ? { + name = v.runner_config.iam_overrides.instance_profile_name + } : null + enable_on_demand_failover_for_errors = v.runner_config.enable_on_demand_failover_for_errors + scale_errors = v.runner_config.scale_errors + subnet_ids = v.runner_config.subnet_ids + vpc_id = v.runner_config.vpc_id + cpu_options = v.runner_config.cpu_options + placement = v.runner_config.placement + license_specifications = v.runner_config.license_specifications + use_dedicated_host = v.runner_config.use_dedicated_host + log_files = v.runner_config.runner_log_files + tags = v.runner_config.runner_ec2_tags + } + } + } + } + } +} + +locals { + translated_experimental_base = merge(local.raw_translated_experimental, { + multi_runner_config = { + for k, v in local.raw_translated_experimental.multi_runner_config : k => merge(v, { + tags = merge(local.raw_translated_experimental.tags, v.tags) + + runner = merge(v.runner, { + os = try(coalesce(v.runner.os, local.raw_translated_experimental.runner.os), null) + architecture = try(coalesce(v.runner.architecture, local.raw_translated_experimental.runner.architecture), null) + disable_default_labels = coalesce(v.runner.disable_default_labels, local.raw_translated_experimental.runner.disable_default_labels) + extra_labels = v.runner.extra_labels != null ? v.runner.extra_labels : local.raw_translated_experimental.runner.extra_labels + group_name = coalesce(v.runner.group_name, local.raw_translated_experimental.runner.group_name) + name_prefix = v.runner.name_prefix != null ? v.runner.name_prefix : local.raw_translated_experimental.runner.name_prefix + run_as_root = coalesce(v.runner.run_as_root, local.raw_translated_experimental.runner.run_as_root) + run_as = coalesce(v.runner.run_as, local.raw_translated_experimental.runner.run_as) + auto_update_disabled = coalesce(v.runner.auto_update_disabled, local.raw_translated_experimental.runner.auto_update_disabled) + tags = merge(local.raw_translated_experimental.runner.tags, v.runner.tags) + hooks = { + job_started = v.runner.hooks.job_started != null ? v.runner.hooks.job_started : local.raw_translated_experimental.runner.hooks.job_started + job_completed = v.runner.hooks.job_completed != null ? v.runner.hooks.job_completed : local.raw_translated_experimental.runner.hooks.job_completed + } + iam = { + role = try(coalesce(v.runner.iam.role, local.raw_translated_experimental.runner.iam.role), null) + managed_policy_arns = v.runner.iam.role != null ? ( + v.runner.iam.managed_policy_arns != null ? v.runner.iam.managed_policy_arns : {} + ) : ( + v.runner.iam.managed_policy_arns != null ? v.runner.iam.managed_policy_arns : local.raw_translated_experimental.runner.iam.managed_policy_arns + ) + additional_trust_policy_json = v.runner.iam.role != null ? v.runner.iam.additional_trust_policy_json : try(coalesce(v.runner.iam.additional_trust_policy_json, local.raw_translated_experimental.runner.iam.additional_trust_policy_json), null) + path = try(coalesce(v.runner.iam.path, local.raw_translated_experimental.runner.iam.path, local.raw_translated_experimental.roles.path), null) + permissions_boundary = try(coalesce(v.runner.iam.permissions_boundary, local.raw_translated_experimental.runner.iam.permissions_boundary, local.raw_translated_experimental.roles.permissions_boundary), null) + } + }) + + lambda = merge(v.lambda, { + runtime = coalesce(v.lambda.runtime, local.raw_translated_experimental.lambda.runtime) + architecture = coalesce(v.lambda.architecture, local.raw_translated_experimental.lambda.architecture) + subnet_ids = v.lambda.subnet_ids != null ? v.lambda.subnet_ids : local.raw_translated_experimental.lambda.subnet_ids + security_group_ids = v.lambda.security_group_ids != null ? v.lambda.security_group_ids : local.raw_translated_experimental.lambda.security_group_ids + tags = merge(local.raw_translated_experimental.lambda.tags, v.lambda.tags) + role = { + path = try(coalesce( + v.lambda.role.path, + local.raw_translated_experimental.lambda.role.path, + local.raw_translated_experimental.roles.path, + ), null) + permissions_boundary = try(coalesce( + v.lambda.role.permissions_boundary, + local.raw_translated_experimental.lambda.role.permissions_boundary, + local.raw_translated_experimental.roles.permissions_boundary, + ), null) + } + }) + + orchestration = { + webhook = v.orchestration.webhook == null ? null : merge(v.orchestration.webhook, { + runner = { + boot_time_in_minutes = coalesce( + v.orchestration.webhook.runner.boot_time_in_minutes, + local.raw_translated_experimental.orchestration.webhook.runner.boot_time_in_minutes, + ) + ephemeral = coalesce( + v.orchestration.webhook.runner.ephemeral, + local.raw_translated_experimental.orchestration.webhook.runner.ephemeral, + ) + jit_config_enabled = try(coalesce( + v.orchestration.webhook.runner.jit_config_enabled, + local.raw_translated_experimental.orchestration.webhook.runner.jit_config_enabled, + ), null) + maximum_count = try(coalesce( + v.orchestration.webhook.runner.maximum_count, + local.raw_translated_experimental.orchestration.webhook.runner.maximum_count, + ), null) + } + + lambda = merge(v.orchestration.webhook.lambda, { + scale = merge(v.orchestration.webhook.lambda.scale, { + up = merge(v.orchestration.webhook.lambda.scale.up, { + memory_size = coalesce(v.orchestration.webhook.lambda.scale.up.memory_size, local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.memory_size) + timeout = coalesce(v.orchestration.webhook.lambda.scale.up.timeout, local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.timeout) + reserved_concurrent_executions = coalesce(v.orchestration.webhook.lambda.scale.up.reserved_concurrent_executions, local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.reserved_concurrent_executions) + job_queued_check_enabled = try(coalesce(v.orchestration.webhook.lambda.scale.up.job_queued_check_enabled, local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.job_queued_check_enabled), null) + event_source_mapping = { + batch_size = coalesce( + v.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size, + local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size, + ) + maximum_batching_window_in_seconds = coalesce( + v.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds, + local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds, + ) + } + tags = merge(local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.tags, v.orchestration.webhook.lambda.scale.up.tags) + }) + down = merge(v.orchestration.webhook.lambda.scale.down, { + memory_size = coalesce(v.orchestration.webhook.lambda.scale.down.memory_size, local.raw_translated_experimental.orchestration.webhook.lambda.scale.down.memory_size) + timeout = coalesce(v.orchestration.webhook.lambda.scale.down.timeout, local.raw_translated_experimental.orchestration.webhook.lambda.scale.down.timeout) + schedule_expression = coalesce(v.orchestration.webhook.lambda.scale.down.schedule_expression, local.raw_translated_experimental.orchestration.webhook.lambda.scale.down.schedule_expression) + minimum_running_time_in_minutes = try(coalesce(v.orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes, local.raw_translated_experimental.orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes), null) + idle_config = v.orchestration.webhook.lambda.scale.down.idle_config != null ? v.orchestration.webhook.lambda.scale.down.idle_config : local.raw_translated_experimental.orchestration.webhook.lambda.scale.down.idle_config + tags = merge(local.raw_translated_experimental.orchestration.webhook.lambda.scale.down.tags, v.orchestration.webhook.lambda.scale.down.tags) + }) + }) + pool = merge(v.orchestration.webhook.lambda.pool, { + memory_size = coalesce(v.orchestration.webhook.lambda.pool.memory_size, local.raw_translated_experimental.orchestration.webhook.lambda.pool.memory_size) + timeout = coalesce(v.orchestration.webhook.lambda.pool.timeout, local.raw_translated_experimental.orchestration.webhook.lambda.pool.timeout) + reserved_concurrent_executions = coalesce(v.orchestration.webhook.lambda.pool.reserved_concurrent_executions, local.raw_translated_experimental.orchestration.webhook.lambda.pool.reserved_concurrent_executions) + config = v.orchestration.webhook.lambda.pool.config != null ? v.orchestration.webhook.lambda.pool.config : local.raw_translated_experimental.orchestration.webhook.lambda.pool.config + include_busy_runners = coalesce(v.orchestration.webhook.lambda.pool.include_busy_runners, local.raw_translated_experimental.orchestration.webhook.lambda.pool.include_busy_runners) + runner_owner = try(coalesce(v.orchestration.webhook.lambda.pool.runner_owner, local.raw_translated_experimental.orchestration.webhook.lambda.pool.runner_owner), null) + tags = merge(local.raw_translated_experimental.orchestration.webhook.lambda.pool.tags, v.orchestration.webhook.lambda.pool.tags) + }) + }) + + queue = merge(v.orchestration.webhook.queue, { + delay_webhook_event = coalesce(v.orchestration.webhook.queue.delay_webhook_event, local.raw_translated_experimental.orchestration.webhook.queue.delay_webhook_event) + job_queue_retention_in_seconds = coalesce(v.orchestration.webhook.queue.job_queue_retention_in_seconds, local.raw_translated_experimental.orchestration.webhook.queue.job_queue_retention_in_seconds) + visibility_timeout_seconds = coalesce(v.orchestration.webhook.queue.visibility_timeout_seconds, local.raw_translated_experimental.orchestration.webhook.queue.visibility_timeout_seconds) + redrive_build_queue = { + enabled = try( + coalesce(try(v.orchestration.webhook.queue.redrive_build_queue.enabled, null), local.raw_translated_experimental.orchestration.webhook.queue.redrive_build_queue.enabled), + local.raw_translated_experimental.orchestration.webhook.queue.redrive_build_queue.enabled, + ) + maxReceiveCount = try( + coalesce(try(v.orchestration.webhook.queue.redrive_build_queue.maxReceiveCount, null), local.raw_translated_experimental.orchestration.webhook.queue.redrive_build_queue.maxReceiveCount), + null, + ) + } + tags = merge(local.raw_translated_experimental.orchestration.webhook.queue.tags, v.orchestration.webhook.queue.tags) + }) + }) + } + + ssm = merge(v.ssm, { + paths = { + root = "${trimsuffix(coalesce( + v.ssm.paths.root, + local.raw_translated_experimental.ssm.paths.root, + "/github-action-runners/${var.prefix}", + ), "/")}/${k}" + tokens = coalesce(v.ssm.paths.tokens, local.raw_translated_experimental.ssm.paths.tokens) + config = coalesce(v.ssm.paths.config, local.raw_translated_experimental.ssm.paths.config) + } + tags = merge(local.raw_translated_experimental.ssm.tags, v.ssm.tags) + parameters = { + tags = merge(local.raw_translated_experimental.ssm.parameters.tags, v.ssm.parameters.tags) + } + housekeeper = { + schedule_expression = coalesce(v.ssm.housekeeper.schedule_expression, local.raw_translated_experimental.ssm.housekeeper.schedule_expression) + state = coalesce(v.ssm.housekeeper.state, local.raw_translated_experimental.ssm.housekeeper.state) + tags = merge(local.raw_translated_experimental.ssm.housekeeper.tags, v.ssm.housekeeper.tags) + lambda = { + artifact = { + zip = v.ssm.housekeeper.lambda.artifact.s3 != null ? null : try(coalesce( + v.ssm.housekeeper.lambda.artifact.zip, + local.raw_translated_experimental.ssm.housekeeper.lambda.artifact.zip, + ), null) + s3 = v.ssm.housekeeper.lambda.artifact.s3 != null ? v.ssm.housekeeper.lambda.artifact.s3 : ( + v.ssm.housekeeper.lambda.artifact.zip != null ? null : local.raw_translated_experimental.ssm.housekeeper.lambda.artifact.s3 + ) + } + memory_size = coalesce(v.ssm.housekeeper.lambda.memory_size, local.raw_translated_experimental.ssm.housekeeper.lambda.memory_size) + timeout = coalesce(v.ssm.housekeeper.lambda.timeout, local.raw_translated_experimental.ssm.housekeeper.lambda.timeout) + } + config = { + tokenPath = try(coalesce( + v.ssm.housekeeper.config.tokenPath, + local.raw_translated_experimental.ssm.housekeeper.config.tokenPath, + ), null) + minimumDaysOld = coalesce(v.ssm.housekeeper.config.minimumDaysOld, local.raw_translated_experimental.ssm.housekeeper.config.minimumDaysOld) + dryRun = coalesce(v.ssm.housekeeper.config.dryRun, local.raw_translated_experimental.ssm.housekeeper.config.dryRun) + } + } + }) + + observability = { + logs = { + level = coalesce(v.observability.logs.level, local.raw_translated_experimental.observability.logs.level) + retention_in_days = coalesce(v.observability.logs.retention_in_days, local.raw_translated_experimental.observability.logs.retention_in_days) + kms_key_id = try(coalesce(v.observability.logs.kms_key_id, local.raw_translated_experimental.observability.logs.kms_key_id), null) + class = coalesce(v.observability.logs.class, local.raw_translated_experimental.observability.logs.class) + tags = merge(local.raw_translated_experimental.observability.logs.tags, v.observability.logs.tags) + } + tracing = { + mode = try(coalesce( + v.observability.tracing.mode, + local.raw_translated_experimental.observability.tracing.mode, + ), null) + capture_http_requests = coalesce(v.observability.tracing.capture_http_requests, local.raw_translated_experimental.observability.tracing.capture_http_requests) + capture_error = coalesce(v.observability.tracing.capture_error, local.raw_translated_experimental.observability.tracing.capture_error) + } + metrics = { + enable = coalesce(v.observability.metrics.enable, local.raw_translated_experimental.observability.metrics.enable) + namespace = coalesce(v.observability.metrics.namespace, local.raw_translated_experimental.observability.metrics.namespace) + metric = { + enable_github_app_rate_limit = coalesce( + v.observability.metrics.metric.enable_github_app_rate_limit, + local.raw_translated_experimental.observability.metrics.metric.enable_github_app_rate_limit, + ) + enable_job_retry = coalesce( + v.observability.metrics.metric.enable_job_retry, + local.raw_translated_experimental.observability.metrics.metric.enable_job_retry, + ) + } + } + } + + compute_provider = { + ec2 = v.compute_provider.ec2 == null ? null : merge(v.compute_provider.ec2, { + vpc_id = try(coalesce(v.compute_provider.ec2.vpc_id, local.raw_translated_experimental.compute_provider.ec2.vpc_id), null) + subnet_ids = v.compute_provider.ec2.subnet_ids != null ? v.compute_provider.ec2.subnet_ids : local.raw_translated_experimental.compute_provider.ec2.subnet_ids + managed_security_group_enabled = coalesce(v.compute_provider.ec2.managed_security_group_enabled, local.raw_translated_experimental.compute_provider.ec2.managed_security_group_enabled) + egress_rules = v.compute_provider.ec2.egress_rules != null ? v.compute_provider.ec2.egress_rules : local.raw_translated_experimental.compute_provider.ec2.egress_rules + additional_security_group_ids = v.compute_provider.ec2.additional_security_group_ids != null ? v.compute_provider.ec2.additional_security_group_ids : local.raw_translated_experimental.compute_provider.ec2.additional_security_group_ids + instance_profile_path = try(coalesce(v.compute_provider.ec2.instance_profile_path, local.raw_translated_experimental.compute_provider.ec2.instance_profile_path), null) + key_name = try(coalesce(v.compute_provider.ec2.key_name, local.raw_translated_experimental.compute_provider.ec2.key_name), null) + associate_public_ipv4_address = coalesce(v.compute_provider.ec2.associate_public_ipv4_address, local.raw_translated_experimental.compute_provider.ec2.associate_public_ipv4_address) + cloudwatch_agent = merge(v.compute_provider.ec2.cloudwatch_agent, { + config = try(coalesce(v.compute_provider.ec2.cloudwatch_agent.config, local.raw_translated_experimental.compute_provider.ec2.cloudwatch_agent.config), null) + }) + binaries_syncer = { + enabled = coalesce(v.compute_provider.ec2.binaries_syncer.enabled, local.raw_translated_experimental.compute_provider.ec2.runner_binaries.enabled) + } + tags = merge(local.raw_translated_experimental.compute_provider.ec2.tags, v.compute_provider.ec2.tags) + }) + } + }) + } + }) +} + +locals { + translated_experimental = merge(local.translated_experimental_base, { + multi_runner_config = { + for k, v in local.translated_experimental_base.multi_runner_config : k => merge(v, { + runner = merge(v.runner, { + labels = sort(setunion( + v.runner.disable_default_labels ? [] : compact([ + "self-hosted", + v.runner.os, + v.runner.architecture, + ]), + v.orchestration.webhook == null ? [] : flatten(v.orchestration.webhook.matcherConfig.labelMatchers), + compact(v.runner.extra_labels), + )) + }) + + github = { + enterprise_server = local.translated_experimental_base.github.enterprise_server + user_agent = local.translated_experimental_base.github.user_agent + } + + lambda = merge(v.lambda, { + artifact = local.translated_experimental_base.lambda.artifact + principals = local.translated_experimental_base.lambda.principals + }) + + orchestration = { + webhook = v.orchestration.webhook == null ? null : merge(v.orchestration.webhook, { + queue = merge(v.orchestration.webhook.queue, { + kms_key_id = local.translated_experimental_base.orchestration.webhook.queue.encryption.kms_master_key_id + }) + + lambda = merge(v.orchestration.webhook.lambda, { + artifact = local.translated_experimental_base.orchestration.webhook.lambda.artifact + }) + }) + } + + ssm = merge(v.ssm, { + kms_key_id = local.translated_experimental_base.ssm.kms_key_id + }) + + compute_provider = merge(v.compute_provider, { + ec2 = v.compute_provider.ec2 == null ? null : merge(v.compute_provider.ec2, { + binaries_syncer = merge(v.compute_provider.ec2.binaries_syncer, { + s3 = v.compute_provider.ec2.binaries_syncer.enabled ? local.runner_binaries_by_os_and_arch_map[ + "${v.runner.os}_${v.runner.architecture}" + ] : null + }) + }) + }) + }) + } + }) +} diff --git a/modules/multi-runner/main.tf b/modules/multi-runner/main.tf index bd96e30847..8d92647278 100644 --- a/modules/multi-runner/main.tf +++ b/modules/multi-runner/main.tf @@ -1,10 +1,6 @@ locals { - tags = merge(var.tags, { - "ghr:environment" = var.prefix - }) - - primary_app_id = coalesce(var.github_app.id_ssm, module.ssm.parameters.github_app_id) - primary_app_key_base64 = coalesce(var.github_app.key_base64_ssm, module.ssm.parameters.github_app_key_base64) + primary_app_id = coalesce(local.translated_experimental.github.app.id_ssm, module.ssm.parameters.github_app_id) + primary_app_key_base64 = coalesce(local.translated_experimental.github.app.key_base64_ssm, module.ssm.parameters.github_app_key_base64) github_app_parameters = { id = concat( @@ -19,24 +15,18 @@ locals { [null], [for p in module.ssm.additional_app_parameters : p.installation_id] ) - webhook_secret = coalesce(var.github_app.webhook_secret_ssm, module.ssm.parameters.github_app_webhook_secret) + webhook_secret = coalesce(local.translated_experimental.github.app.webhook_secret_ssm, module.ssm.parameters.github_app_webhook_secret) } - runner_extra_labels = { for k, v in var.multi_runner_config : k => sort(setunion(flatten(v.matcherConfig.labelMatchers), compact(v.runner_config.runner_extra_labels))) } - - runner_config = { for k, v in var.multi_runner_config : k => merge( - { - id = aws_sqs_queue.queued_builds[k].id - arn = aws_sqs_queue.queued_builds[k].arn - url = aws_sqs_queue.queued_builds[k].url - }, - merge(v, { runner_config = merge(v.runner_config, { runner_extra_labels = local.runner_extra_labels[k] }) }), - ) } - - tmp_distinct_list_unique_os_and_arch = distinct([for i, config in local.runner_config : { "os_type" : config.runner_config.runner_os, "architecture" : config.runner_config.runner_architecture } if config.runner_config.enable_runner_binaries_syncer]) - unique_os_and_arch = { for i, v in local.tmp_distinct_list_unique_os_and_arch : "${v.os_type}_${v.architecture}" => v } - - ssm_root_path = "/${var.ssm_paths.root}/${var.prefix}" + # Keep a concrete map type when unrelated configuration values are unknown until apply. + tmp_distinct_list_unique_os_and_arch = distinct([ + for _, config in lookup(local.runner_config_by_provider, "ec2", {}) : { + "os_type" : config.runner.os, + "architecture" : config.runner.architecture + } + if config.compute_provider.ec2.binaries_syncer.enabled + ]) + unique_os_and_arch = { for _, v in local.tmp_distinct_list_unique_os_and_arch : "${v.os_type}_${v.architecture}" => v } } resource "random_string" "random" { diff --git a/modules/multi-runner/outputs.tf b/modules/multi-runner/outputs.tf index 50adb7fe46..9576a45c68 100644 --- a/modules/multi-runner/outputs.tf +++ b/modules/multi-runner/outputs.tf @@ -1,5 +1,6 @@ output "runners_map" { + description = "Stable v1 runner resources keyed by runner configuration. Entries retain the historical flat output shape." value = { for runner_key, runner in module.runners : runner_key => { launch_template_name = runner.launch_template.name launch_template_id = runner.launch_template.id @@ -21,6 +22,19 @@ output "runners_map" { } } +output "runners_map_v2" { + description = "Experimental v2 runner resources keyed by runner configuration. The orchestration object is canonical; scale_up, scale_down, and pool remain compatibility aliases." + value = { for runner_key, runner in module.runner_configs : runner_key => { + runner = runner.runner + orchestration = runner.orchestration + scale_up = runner.scale_up + scale_down = runner.scale_down + pool = runner.pool + provider = runner.provider + } + } +} + output "binaries_syncer_map" { value = { for runner_binary_key, runner_binary in module.runner_binaries : runner_binary_key => { lambda = runner_binary.lambda @@ -39,8 +53,8 @@ output "webhook" { lambda_role = module.webhook.role endpoint = "${module.webhook.gateway.api_endpoint}/${module.webhook.endpoint_relative_path}" webhook = module.webhook.webhook - dispatcher = var.eventbridge.enable ? module.webhook.dispatcher : null - eventbridge = var.eventbridge.enable ? module.webhook.eventbridge : null + dispatcher = local.translated_experimental.orchestration.webhook.eventbridge.enable ? module.webhook.dispatcher : null + eventbridge = local.translated_experimental.orchestration.webhook.eventbridge.enable ? module.webhook.eventbridge : null } } @@ -67,7 +81,7 @@ output "ssm_parameters" { } output "instance_termination_watcher" { - value = var.instance_termination_watcher.enable && var.instance_termination_watcher.features.enable_spot_termination_notification_watcher ? { + value = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enabled && local.translated_experimental.compute_provider.ec2.instance_termination_watcher.features.enable_spot_termination_notification_watcher ? { lambda = module.instance_termination_watcher[0].spot_termination_notification.lambda lambda_log_group = module.instance_termination_watcher[0].spot_termination_notification.lambda_log_group lambda_role = module.instance_termination_watcher[0].spot_termination_notification.lambda_role @@ -75,7 +89,7 @@ output "instance_termination_watcher" { } output "instance_termination_handler" { - value = var.instance_termination_watcher.enable && var.instance_termination_watcher.features.enable_spot_termination_handler ? { + value = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enabled && local.translated_experimental.compute_provider.ec2.instance_termination_watcher.features.enable_spot_termination_handler ? { lambda = module.instance_termination_watcher[0].spot_termination_handler.lambda lambda_log_group = module.instance_termination_watcher[0].spot_termination_handler.lambda_log_group lambda_role = module.instance_termination_watcher[0].spot_termination_handler.lambda_role diff --git a/modules/multi-runner/queues.tf b/modules/multi-runner/queues.tf index bcc75f99cc..f3d49e9448 100644 --- a/modules/multi-runner/queues.tf +++ b/modules/multi-runner/queues.tf @@ -1,5 +1,6 @@ +data "aws_iam_policy_document" "deny_insecure_transport_build" { + for_each = local.webhook_runner_config -data "aws_iam_policy_document" "deny_insecure_transport" { statement { sid = "DenyInsecureTransport" @@ -14,9 +15,7 @@ data "aws_iam_policy_document" "deny_insecure_transport" { "sqs:*" ] - resources = [ - "*" - ] + resources = [aws_sqs_queue.queued_builds[each.key].arn] condition { test = "Bool" @@ -27,42 +26,76 @@ data "aws_iam_policy_document" "deny_insecure_transport" { } resource "aws_sqs_queue" "queued_builds" { - for_each = var.multi_runner_config + for_each = local.webhook_runner_config name = "${var.prefix}-${each.key}-queued-builds" - delay_seconds = each.value.runner_config.delay_webhook_event - visibility_timeout_seconds = var.runners_scale_up_lambda_timeout - message_retention_seconds = each.value.runner_config.job_queue_retention_in_seconds + delay_seconds = each.value.orchestration.webhook.queue.delay_webhook_event + visibility_timeout_seconds = each.value.orchestration.webhook.queue.visibility_timeout_seconds + message_retention_seconds = each.value.orchestration.webhook.queue.job_queue_retention_in_seconds receive_wait_time_seconds = 0 - redrive_policy = each.value.redrive_build_queue.enabled ? jsonencode({ + redrive_policy = each.value.orchestration.webhook.queue.redrive_build_queue.enabled ? jsonencode({ deadLetterTargetArn = aws_sqs_queue.queued_builds_dlq[each.key].arn, - maxReceiveCount = each.value.redrive_build_queue.maxReceiveCount + maxReceiveCount = each.value.orchestration.webhook.queue.redrive_build_queue.maxReceiveCount }) : null - sqs_managed_sse_enabled = var.queue_encryption.sqs_managed_sse_enabled - kms_master_key_id = var.queue_encryption.kms_master_key_id - kms_data_key_reuse_period_seconds = var.queue_encryption.kms_data_key_reuse_period_seconds + sqs_managed_sse_enabled = local.translated_experimental.orchestration.webhook.queue.encryption.sqs_managed_sse_enabled + kms_master_key_id = local.translated_experimental.orchestration.webhook.queue.encryption.kms_master_key_id + kms_data_key_reuse_period_seconds = local.translated_experimental.orchestration.webhook.queue.encryption.kms_data_key_reuse_period_seconds - tags = var.tags + tags = merge( + local.translated_experimental.tags, + each.value.tags, + each.value.orchestration.webhook.queue.tags, + ) } - resource "aws_sqs_queue_policy" "build_queue_policy" { - for_each = var.multi_runner_config + for_each = local.webhook_runner_config queue_url = aws_sqs_queue.queued_builds[each.key].id - policy = data.aws_iam_policy_document.deny_insecure_transport.json + policy = data.aws_iam_policy_document.deny_insecure_transport_build[each.key].json } resource "aws_sqs_queue" "queued_builds_dlq" { - for_each = { for config, values in var.multi_runner_config : config => values if values.redrive_build_queue.enabled } + for_each = { for config, values in local.webhook_runner_config : config => values if values.orchestration.webhook.queue.redrive_build_queue.enabled } name = "${var.prefix}-${each.key}-queued-builds_dead_letter" - sqs_managed_sse_enabled = var.queue_encryption.sqs_managed_sse_enabled - kms_master_key_id = var.queue_encryption.kms_master_key_id - kms_data_key_reuse_period_seconds = var.queue_encryption.kms_data_key_reuse_period_seconds - tags = var.tags + sqs_managed_sse_enabled = local.translated_experimental.orchestration.webhook.queue.encryption.sqs_managed_sse_enabled + kms_master_key_id = local.translated_experimental.orchestration.webhook.queue.encryption.kms_master_key_id + kms_data_key_reuse_period_seconds = local.translated_experimental.orchestration.webhook.queue.encryption.kms_data_key_reuse_period_seconds + tags = merge( + local.translated_experimental.tags, + each.value.tags, + each.value.orchestration.webhook.queue.tags, + ) +} + +data "aws_iam_policy_document" "deny_insecure_transport_build_dlq" { + for_each = { for config, values in local.webhook_runner_config : config => values if values.orchestration.webhook.queue.redrive_build_queue.enabled } + + statement { + sid = "DenyInsecureTransport" + + effect = "Deny" + + principals { + type = "AWS" + identifiers = ["*"] + } + + actions = [ + "sqs:*" + ] + + resources = [aws_sqs_queue.queued_builds_dlq[each.key].arn] + + condition { + test = "Bool" + variable = "aws:SecureTransport" + values = ["false"] + } + } } resource "aws_sqs_queue_policy" "build_queue_dlq_policy" { - for_each = { for config, values in var.multi_runner_config : config => values if values.redrive_build_queue.enabled } + for_each = { for config, values in local.webhook_runner_config : config => values if values.orchestration.webhook.queue.redrive_build_queue.enabled } queue_url = aws_sqs_queue.queued_builds_dlq[each.key].id - policy = data.aws_iam_policy_document.deny_insecure_transport.json + policy = data.aws_iam_policy_document.deny_insecure_transport_build_dlq[each.key].json } diff --git a/modules/multi-runner/runner-binaries.tf b/modules/multi-runner/runner-binaries.tf index fb511bb3c5..fe6534a7e5 100644 --- a/modules/multi-runner/runner-binaries.tf +++ b/modules/multi-runner/runner-binaries.tf @@ -2,7 +2,7 @@ module "runner_binaries" { source = "../runner-binaries-syncer" for_each = local.unique_os_and_arch prefix = "${var.prefix}-${each.value.os_type}-${each.value.architecture}" - tags = local.tags + tags = merge(local.translated_experimental_base.tags, { "ghr:environment" = var.prefix }) # force mandatory lower case for s3 bucketname distribution_bucket_name = lower("${var.prefix}-${each.value.os_type}-${each.value.architecture}-dist-${random_string.random.result}") @@ -10,36 +10,48 @@ module "runner_binaries" { runner_os = each.value.os_type runner_architecture = each.value.architecture - lambda_s3_bucket = var.lambda_s3_bucket - syncer_lambda_s3_key = var.syncer_lambda_s3_key - syncer_lambda_s3_object_version = var.syncer_lambda_s3_object_version - lambda_runtime = var.lambda_runtime - lambda_architecture = var.lambda_architecture - lambda_zip = var.runner_binaries_syncer_lambda_zip - lambda_memory_size = var.runner_binaries_syncer_memory_size - lambda_timeout = var.runner_binaries_syncer_lambda_timeout - lambda_tags = var.lambda_tags - tracing_config = var.tracing_config - logging_retention_in_days = var.logging_retention_in_days - logging_kms_key_id = var.logging_kms_key_id - log_class = var.log_class - state_event_rule_binaries_syncer = var.state_event_rule_binaries_syncer - - server_side_encryption_configuration = var.runner_binaries_s3_sse_configuration - s3_tags = var.runner_binaries_s3_tags - s3_versioning = var.runner_binaries_s3_versioning - - role_path = var.role_path - role_permissions_boundary = var.role_permissions_boundary - - log_level = var.log_level - - lambda_subnet_ids = var.lambda_subnet_ids - lambda_security_group_ids = var.lambda_security_group_ids + lambda_s3_bucket = local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.artifact.s3 == null ? null : local.translated_experimental_base.lambda.artifact.s3.bucket + syncer_lambda_s3_key = try(local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.artifact.s3.key, null) + syncer_lambda_s3_object_version = try(local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.artifact.s3.object_version, null) + lambda_runtime = local.translated_experimental_base.lambda.runtime + lambda_architecture = local.translated_experimental_base.lambda.architecture + lambda_zip = local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.artifact.zip + lambda_memory_size = local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.lambda.memory_size + lambda_timeout = local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.lambda.timeout + lambda_tags = local.translated_experimental_base.lambda.tags + tracing_config = local.translated_experimental_base.observability.tracing + logging_retention_in_days = local.translated_experimental_base.observability.logs.retention_in_days + logging_kms_key_id = local.translated_experimental_base.observability.logs.kms_key_id + log_class = local.translated_experimental_base.observability.logs.class + state_event_rule_binaries_syncer = local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.schedule.state + lambda_schedule_expression = local.translated_experimental_base.compute_provider.ec2.runner_binaries.syncer.schedule.expression + + server_side_encryption_configuration = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.encryption.enabled ? { + rule = { + bucket_key_enabled = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.encryption.bucket_key_enabled + apply_server_side_encryption_by_default = { + sse_algorithm = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm + kms_master_key_id = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.encryption.kms_master_key_id + } + } + } : null + s3_tags = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.tags + s3_versioning = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.versioning + s3_logging_bucket = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.logging.bucket + s3_logging_bucket_prefix = local.translated_experimental_base.compute_provider.ec2.runner_binaries.s3.logging.prefix + + role_path = try(coalesce(local.translated_experimental_base.lambda.role.path, local.translated_experimental_base.roles.path), null) + role_permissions_boundary = try(coalesce(local.translated_experimental_base.lambda.role.permissions_boundary, local.translated_experimental_base.roles.permissions_boundary), null) + + log_level = local.translated_experimental_base.observability.logs.level + + lambda_subnet_ids = local.translated_experimental_base.lambda.subnet_ids + lambda_security_group_ids = local.translated_experimental_base.lambda.security_group_ids aws_partition = var.aws_partition - lambda_principals = var.lambda_principals + lambda_principals = local.translated_experimental_base.lambda.principals } + locals { runner_binaries_by_os_and_arch_map = { for k, v in module.runner_binaries : k => { arn = v.bucket.arn, id = v.bucket.id, key = v.runner_distribution_object_key } diff --git a/modules/multi-runner/runners.experimental.tf b/modules/multi-runner/runners.experimental.tf new file mode 100644 index 0000000000..b8481c54e1 --- /dev/null +++ b/modules/multi-runner/runners.experimental.tf @@ -0,0 +1,43 @@ +moved { + from = module.runner_stacks + to = module.runner_configs +} + +module "runner_configs" { + source = "../runner-config" + for_each = { + for runner_key, runner_config in local.translated_experimental.multi_runner_config : + runner_key => runner_config if local.use_multi_runner_config_v2 + } + + aws_region = var.aws_region + aws_partition = var.aws_partition + prefix = "${var.prefix}-${each.key}" + + tags = merge( + each.value.tags, + { "ghr:environment" = var.prefix }, + ) + runner = each.value.runner + github = merge(each.value.github, { + app_parameters = local.github_app_parameters + }) + lambda = each.value.lambda + orchestration = { + webhook = each.value.orchestration.webhook == null ? null : { + runner = each.value.orchestration.webhook.runner + github = each.value.orchestration.webhook.github + queue = merge(each.value.orchestration.webhook.queue, { + build = { + arn = aws_sqs_queue.queued_builds[each.key].arn + url = aws_sqs_queue.queued_builds[each.key].url + } + }) + lambda = each.value.orchestration.webhook.lambda + job_retry = each.value.orchestration.webhook.job_retry + } + } + ssm = each.value.ssm + observability = each.value.observability + compute_provider = each.value.compute_provider +} diff --git a/modules/multi-runner/runners.tf b/modules/multi-runner/runners.tf index 892113dcc7..f1c0c9d68c 100644 --- a/modules/multi-runner/runners.tf +++ b/modules/multi-runner/runners.tf @@ -1,130 +1,168 @@ module "runners" { - source = "../runners" - for_each = local.runner_config + source = "../runners" + for_each = { + for runner_key, runner_config in local.translated_experimental.multi_runner_config : + runner_key => runner_config if !local.use_multi_runner_config_v2 + } + aws_region = var.aws_region aws_partition = var.aws_partition - vpc_id = coalesce(each.value.runner_config.vpc_id, var.vpc_id) - subnet_ids = coalesce(each.value.runner_config.subnet_ids, var.subnet_ids) + vpc_id = each.value.compute_provider.ec2.vpc_id + subnet_ids = each.value.compute_provider.ec2.subnet_ids prefix = "${var.prefix}-${each.key}" - tags = merge(local.tags, { + tags = merge(each.value.tags, { "ghr:environment" = "${var.prefix}-${each.key}" }) - s3_runner_binaries = each.value.runner_config.enable_runner_binaries_syncer ? local.runner_binaries_by_os_and_arch_map["${each.value.runner_config.runner_os}_${each.value.runner_config.runner_architecture}"] : null + s3_runner_binaries = each.value.compute_provider.ec2.binaries_syncer.s3 - ssm_paths = { - root = "${local.ssm_root_path}/${each.key}" - tokens = "${var.ssm_paths.runners}/tokens" - config = "${var.ssm_paths.runners}/config" - } + ssm_paths = each.value.ssm.paths - runner_os = each.value.runner_config.runner_os - instance_types = each.value.runner_config.instance_types - instance_target_capacity_type = each.value.runner_config.instance_target_capacity_type - instance_allocation_strategy = each.value.runner_config.instance_allocation_strategy - instance_type_priorities = each.value.runner_config.instance_type_priorities - instance_max_spot_price = each.value.runner_config.instance_max_spot_price - block_device_mappings = each.value.runner_config.block_device_mappings + runner_os = each.value.runner.os + instance_types = each.value.compute_provider.ec2.instance_types + instance_target_capacity_type = each.value.compute_provider.ec2.instance_target_capacity_type + instance_allocation_strategy = each.value.compute_provider.ec2.instance_allocation_strategy + instance_type_priorities = each.value.compute_provider.ec2.instance_type_priorities + instance_max_spot_price = each.value.compute_provider.ec2.instance_max_spot_price + block_device_mappings = each.value.compute_provider.ec2.block_device_mappings - runner_architecture = each.value.runner_config.runner_architecture - ami = each.value.runner_config.ami + runner_architecture = each.value.runner.architecture + ami = each.value.compute_provider.ec2.ami == null ? null : { + filter = each.value.compute_provider.ec2.ami.filter + owners = each.value.compute_provider.ec2.ami.owners + id_ssm_parameter_arn = try(each.value.compute_provider.ec2.ami.id_ssm_parameter.arn, null) + kms_key_arn = try(each.value.compute_provider.ec2.ami.kms_key.arn, null) + } - sqs_build_queue = { "arn" : each.value.arn, "url" : each.value.url } + sqs_build_queue = { + arn = aws_sqs_queue.queued_builds[each.key].arn + url = aws_sqs_queue.queued_builds[each.key].url + } github_app_parameters = local.github_app_parameters - ebs_optimized = each.value.runner_config.ebs_optimized - enable_on_demand_failover_for_errors = each.value.runner_config.enable_on_demand_failover_for_errors - scale_errors = each.value.runner_config.scale_errors - enable_organization_runners = each.value.runner_config.enable_organization_runners - enable_ephemeral_runners = each.value.runner_config.enable_ephemeral_runners - enable_jit_config = each.value.runner_config.enable_jit_config - enable_job_queued_check = each.value.runner_config.enable_job_queued_check - disable_runner_autoupdate = each.value.runner_config.disable_runner_autoupdate - enable_managed_runner_security_group = var.enable_managed_runner_security_group - enable_runner_detailed_monitoring = each.value.runner_config.enable_runner_detailed_monitoring - scale_down_schedule_expression = each.value.runner_config.scale_down_schedule_expression - minimum_running_time_in_minutes = each.value.runner_config.minimum_running_time_in_minutes - runner_boot_time_in_minutes = each.value.runner_config.runner_boot_time_in_minutes - runner_disable_default_labels = each.value.runner_config.runner_disable_default_labels - runner_labels = each.value.runner_config.runner_disable_default_labels ? sort(distinct(each.value.runner_config.runner_extra_labels)) : sort(distinct(concat(["self-hosted", each.value.runner_config.runner_os, each.value.runner_config.runner_architecture], each.value.runner_config.runner_extra_labels))) - runner_as_root = each.value.runner_config.runner_as_root - runner_run_as = each.value.runner_config.runner_run_as - runners_maximum_count = each.value.runner_config.runners_maximum_count - idle_config = each.value.runner_config.idle_config - enable_ssm_on_runners = each.value.runner_config.enable_ssm_on_runners - egress_rules = var.runner_egress_rules - runner_additional_security_group_ids = try(coalescelist(each.value.runner_config.runner_additional_security_group_ids, var.runner_additional_security_group_ids), []) - metadata_options = each.value.runner_config.runner_metadata_options - credit_specification = each.value.runner_config.credit_specification - cpu_options = each.value.runner_config.cpu_options - placement = each.value.runner_config.placement - license_specifications = each.value.runner_config.license_specifications - use_dedicated_host = each.value.runner_config.use_dedicated_host - - enable_runner_binaries_syncer = each.value.runner_config.enable_runner_binaries_syncer - lambda_s3_bucket = var.lambda_s3_bucket - runners_lambda_s3_key = var.runners_lambda_s3_key - runners_lambda_s3_object_version = var.runners_lambda_s3_object_version - lambda_runtime = var.lambda_runtime - lambda_architecture = var.lambda_architecture - lambda_zip = var.runners_lambda_zip - lambda_scale_up_memory_size = var.scale_up_lambda_memory_size - lambda_event_source_mapping_batch_size = coalesce(each.value.runner_config.lambda_event_source_mapping_batch_size, var.lambda_event_source_mapping_batch_size) - lambda_event_source_mapping_maximum_batching_window_in_seconds = coalesce(each.value.runner_config.lambda_event_source_mapping_maximum_batching_window_in_seconds, var.lambda_event_source_mapping_maximum_batching_window_in_seconds) - lambda_timeout_scale_up = var.runners_scale_up_lambda_timeout - lambda_scale_down_memory_size = var.scale_down_lambda_memory_size - lambda_timeout_scale_down = var.runners_scale_down_lambda_timeout - lambda_subnet_ids = var.lambda_subnet_ids - lambda_security_group_ids = var.lambda_security_group_ids - lambda_tags = var.lambda_tags - tracing_config = var.tracing_config - logging_retention_in_days = var.logging_retention_in_days - logging_kms_key_id = var.logging_kms_key_id - log_class = var.log_class - enable_cloudwatch_agent = each.value.runner_config.enable_cloudwatch_agent - cloudwatch_config = try(coalesce(each.value.runner_config.cloudwatch_config, var.cloudwatch_config), null) - runner_log_files = each.value.runner_config.runner_log_files - runner_group_name = each.value.runner_config.runner_group_name - runner_name_prefix = each.value.runner_config.runner_name_prefix - parameter_store_tags = var.parameter_store_tags - - scale_up_reserved_concurrent_executions = each.value.runner_config.scale_up_reserved_concurrent_executions - - instance_profile_path = var.instance_profile_path - role_path = var.role_path - role_permissions_boundary = var.role_permissions_boundary - - enable_userdata = each.value.runner_config.enable_userdata - userdata_template = each.value.runner_config.userdata_template - userdata_content = each.value.runner_config.userdata_content - userdata_pre_install = each.value.runner_config.userdata_pre_install - userdata_post_install = each.value.runner_config.userdata_post_install - runner_hook_job_started = each.value.runner_config.runner_hook_job_started - runner_hook_job_completed = each.value.runner_config.runner_hook_job_completed - key_name = var.key_name - runner_ec2_tags = each.value.runner_config.runner_ec2_tags - - create_service_linked_role_spot = each.value.runner_config.create_service_linked_role_spot - - runner_iam_role_managed_policy_arns = each.value.runner_config.runner_iam_role_managed_policy_arns - iam_overrides = each.value.runner_config.iam_overrides - - ghes_url = var.ghes_url - ghes_ssl_verify = var.ghes_ssl_verify - user_agent = var.user_agent - - kms_key_arn = var.kms_key_arn - - log_level = var.log_level - - pool_config = each.value.runner_config.pool_config - pool_lambda_timeout = var.pool_lambda_timeout - pool_runner_owner = each.value.runner_config.pool_runner_owner - pool_lambda_reserved_concurrent_executions = var.pool_lambda_reserved_concurrent_executions - associate_public_ipv4_address = var.associate_public_ipv4_address - - ssm_housekeeper = var.runners_ssm_housekeeper - - job_retry = each.value.runner_config.job_retry - - metrics = var.metrics + ebs_optimized = each.value.compute_provider.ec2.ebs_optimized + enable_on_demand_failover_for_errors = each.value.compute_provider.ec2.enable_on_demand_failover_for_errors + scale_errors = each.value.compute_provider.ec2.scale_errors + enable_organization_runners = each.value.orchestration.webhook.github.organization_runners + enable_ephemeral_runners = each.value.orchestration.webhook.runner.ephemeral + enable_jit_config = each.value.orchestration.webhook.runner.jit_config_enabled + enable_job_queued_check = each.value.orchestration.webhook.lambda.scale.up.job_queued_check_enabled + disable_runner_autoupdate = each.value.runner.auto_update_disabled + enable_managed_runner_security_group = each.value.compute_provider.ec2.managed_security_group_enabled + enable_runner_detailed_monitoring = each.value.compute_provider.ec2.detailed_monitoring_enabled + scale_down_schedule_expression = each.value.orchestration.webhook.lambda.scale.down.schedule_expression + minimum_running_time_in_minutes = each.value.orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes + runner_boot_time_in_minutes = each.value.orchestration.webhook.runner.boot_time_in_minutes + runner_disable_default_labels = each.value.runner.disable_default_labels + runner_labels = each.value.runner.labels + runner_as_root = each.value.runner.run_as_root + runner_run_as = each.value.runner.run_as + runners_maximum_count = each.value.orchestration.webhook.runner.maximum_count + idle_config = each.value.orchestration.webhook.lambda.scale.down.idle_config + enable_ssm_on_runners = each.value.compute_provider.ec2.ssm_enabled + egress_rules = each.value.compute_provider.ec2.egress_rules + runner_additional_security_group_ids = each.value.compute_provider.ec2.additional_security_group_ids + metadata_options = each.value.compute_provider.ec2.metadata_options + credit_specification = each.value.compute_provider.ec2.credit_specification + cpu_options = each.value.compute_provider.ec2.cpu_options + placement = each.value.compute_provider.ec2.placement + license_specifications = each.value.compute_provider.ec2.license_specifications + use_dedicated_host = each.value.compute_provider.ec2.use_dedicated_host + + enable_runner_binaries_syncer = each.value.compute_provider.ec2.binaries_syncer.enabled + lambda_s3_bucket = local.translated_experimental.orchestration.webhook.lambda.artifact.s3 == null ? null : local.translated_experimental.lambda.artifact.s3.bucket + runners_lambda_s3_key = try(local.translated_experimental.orchestration.webhook.lambda.artifact.s3.key, null) + runners_lambda_s3_object_version = try(local.translated_experimental.orchestration.webhook.lambda.artifact.s3.object_version, null) + lambda_runtime = each.value.lambda.runtime + lambda_architecture = each.value.lambda.architecture + lambda_zip = local.translated_experimental.orchestration.webhook.lambda.artifact.zip + lambda_scale_up_memory_size = each.value.orchestration.webhook.lambda.scale.up.memory_size + lambda_event_source_mapping_batch_size = each.value.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size + lambda_event_source_mapping_maximum_batching_window_in_seconds = each.value.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds + lambda_timeout_scale_up = each.value.orchestration.webhook.lambda.scale.up.timeout + lambda_scale_down_memory_size = each.value.orchestration.webhook.lambda.scale.down.memory_size + lambda_timeout_scale_down = each.value.orchestration.webhook.lambda.scale.down.timeout + lambda_subnet_ids = each.value.lambda.subnet_ids + lambda_security_group_ids = each.value.lambda.security_group_ids + lambda_tags = each.value.lambda.tags + tracing_config = each.value.observability.tracing + logging_retention_in_days = each.value.observability.logs.retention_in_days + logging_kms_key_id = each.value.observability.logs.kms_key_id + log_class = each.value.observability.logs.class + enable_cloudwatch_agent = each.value.compute_provider.ec2.cloudwatch_agent.enabled + cloudwatch_config = each.value.compute_provider.ec2.cloudwatch_agent.config + runner_log_files = each.value.compute_provider.ec2.log_files + runner_group_name = each.value.runner.group_name + runner_name_prefix = each.value.runner.name_prefix + parameter_store_tags = each.value.ssm.parameters.tags + + scale_up_reserved_concurrent_executions = each.value.orchestration.webhook.lambda.scale.up.reserved_concurrent_executions + + instance_profile_path = each.value.compute_provider.ec2.instance_profile_path + role_path = each.value.runner.iam.path + role_permissions_boundary = each.value.runner.iam.permissions_boundary + + enable_userdata = each.value.compute_provider.ec2.user_data.enabled + userdata_template = each.value.compute_provider.ec2.user_data.template + userdata_content = each.value.compute_provider.ec2.user_data.content + userdata_pre_install = each.value.compute_provider.ec2.user_data.pre_install + userdata_post_install = each.value.compute_provider.ec2.user_data.post_install + enable_user_data_debug_logging = each.value.compute_provider.ec2.user_data.debug_logging_enabled + runner_hook_job_started = each.value.runner.hooks.job_started + runner_hook_job_completed = each.value.runner.hooks.job_completed + key_name = each.value.compute_provider.ec2.key_name + runner_ec2_tags = each.value.compute_provider.ec2.tags + + create_service_linked_role_spot = each.value.compute_provider.ec2.create_service_linked_role_spot + + runner_iam_role_managed_policy_arns = values(each.value.runner.iam.managed_policy_arns) + iam_overrides = { + override_instance_profile = each.value.compute_provider.ec2.instance_profile != null + instance_profile_name = try(each.value.compute_provider.ec2.instance_profile.name, null) + override_runner_role = each.value.runner.iam.role != null + runner_role_arn = try(each.value.runner.iam.role.arn, null) + } + + ghes_url = local.translated_experimental.github.enterprise_server.url + ghes_ssl_verify = local.translated_experimental.github.enterprise_server.ssl_verify + user_agent = local.translated_experimental.github.user_agent + + kms_key_arn = local.translated_experimental.ssm.kms_key_id + + log_level = each.value.observability.logs.level + + pool_config = each.value.orchestration.webhook.lambda.pool.config + pool_lambda_timeout = each.value.orchestration.webhook.lambda.pool.timeout + pool_lambda_memory_size = each.value.orchestration.webhook.lambda.pool.memory_size + pool_runner_owner = each.value.orchestration.webhook.lambda.pool.runner_owner + pool_include_busy_runners = each.value.orchestration.webhook.lambda.pool.include_busy_runners + pool_lambda_reserved_concurrent_executions = each.value.orchestration.webhook.lambda.pool.reserved_concurrent_executions + associate_public_ipv4_address = each.value.compute_provider.ec2.associate_public_ipv4_address + + ssm_housekeeper = { + schedule_expression = each.value.ssm.housekeeper.schedule_expression + state = each.value.ssm.housekeeper.state + lambda_memory_size = each.value.ssm.housekeeper.lambda.memory_size + lambda_timeout = each.value.ssm.housekeeper.lambda.timeout + config = each.value.ssm.housekeeper.config + } + + job_retry = { + enable = each.value.orchestration.webhook.job_retry.enabled + delay_in_seconds = each.value.orchestration.webhook.job_retry.delay_in_seconds + delay_backoff = each.value.orchestration.webhook.job_retry.delay_backoff + lambda_memory_size = each.value.orchestration.webhook.job_retry.lambda.memory_size + lambda_reserved_concurrent_executions = each.value.orchestration.webhook.job_retry.lambda.reserved_concurrent_executions + lambda_timeout = each.value.orchestration.webhook.job_retry.lambda.timeout + max_attempts = each.value.orchestration.webhook.job_retry.max_attempts + } + + metrics = { + enable = each.value.observability.metrics.enable + namespace = each.value.observability.metrics.namespace + metric = { + enable_github_app_rate_limit = each.value.observability.metrics.metric.enable_github_app_rate_limit + enable_job_retry = each.value.observability.metrics.metric.enable_job_retry + enable_spot_termination_warning = local.translated_experimental.observability.metrics.metric.enable_spot_termination_warning + } + } } diff --git a/modules/multi-runner/ssm.tf b/modules/multi-runner/ssm.tf index 3e4b740fdd..2f1c199dff 100644 --- a/modules/multi-runner/ssm.tf +++ b/modules/multi-runner/ssm.tf @@ -1,8 +1,13 @@ module "ssm" { - source = "../ssm" - kms_key_arn = var.kms_key_arn - path_prefix = "${local.ssm_root_path}/${var.ssm_paths.app}" - github_app = var.github_app - additional_github_apps = var.additional_github_apps - tags = local.tags + source = "../ssm" + + kms_key_arn = local.translated_experimental.ssm.kms_key_id + path_prefix = "${trimsuffix(coalesce(local.translated_experimental.ssm.paths.root, "/github-action-runners/${var.prefix}"), "/")}/${local.translated_experimental.ssm.paths.app}" + github_app = local.translated_experimental.github.app + additional_github_apps = local.translated_experimental.github.additional_apps + tags = merge( + local.translated_experimental.tags, + local.translated_experimental.ssm.tags, + { "ghr:environment" = var.prefix }, + ) } diff --git a/modules/multi-runner/termination-watcher.tf b/modules/multi-runner/termination-watcher.tf index 750db361bf..4fd3227a40 100644 --- a/modules/multi-runner/termination-watcher.tf +++ b/modules/multi-runner/termination-watcher.tf @@ -1,36 +1,38 @@ -locals { - lambda_instance_termination_watcher = { +module "instance_termination_watcher" { + source = "../termination-watcher" + count = try(local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enabled, false) ? 1 : 0 + + config = { prefix = var.prefix - tags = local.tags + tags = merge(local.translated_experimental.tags, { "ghr:environment" = var.prefix }) aws_partition = var.aws_partition - architecture = var.lambda_architecture - principals = var.lambda_principals - runtime = var.lambda_runtime - security_group_ids = var.lambda_security_group_ids - subnet_ids = var.lambda_subnet_ids - log_level = var.log_level - log_class = var.log_class - logging_kms_key_id = var.logging_kms_key_id - logging_retention_in_days = var.logging_retention_in_days - role_path = var.role_path - role_permissions_boundary = var.role_permissions_boundary - s3_bucket = var.lambda_s3_bucket - tracing_config = var.tracing_config - lambda_tags = var.lambda_tags - metrics = var.metrics - enable_runner_deregistration = var.instance_termination_watcher.enable_runner_deregistration - github_app_parameters = var.instance_termination_watcher.enable_runner_deregistration ? { + architecture = local.translated_experimental.lambda.architecture + principals = local.translated_experimental.lambda.principals + runtime = local.translated_experimental.lambda.runtime + security_group_ids = local.translated_experimental.lambda.security_group_ids + subnet_ids = local.translated_experimental.lambda.subnet_ids + log_level = local.translated_experimental.observability.logs.level + log_class = local.translated_experimental.observability.logs.class + logging_kms_key_id = local.translated_experimental.observability.logs.kms_key_id + logging_retention_in_days = local.translated_experimental.observability.logs.retention_in_days + role_path = try(coalesce(local.translated_experimental.lambda.role.path, local.translated_experimental.roles.path), null) + role_permissions_boundary = try(coalesce(local.translated_experimental.lambda.role.permissions_boundary, local.translated_experimental.roles.permissions_boundary), null) + s3_bucket = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3 == null ? null : local.translated_experimental.lambda.artifact.s3.bucket + tracing_config = local.translated_experimental.observability.tracing + lambda_tags = local.translated_experimental.lambda.tags + metrics = local.translated_experimental.observability.metrics + features = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.features + memory_size = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.lambda.memory_size + timeout = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.lambda.timeout + zip = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.artifact.zip + s3_key = try(local.translated_experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3.key, null) + s3_object_version = try(local.translated_experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3.object_version, null) + enable_runner_deregistration = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enable_runner_deregistration + github_app_parameters = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enable_runner_deregistration ? { id = local.github_app_parameters.id[0] key_base64 = local.github_app_parameters.key_base64[0] } : null - ghes_url = var.ghes_url - environment_variables = var.instance_termination_watcher.environment_variables + ghes_url = local.translated_experimental.github.enterprise_server.url + environment_variables = local.translated_experimental.compute_provider.ec2.instance_termination_watcher.environment_variables } } - -module "instance_termination_watcher" { - source = "../termination-watcher" - count = var.instance_termination_watcher.enable ? 1 : 0 - - config = merge(local.lambda_instance_termination_watcher, var.instance_termination_watcher) -} diff --git a/modules/multi-runner/tests/computed-runner-inputs.tftest.hcl b/modules/multi-runner/tests/computed-runner-inputs.tftest.hcl new file mode 100644 index 0000000000..1a9a59df1d --- /dev/null +++ b/modules/multi-runner/tests/computed-runner-inputs.tftest.hcl @@ -0,0 +1,67 @@ +mock_provider "aws" { + mock_data "aws_caller_identity" { + defaults = { + account_id = "123456789012" + } + } + + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } + + mock_resource "aws_iam_role" { + defaults = { + arn = "arn:aws:iam::123456789012:role/test-role" + } + } + + mock_resource "aws_cloudwatch_event_bus" { + defaults = { + arn = "arn:aws:events:eu-west-1:123456789012:event-bus/test" + } + } + + mock_resource "aws_cloudwatch_event_rule" { + defaults = { + arn = "arn:aws:events:eu-west-1:123456789012:rule/test" + } + } + + mock_resource "aws_lambda_function" { + defaults = { + arn = "arn:aws:lambda:eu-west-1:123456789012:function:test" + } + } + + mock_resource "aws_sqs_queue" { + defaults = { + arn = "arn:aws:sqs:eu-west-1:123456789012:test" + } + } + + mock_resource "aws_apigatewayv2_api" { + defaults = { + execution_arn = "arn:aws:execute-api:eu-west-1:123456789012:test" + } + } +} + +run "computed_lane_values_keep_binary_syncer_instances_plannable" { + command = plan + + module { + source = "./tests/fixtures/computed-runner-inputs" + } + + assert { + condition = output.runner_config_keys == ["linux"] + error_message = "Apply-time values inside a statically keyed runner configuration must not make binary-syncer module instances unknown." + } + + assert { + condition = output.binaries_syncer_keys == [] + error_message = "A runner configuration with the binary syncer disabled must not create a binary-syncer module instance." + } +} diff --git a/modules/multi-runner/tests/fixtures/computed-runner-inputs/README.md b/modules/multi-runner/tests/fixtures/computed-runner-inputs/README.md new file mode 100644 index 0000000000..5e0e532bc0 --- /dev/null +++ b/modules/multi-runner/tests/fixtures/computed-runner-inputs/README.md @@ -0,0 +1,37 @@ + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3 | +| [random](#requirement\_random) | ~> 3.0 | + +## Providers + +| Name | Version | +|------|---------| +| [random](#provider\_random) | ~> 3.0 | + +## Modules + +| Name | Source | Version | +|------|--------|---------| +| [multi\_runner](#module\_multi\_runner) | ../../.. | n/a | + +## Resources + +| Name | Type | +|------|------| +| [random_id.managed_policy](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/id) | resource | + +## Inputs + +No inputs. + +## Outputs + +| Name | Description | +|------|-------------| +| [binaries\_syncer\_keys](#output\_binaries\_syncer\_keys) | n/a | +| [runner\_config\_keys](#output\_runner\_config\_keys) | n/a | + diff --git a/modules/multi-runner/tests/fixtures/computed-runner-inputs/main.tf b/modules/multi-runner/tests/fixtures/computed-runner-inputs/main.tf new file mode 100644 index 0000000000..68635ece1e --- /dev/null +++ b/modules/multi-runner/tests/fixtures/computed-runner-inputs/main.tf @@ -0,0 +1,133 @@ +# Keep the runner-configuration key, provider selection, and optional KMS scalar +# caller-known while passing apply-time ARNs through the configuration. +resource "random_id" "managed_policy" { + byte_length = 4 +} + +module "multi_runner" { + source = "../../.." + + aws_region = "eu-west-1" + prefix = "computed-inputs" + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/generated-${random_id.managed_policy.hex}" + + github_app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + + lambda_s3_bucket = "lambda-artifacts" + webhook_lambda_s3_key = "webhook.zip" + runners_lambda_s3_key = "runners.zip" + syncer_lambda_s3_key = "runner-binaries-syncer.zip" + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + + lambda = { + artifact = { + s3 = { + bucket = "nested-lambda-artifacts" + } + } + } + + orchestration = { + webhook = { + queue = { + encryption = { + kms_data_key_reuse_period_seconds = 300 + kms_master_key_id = "arn:aws:kms:eu-west-1:123456789012:key/generated-${random_id.managed_policy.hex}" + sqs_managed_sse_enabled = null + } + } + + lambda = { + artifact = { + s3 = { + key = "nested-runners.zip" + } + } + + webhook = { + artifact = { + s3 = { + key = "webhook.zip" + } + } + } + } + } + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-nested-12345678" + subnet_ids = ["subnet-nested-12345678"] + } + } + + ssm = { + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/generated-${random_id.managed_policy.hex}" + housekeeper = { + lambda = { + artifact = { + s3 = { + key = "nested-ssm-housekeeper.zip" + } + } + } + } + } + + multi_runner_config = { + linux = { + runner = { + os = "linux" + architecture = "x64" + iam = { + managed_policy_arns = { + generated = "arn:aws:iam::123456789012:policy/generated-${random_id.managed_policy.hex}" + } + } + } + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } +} + +output "runner_config_keys" { + value = keys(module.multi_runner.runners_map_v2) +} + +output "binaries_syncer_keys" { + value = keys(module.multi_runner.binaries_syncer_map) +} diff --git a/modules/multi-runner/tests/fixtures/computed-runner-inputs/versions.tf b/modules/multi-runner/tests/fixtures/computed-runner-inputs/versions.tf new file mode 100644 index 0000000000..9fd85fad8f --- /dev/null +++ b/modules/multi-runner/tests/fixtures/computed-runner-inputs/versions.tf @@ -0,0 +1,13 @@ +terraform { + required_version = ">= 1.3" + + required_providers { + aws = { + source = "hashicorp/aws" + } + random = { + source = "hashicorp/random" + version = "~> 3.0" + } + } +} diff --git a/modules/multi-runner/tests/provider-routing.tftest.hcl b/modules/multi-runner/tests/provider-routing.tftest.hcl new file mode 100644 index 0000000000..2869365299 --- /dev/null +++ b/modules/multi-runner/tests/provider-routing.tftest.hcl @@ -0,0 +1,5220 @@ +mock_provider "aws" { + mock_data "aws_caller_identity" { + defaults = { + account_id = "123456789012" + } + } + + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" + } + } +} + +mock_provider "random" {} +mock_provider "null" {} + +variables { + aws_region = "eu-west-1" + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + + github_app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + + lambda_s3_bucket = "lambda-artifacts" + webhook_lambda_s3_key = "webhook.zip" + runners_lambda_zip = "README.md" + runners_lambda_s3_key = "runners.zip" + syncer_lambda_s3_key = "runner-binaries-syncer.zip" +} + +run "empty_runner_configurations_return_empty_output_maps" { + command = plan + + assert { + condition = length(output.runners_map) == 0 && length(output.runners_map_v2) == 0 + error_message = "Stable and experimental runner outputs must both be empty when no runner configurations are supplied." + } + + assert { + condition = ( + length(local.raw_translated_experimental.multi_runner_config) == 0 + && length(local.translated_experimental.multi_runner_config) == 0 + && length(local.webhook_runner_config) == 0 + && length(local.runner_matcher_config) == 0 + && length(module.runner_configs) == 0 + ) + error_message = "An empty stable and experimental configuration must translate to an empty raw runner-configuration map without selecting a v2 runner configuration." + } + + assert { + condition = ( + local.github_app_parameters.webhook_secret != null + && module.ssm.parameters.github_app_webhook_secret != null + && output.ssm_parameters.webhook_secret != null + && output.webhook != null + ) + error_message = "Stable v1 must retain its shared webhook and webhook-secret parameter even when multi_runner_config is empty." + } +} + +run "stable_v1_keeps_legacy_runner_module" { + command = plan + + variables { + tags = { + StableGlobal = "global" + Precedence = "global" + } + + repository_white_list = ["legacy-owner/legacy-repository"] + queue_selection_strategy = "random" + eventbridge = { + enable = false + accept_events = ["workflow_job"] + } + matcher_config_parameter_store_tier = "Advanced" + webhook_lambda_apigateway_access_log_settings = { + destination_arn = "arn:aws:logs:eu-west-1:123456789012:log-group:legacy-api-access" + format = "$context.requestId" + } + webhook_lambda_s3_object_version = "legacy-webhook-version" + + lambda_runtime = "nodejs20.x" + lambda_architecture = "x86_64" + lambda_subnet_ids = ["subnet-legacy-lambda"] + lambda_security_group_ids = ["sg-legacy-lambda"] + lambda_principals = [{ + type = "AWS" + identifiers = ["arn:aws:iam::123456789012:role/legacy-lambda-principal"] + }] + webhook_lambda_memory_size = 320 + webhook_lambda_timeout = 25 + runners_scale_up_lambda_timeout = 47 + runners_lambda_s3_object_version = "legacy-runners-version" + runner_binaries_syncer_memory_size = 640 + runner_binaries_syncer_lambda_timeout = 70 + role_path = "/legacy/" + role_permissions_boundary = "arn:aws:iam::123456789012:policy/legacy-boundary" + ghes_url = "https://legacy.example.com" + ghes_ssl_verify = false + user_agent = "legacy-user-agent" + log_level = "warn" + logging_retention_in_days = 14 + logging_kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/legacy-logs" + log_class = "STANDARD" + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/legacy-ssm" + + queue_encryption = { + kms_data_key_reuse_period_seconds = 300 + kms_master_key_id = "arn:aws:kms:eu-west-1:123456789012:key/legacy-queue" + sqs_managed_sse_enabled = null + } + + lambda_tags = { + LegacyLambda = "legacy" + } + + tracing_config = { + mode = "Active" + capture_http_requests = true + capture_error = false + } + + metrics = { + enable = true + namespace = "LegacyMetrics" + metric = { + enable_github_app_rate_limit = true + enable_job_retry = false + enable_spot_termination_warning = false + } + } + + ssm_paths = { + root = "legacy-root" + app = "legacy-app" + runners = "legacy-runners" + webhook = "legacy-webhook" + } + + parameter_store_tags = { + LegacyParameter = "legacy" + Precedence = "legacy-parameter" + } + + runners_ssm_housekeeper = { + schedule_expression = "rate(12 hours)" + enabled = false + lambda_memory_size = 320 + lambda_timeout = 45 + config = { + tokenPath = "/legacy/cleanup/tokens" + minimumDaysOld = 5 + dryRun = true + } + } + + instance_termination_watcher = { + enable = true + enable_runner_deregistration = true + environment_variables = { + LEGACY_WATCHER = "true" + } + features = { + enable_spot_termination_handler = true + enable_spot_termination_notification_watcher = true + } + memory_size = 448 + timeout = 35 + s3_key = "termination-watcher.zip" + s3_object_version = "legacy-watcher-version" + } + + enable_ami_housekeeper = true + ami_housekeeper_lambda_memory_size = 384 + ami_housekeeper_lambda_timeout = 90 + ami_housekeeper_lambda_s3_key = "ami-housekeeper.zip" + ami_housekeeper_lambda_s3_object_version = "legacy-ami-housekeeper-version" + ami_housekeeper_lambda_schedule_expression = "rate(2 days)" + ami_housekeeper_cleanup_config = { + maxItems = 7 + minimumDaysOld = 14 + dryRun = true + } + + experimental = { + tags = { + ExperimentalOnly = "ignored" + } + roles = { + path = "/experimental/" + } + lambda = { + artifact = { + s3 = { + bucket = "experimental-ignored-artifacts" + } + } + runtime = "nodejs22.x" + architecture = "sparc64" + principals = [{ + type = "AWS" + identifiers = ["arn:aws:iam::123456789012:role/experimental-ignored-principal"] + }] + subnet_ids = ["subnet-experimental-lambda"] + security_group_ids = ["sg-experimental-lambda"] + tags = { + ExperimentalLambda = "ignored" + } + } + + orchestration = { + webhook = { + lambda = { + webhook = { + memory_size = 896 + timeout = 90 + } + } + } + } + github = { + app = { + id = "incomplete-experimental-id" + } + additional_apps = [{ id = "incomplete-additional-app-id" }] + enterprise_server = { + url = "https://experimental.example.com" + ssl_verify = true + } + user_agent = "experimental-user-agent" + } + ssm = { + paths = { + root = "relative-experimental-root" + tokens = "experimental-tokens" + config = "experimental-config" + } + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/experimental-ssm" + tags = { + ExperimentalSsm = "ignored" + } + parameters = { + tags = { + ExperimentalParameter = "ignored" + } + } + housekeeper = { + schedule_expression = "rate(1 hour)" + state = "PAUSED" + lambda = { + memory_size = 896 + timeout = 90 + } + config = { + tokenPath = "/experimental/cleanup/tokens" + minimumDaysOld = 1 + dryRun = false + } + } + } + observability = { + logs = { + level = "verbose" + retention_in_days = 30 + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/experimental-logs" + class = "ARCHIVE" + } + tracing = { + mode = "PassThrough" + capture_http_requests = false + capture_error = true + } + metrics = { + enable = false + namespace = "ExperimentalMetrics" + metric = { + enable_github_app_rate_limit = false + enable_job_retry = true + enable_spot_termination_warning = true + } + } + } + } + + multi_runner_config = { + linux = { + runner_config = { + runner_os = "linux" + runner_architecture = "x64" + instance_types = ["m5.large"] + runners_maximum_count = 2 + enable_runner_binaries_syncer = true + enable_organization_runners = true + delay_webhook_event = 17 + job_queue_retention_in_seconds = 12345 + } + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + redrive_build_queue = { + enabled = true + maxReceiveCount = 3 + } + } + } + } + + assert { + condition = ( + toset(keys(local.raw_translated_experimental)) == toset([ + "tags", + "roles", + "runner", + "github", + "lambda", + "orchestration", + "ssm", + "observability", + "compute_provider", + "multi_runner_config", + ]) + && toset(keys(local.raw_translated_experimental.github)) == toset([ + "app", + "additional_apps", + "enterprise_server", + "user_agent", + ]) + && toset(keys(local.raw_translated_experimental.lambda)) == toset([ + "artifact", + "runtime", + "architecture", + "principals", + "subnet_ids", + "security_group_ids", + "tags", + "role", + ]) + && toset(keys(local.raw_translated_experimental.orchestration)) == toset([ + "webhook", + ]) + && toset(keys(local.raw_translated_experimental.orchestration.webhook)) == toset([ + "queue_selection_strategy", + "eventbridge", + "matcher_config_parameter_store_tier", + "runner", + "github", + "lambda", + "queue", + ]) + && toset(keys(local.raw_translated_experimental.orchestration.webhook.runner)) == toset([ + "boot_time_in_minutes", + "ephemeral", + "jit_config_enabled", + "maximum_count", + ]) + && toset(keys(local.raw_translated_experimental.orchestration.webhook.github)) == toset([ + "repository_white_list", + ]) + && toset(keys(local.raw_translated_experimental.orchestration.webhook.lambda)) == toset([ + "artifact", + "scale", + "webhook", + "pool", + ]) + && toset(keys(local.raw_translated_experimental.orchestration.webhook.lambda.scale)) == toset([ + "up", + "down", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"])) == toset([ + "tags", + "runner", + "lambda", + "orchestration", + "ssm", + "observability", + "compute_provider", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].lambda)) == toset([ + "runtime", + "architecture", + "subnet_ids", + "security_group_ids", + "tags", + "role", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].orchestration)) == toset([ + "webhook", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook)) == toset([ + "runner", + "github", + "lambda", + "queue", + "job_retry", + "matcherConfig", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda)) == toset([ + "scale", + "pool", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale)) == toset([ + "up", + "down", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue)) == toset([ + "delay_webhook_event", + "job_queue_retention_in_seconds", + "visibility_timeout_seconds", + "redrive_build_queue", + "tags", + ]) + && toset(keys(local.raw_translated_experimental.orchestration.webhook.queue)) == toset([ + "delay_webhook_event", + "job_queue_retention_in_seconds", + "visibility_timeout_seconds", + "redrive_build_queue", + "tags", + "encryption", + ]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].compute_provider)) == toset(["ec2"]) + && toset(keys(local.raw_translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer)) == toset(["enabled"]) + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].ssm), "kms_key_id") + && !contains(keys(local.raw_translated_experimental.runner), "boot_time_in_minutes") + && !contains(keys(local.raw_translated_experimental.runner), "ephemeral") + && !contains(keys(local.raw_translated_experimental.runner), "jit_config_enabled") + && !contains(keys(local.raw_translated_experimental.runner), "maximum_count") + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].runner), "boot_time_in_minutes") + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].runner), "ephemeral") + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].runner), "jit_config_enabled") + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].runner), "maximum_count") + && local.raw_translated_experimental.orchestration.webhook.runner.boot_time_in_minutes == 5 + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"]), "scale_up") + ) + error_message = "Stable v1 must translate into the exact raw experimental schema before defaults, queue event-source mappings, binary artifacts, or runner-config component shapes are resolved." + } + + assert { + condition = ( + toset(keys(local.translated_experimental_base.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer)) == toset(["enabled"]) + && toset(keys(local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer)) == toset(["enabled", "s3"]) + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer.enabled + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer.s3 != null + && toset(keys(local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer.s3)) == toset(["arn", "id", "key"]) + ) + error_message = "Stable translation must discover binary-syncer runner configurations from the base object, then enrich the final canonical configuration with its resolved S3 distribution." + } + + assert { + condition = ( + local.raw_translated_experimental.tags == var.tags + && local.raw_translated_experimental.roles.path == var.role_path + && local.raw_translated_experimental.roles.permissions_boundary == var.role_permissions_boundary + && local.raw_translated_experimental.github.app == var.github_app + && local.raw_translated_experimental.github.additional_apps == var.additional_github_apps + && local.raw_translated_experimental.orchestration.webhook.github.repository_white_list == var.repository_white_list + && local.raw_translated_experimental.github.enterprise_server.url == var.ghes_url + && local.raw_translated_experimental.github.enterprise_server.ssl_verify == var.ghes_ssl_verify + && local.raw_translated_experimental.github.user_agent == var.user_agent + && local.raw_translated_experimental.orchestration.webhook.queue_selection_strategy == var.queue_selection_strategy + && local.raw_translated_experimental.orchestration.webhook.eventbridge == var.eventbridge + && local.raw_translated_experimental.orchestration.webhook.matcher_config_parameter_store_tier == var.matcher_config_parameter_store_tier + && local.raw_translated_experimental.orchestration.webhook.lambda.artifact.zip == null + && local.raw_translated_experimental.lambda.artifact.s3.bucket == var.lambda_s3_bucket + && local.raw_translated_experimental.orchestration.webhook.lambda.artifact.s3.key == var.runners_lambda_s3_key + && local.raw_translated_experimental.orchestration.webhook.lambda.artifact.s3.object_version == var.runners_lambda_s3_object_version + && local.raw_translated_experimental.lambda.runtime == var.lambda_runtime + && local.raw_translated_experimental.lambda.architecture == var.lambda_architecture + && local.raw_translated_experimental.lambda.principals == var.lambda_principals + && local.raw_translated_experimental.lambda.subnet_ids == var.lambda_subnet_ids + && local.raw_translated_experimental.lambda.security_group_ids == var.lambda_security_group_ids + && local.raw_translated_experimental.lambda.tags == var.lambda_tags + && local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size == var.lambda_event_source_mapping_batch_size + && local.raw_translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds == var.lambda_event_source_mapping_maximum_batching_window_in_seconds + && local.raw_translated_experimental.orchestration.webhook.lambda.webhook.artifact.zip == null + && local.raw_translated_experimental.orchestration.webhook.lambda.webhook.artifact.s3.key == var.webhook_lambda_s3_key + && local.raw_translated_experimental.orchestration.webhook.lambda.webhook.artifact.s3.object_version == var.webhook_lambda_s3_object_version + && local.raw_translated_experimental.orchestration.webhook.lambda.webhook.api_gateway_access_log_settings == var.webhook_lambda_apigateway_access_log_settings + && local.raw_translated_experimental.orchestration.webhook.lambda.webhook.memory_size == var.webhook_lambda_memory_size + && local.raw_translated_experimental.orchestration.webhook.lambda.webhook.timeout == var.webhook_lambda_timeout + && local.raw_translated_experimental.orchestration.webhook.queue.visibility_timeout_seconds == var.runners_scale_up_lambda_timeout + && local.raw_translated_experimental.orchestration.webhook.queue.encryption == var.queue_encryption + && local.raw_translated_experimental.ssm.paths.root == "/legacy-root/github-actions" + && local.raw_translated_experimental.ssm.paths.app == var.ssm_paths.app + && local.raw_translated_experimental.ssm.paths.webhook == var.ssm_paths.webhook + && local.raw_translated_experimental.ssm.paths.tokens == "${var.ssm_paths.runners}/tokens" + && local.raw_translated_experimental.ssm.paths.config == "${var.ssm_paths.runners}/config" + && local.raw_translated_experimental.ssm.kms_key_id == var.kms_key_arn + && local.raw_translated_experimental.ssm.parameters.tags == var.parameter_store_tags + && local.raw_translated_experimental.observability.logs.level == var.log_level + && local.raw_translated_experimental.observability.logs.retention_in_days == var.logging_retention_in_days + && local.raw_translated_experimental.observability.logs.kms_key_id == var.logging_kms_key_id + && local.raw_translated_experimental.observability.logs.class == var.log_class + && local.raw_translated_experimental.observability.tracing == var.tracing_config + && local.raw_translated_experimental.observability.metrics.enable == var.metrics.enable + && local.raw_translated_experimental.observability.metrics.namespace == var.metrics.namespace + && local.raw_translated_experimental.observability.metrics.metric.enable_github_app_rate_limit == var.metrics.metric.enable_github_app_rate_limit + && local.raw_translated_experimental.observability.metrics.metric.enable_job_retry == var.metrics.metric.enable_job_retry + && local.raw_translated_experimental.observability.metrics.metric.enable_spot_termination + && local.raw_translated_experimental.observability.metrics.metric.enable_spot_termination_warning == var.metrics.metric.enable_spot_termination_warning + && local.raw_translated_experimental.ssm.housekeeper.lambda.artifact.zip == null + && local.raw_translated_experimental.ssm.housekeeper.lambda.artifact.s3.key == var.runners_lambda_s3_key + && local.raw_translated_experimental.ssm.housekeeper.lambda.artifact.s3.object_version == var.runners_lambda_s3_object_version + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.lambda.artifact.s3.key == var.runners_lambda_s3_key + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.lambda.artifact.s3.object_version == var.runners_lambda_s3_object_version + && local.raw_translated_experimental.compute_provider.ec2.vpc_id == var.vpc_id + && local.raw_translated_experimental.compute_provider.ec2.subnet_ids == var.subnet_ids + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.enabled == var.enable_ami_housekeeper + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.cleanup_config == var.ami_housekeeper_cleanup_config + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.artifact.zip == null + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.artifact.s3.key == var.ami_housekeeper_lambda_s3_key + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.artifact.s3.object_version == var.ami_housekeeper_lambda_s3_object_version + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.lambda.memory_size == var.ami_housekeeper_lambda_memory_size + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.lambda.timeout == var.ami_housekeeper_lambda_timeout + && local.raw_translated_experimental.compute_provider.ec2.ami.housekeeper.schedule.expression == var.ami_housekeeper_lambda_schedule_expression + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.enabled == var.instance_termination_watcher.enable + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.features == var.instance_termination_watcher.features + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.enable_runner_deregistration == var.instance_termination_watcher.enable_runner_deregistration + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.environment_variables == var.instance_termination_watcher.environment_variables + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.artifact.zip == null + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3.key == var.instance_termination_watcher.s3_key + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3.object_version == var.instance_termination_watcher.s3_object_version + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.lambda.memory_size == var.instance_termination_watcher.memory_size + && local.raw_translated_experimental.compute_provider.ec2.instance_termination_watcher.lambda.timeout == var.instance_termination_watcher.timeout + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.enabled + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.s3.encryption.enabled + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm == var.runner_binaries_s3_sse_configuration.rule.apply_server_side_encryption_by_default.sse_algorithm + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.s3.tags == var.runner_binaries_s3_tags + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.s3.versioning == var.runner_binaries_s3_versioning + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3.key == var.syncer_lambda_s3_key + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3.object_version == var.syncer_lambda_s3_object_version + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.syncer.lambda.memory_size == var.runner_binaries_syncer_memory_size + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.syncer.lambda.timeout == var.runner_binaries_syncer_lambda_timeout + && local.raw_translated_experimental.compute_provider.ec2.runner_binaries.syncer.schedule.state == var.state_event_rule_binaries_syncer + && local.raw_translated_experimental.multi_runner_config["linux"].runner.os == var.multi_runner_config["linux"].runner_config.runner_os + && local.raw_translated_experimental.multi_runner_config["linux"].runner.architecture == var.multi_runner_config["linux"].runner_config.runner_architecture + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].runner), "boot_time_in_minutes") + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].runner), "ephemeral") + && !contains(keys(local.raw_translated_experimental.multi_runner_config["linux"].runner), "jit_config_enabled") + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.boot_time_in_minutes == var.multi_runner_config["linux"].runner_config.runner_boot_time_in_minutes + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.ephemeral == var.multi_runner_config["linux"].runner_config.enable_ephemeral_runners + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.jit_config_enabled == var.multi_runner_config["linux"].runner_config.enable_jit_config + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.maximum_count == var.multi_runner_config["linux"].runner_config.runners_maximum_count + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.github.organization_runners == var.multi_runner_config["linux"].runner_config.enable_organization_runners + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size == var.multi_runner_config["linux"].runner_config.lambda_event_source_mapping_batch_size + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.delay_webhook_event == var.multi_runner_config["linux"].runner_config.delay_webhook_event + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.job_queue_retention_in_seconds == var.multi_runner_config["linux"].runner_config.job_queue_retention_in_seconds + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.visibility_timeout_seconds == var.runners_scale_up_lambda_timeout + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.redrive_build_queue == var.multi_runner_config["linux"].redrive_build_queue + && local.raw_translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer.enabled + && local.raw_translated_experimental.multi_runner_config["linux"].orchestration.webhook.matcherConfig == var.multi_runner_config["linux"].matcherConfig + ) + error_message = "Stable v1 flat and per-runner inputs must populate every raw translation family while conflicting experimental globals remain inactive." + } + + assert { + condition = ( + !var.runners_ssm_housekeeper.enabled + && local.translated_experimental.ssm.housekeeper.state == "DISABLED" + && keys(module.runners) == ["linux"] + ) + error_message = "Stable v1 must translate runners_ssm_housekeeper.enabled=false to the DISABLED child event-rule state while retaining module.runners ownership." + } + + assert { + condition = keys(local.runner_config_by_provider.ec2) == ["linux"] + error_message = "Stable multi_runner_config entries must route to the EC2 provider." + } + + assert { + condition = ( + !local.use_multi_runner_config_v2 + && toset(keys(local.raw_translated_experimental.multi_runner_config)) == toset(["linux"]) + && toset(keys(local.translated_experimental.multi_runner_config)) == toset(["linux"]) + && length(module.runner_configs) == 0 + && keys(module.runners) == ["linux"] + ) + error_message = "Stable multi_runner_config entries must keep the original runner configuration and remain isolated from v2." + } + + assert { + condition = ( + var.experimental.github.app.key_base64 == null + && var.experimental.github.app.webhook_secret == null + && var.experimental.github.additional_apps[0].key_base64 == null + && var.experimental.lambda.architecture == "sparc64" + && var.experimental.observability.logs.level == "verbose" + && var.experimental.observability.logs.class == "ARCHIVE" + && var.experimental.ssm.paths.root == "relative-experimental-root" + && var.experimental.ssm.housekeeper.state == "PAUSED" + && !local.use_multi_runner_config_v2 + && keys(module.runners) == ["linux"] + ) + error_message = "Invalid but unused experimental sibling globals must remain gated when a stable v1 configuration owns the deployment." + } + + assert { + condition = ( + contains(keys(local.translated_experimental.multi_runner_config["linux"]), "compute_provider") + && !contains(keys(local.translated_experimental.multi_runner_config["linux"]), "runner_config") + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.github.organization_runners + ) + error_message = "Stable module inputs must use the canonical translated runner configuration while retaining stable module.runners ownership." + } + + assert { + condition = keys(module.runners) == ["linux"] && length(module.runner_configs) == 0 + error_message = "Stable multi_runner_config entries must retain the historical module.runners address." + } + + assert { + condition = keys(aws_sqs_queue.queued_builds) == ["linux"] + error_message = "Common queue ownership must preserve the stable runner configuration key." + } + + assert { + condition = ( + aws_sqs_queue.queued_builds["linux"].tags == var.tags + && aws_sqs_queue.queued_builds_dlq["linux"].tags == var.tags + ) + error_message = "Stable multi_runner_config queues must continue to receive exactly the module-level tags." + } + + assert { + condition = ( + aws_sqs_queue.queued_builds["linux"].delay_seconds == 17 + && aws_sqs_queue.queued_builds["linux"].message_retention_seconds == 12345 + && aws_sqs_queue.queued_builds["linux"].visibility_timeout_seconds == var.runners_scale_up_lambda_timeout + && aws_sqs_queue.queued_builds["linux"].kms_master_key_id == var.queue_encryption.kms_master_key_id + && aws_sqs_queue.queued_builds["linux"].kms_data_key_reuse_period_seconds == var.queue_encryption.kms_data_key_reuse_period_seconds + && aws_sqs_queue.queued_builds_dlq["linux"].kms_master_key_id == var.queue_encryption.kms_master_key_id + && aws_sqs_queue.queued_builds_dlq["linux"].kms_data_key_reuse_period_seconds == var.queue_encryption.kms_data_key_reuse_period_seconds + ) + error_message = "Stable v1 queues must retain per-runner delay and retention plus flat timeout and encryption inputs after translation." + } + + assert { + condition = ( + output.runners_map["linux"].lambda_up.runtime == "nodejs20.x" + && output.runners_map["linux"].lambda_up.s3_bucket == var.lambda_s3_bucket + && output.runners_map["linux"].lambda_up.s3_key == var.runners_lambda_s3_key + && output.runners_map["linux"].lambda_up.s3_object_version == "legacy-runners-version" + && output.runners_map["linux"].role_scale_up.path == "/legacy/" + && output.webhook.lambda.runtime == "nodejs20.x" + && output.webhook.lambda.architectures == tolist(["x86_64"]) + && output.webhook.lambda.memory_size == 320 + && output.webhook.lambda.timeout == 25 + && output.webhook.lambda.s3_bucket == "lambda-artifacts" + && output.webhook.lambda.s3_key == "webhook.zip" + && output.webhook.lambda.s3_object_version == "legacy-webhook-version" + && toset(output.webhook.lambda.vpc_config[0].subnet_ids) == toset(["subnet-legacy-lambda"]) + && toset(output.webhook.lambda.vpc_config[0].security_group_ids) == toset(["sg-legacy-lambda"]) + && output.webhook.lambda.tags["LegacyLambda"] == "legacy" + && !contains(keys(output.webhook.lambda.tags), "ExperimentalLambda") + && output.webhook.lambda_role.path == "/legacy/" + && output.webhook.lambda_role.permissions_boundary == "arn:aws:iam::123456789012:policy/legacy-boundary" + && toset(jsondecode(output.webhook.lambda.environment[0].variables["REPOSITORY_ALLOW_LIST"])) == toset(var.repository_white_list) + && output.webhook.lambda.environment[0].variables["QUEUE_SELECTION_STRATEGY"] == var.queue_selection_strategy + && output.webhook.eventbridge == null + && output.webhook.dispatcher == null + && output.runners_map["linux"].lambda_up.environment[0].variables["GHES_URL"] == "https://legacy.example.com" + && output.runners_map["linux"].lambda_up.environment[0].variables["NODE_TLS_REJECT_UNAUTHORIZED"] == "0" + && output.runners_map["linux"].lambda_up.environment[0].variables["USER_AGENT"] == "legacy-user-agent" + ) + error_message = "The stable v1 runner and shared webhook must use flat Lambda, artifact, network, tag, role, and GitHub inputs while ignoring experimental globals." + } + + assert { + condition = ( + keys(output.binaries_syncer_map) == ["linux_x64"] + && output.binaries_syncer_map["linux_x64"].lambda.runtime == "nodejs20.x" + && output.binaries_syncer_map["linux_x64"].lambda.architectures == tolist(["x86_64"]) + && output.binaries_syncer_map["linux_x64"].lambda.memory_size == 640 + && output.binaries_syncer_map["linux_x64"].lambda.timeout == 70 + && toset(output.binaries_syncer_map["linux_x64"].lambda.vpc_config[0].subnet_ids) == toset(["subnet-legacy-lambda"]) + && toset(output.binaries_syncer_map["linux_x64"].lambda.vpc_config[0].security_group_ids) == toset(["sg-legacy-lambda"]) + && output.binaries_syncer_map["linux_x64"].lambda.tags["LegacyLambda"] == "legacy" + && !contains(keys(output.binaries_syncer_map["linux_x64"].lambda.tags), "ExperimentalLambda") + && output.binaries_syncer_map["linux_x64"].lambda_role.path == "/legacy/" + && output.binaries_syncer_map["linux_x64"].lambda_role.permissions_boundary == "arn:aws:iam::123456789012:policy/legacy-boundary" + && output.binaries_syncer_map["linux_x64"].lambda.environment[0].variables["LOG_LEVEL"] == "WARN" + && output.binaries_syncer_map["linux_x64"].lambda.tracing_config[0].mode == "Active" + && output.binaries_syncer_map["linux_x64"].lambda_log_group.retention_in_days == 14 + && output.binaries_syncer_map["linux_x64"].lambda_log_group.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/legacy-logs" + && output.binaries_syncer_map["linux_x64"].lambda_log_group.log_group_class == "STANDARD" + ) + error_message = "The stable v1 binary syncer must receive the same flat Lambda, network, role, and observability values through the translated configuration." + } + + assert { + condition = ( + output.instance_termination_watcher.lambda.function.runtime == "nodejs20.x" + && output.instance_termination_watcher.lambda.function.architectures == tolist(["x86_64"]) + && output.instance_termination_watcher.lambda.function.memory_size == 448 + && output.instance_termination_watcher.lambda.function.timeout == 35 + && output.instance_termination_watcher.lambda.function.s3_bucket == "lambda-artifacts" + && output.instance_termination_watcher.lambda.function.s3_key == "termination-watcher.zip" + && output.instance_termination_watcher.lambda.function.s3_object_version == "legacy-watcher-version" + && toset(output.instance_termination_watcher.lambda.function.vpc_config[0].subnet_ids) == toset(["subnet-legacy-lambda"]) + && toset(output.instance_termination_watcher.lambda.function.vpc_config[0].security_group_ids) == toset(["sg-legacy-lambda"]) + && output.instance_termination_watcher.lambda.function.tags["LegacyLambda"] == "legacy" + && !contains(keys(output.instance_termination_watcher.lambda.function.tags), "ExperimentalLambda") + && output.instance_termination_watcher.lambda_role.path == "/legacy/" + && output.instance_termination_watcher.lambda_role.permissions_boundary == "arn:aws:iam::123456789012:policy/legacy-boundary" + && output.instance_termination_watcher.lambda.function.environment[0].variables["GHES_URL"] == "https://legacy.example.com" + && output.instance_termination_watcher.lambda.function.environment[0].variables["LOG_LEVEL"] == "warn" + && output.instance_termination_watcher.lambda.function.tracing_config[0].mode == "Active" + && output.instance_termination_watcher.lambda_log_group.retention_in_days == 14 + && output.instance_termination_watcher.lambda_log_group.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/legacy-logs" + && output.instance_termination_watcher.lambda_log_group.log_group_class == "STANDARD" + ) + error_message = "The stable v1 termination watcher must receive flat component settings and translated global Lambda, role, GitHub, and observability values." + } + + assert { + condition = ( + length(module.ami_housekeeper) == 1 + && module.ami_housekeeper[0].lambda.runtime == "nodejs20.x" + && module.ami_housekeeper[0].lambda.architectures == tolist(["x86_64"]) + && module.ami_housekeeper[0].lambda.memory_size == 384 + && module.ami_housekeeper[0].lambda.timeout == 90 + && module.ami_housekeeper[0].lambda.s3_bucket == "lambda-artifacts" + && module.ami_housekeeper[0].lambda.s3_key == "ami-housekeeper.zip" + && module.ami_housekeeper[0].lambda.s3_object_version == "legacy-ami-housekeeper-version" + && module.ami_housekeeper[0].lambda.environment[0].variables["LOG_LEVEL"] == "WARN" + && jsondecode(module.ami_housekeeper[0].lambda.environment[0].variables["AMI_CLEANUP_OPTIONS"]).maxItems == 7 + && jsondecode(module.ami_housekeeper[0].lambda.environment[0].variables["AMI_CLEANUP_OPTIONS"]).minimumDaysOld == 14 + && jsondecode(module.ami_housekeeper[0].lambda.environment[0].variables["AMI_CLEANUP_OPTIONS"]).dryRun + && module.ami_housekeeper[0].lambda_role.path == "/legacy/" + && module.ami_housekeeper[0].lambda_role.permissions_boundary == "arn:aws:iam::123456789012:policy/legacy-boundary" + ) + error_message = "The stable v1 AMI housekeeper must preserve flat component settings through the translated compute-provider global while inheriting translated Lambda, role, and observability values." + } + + assert { + condition = ( + output.runners_map["linux"].lambda_up.environment[0].variables["LOG_LEVEL"] == "WARN" + && output.runners_map["linux"].lambda_up.environment[0].variables["POWERTOOLS_METRICS_NAMESPACE"] == "LegacyMetrics" + && output.runners_map["linux"].lambda_up.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "true" + && output.runners_map["linux"].lambda_up.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "false" + && output.runners_map["linux"].lambda_up_log_group.retention_in_days == 14 + && output.runners_map["linux"].lambda_up_log_group.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/legacy-logs" + && output.runners_map["linux"].lambda_up_log_group.log_group_class == "STANDARD" + && output.runners_map["linux"].lambda_up.tracing_config[0].mode == "Active" + && output.webhook.lambda.environment[0].variables["LOG_LEVEL"] == "WARN" + && output.webhook.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "true" + && output.webhook.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "false" + && output.webhook.lambda.tracing_config[0].mode == "Active" + && output.webhook.lambda_log_group.retention_in_days == 14 + && output.webhook.lambda_log_group.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/legacy-logs" + && output.webhook.lambda_log_group.log_group_class == "STANDARD" + ) + error_message = "Experimental observability globals must not override stable v1 logging, tracing, or metrics inputs." + } + + assert { + condition = ( + local.translated_experimental.ssm.paths.root == "/legacy-root/github-actions" + && local.translated_experimental.ssm.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/legacy-ssm" + && var.kms_key_arn == "arn:aws:kms:eu-west-1:123456789012:key/legacy-ssm" + && output.ssm_parameters.id.name == "/legacy-root/github-actions/legacy-app/github_app_id" + && output.webhook.lambda.environment[0].variables["PARAMETER_RUNNER_MATCHER_CONFIG_PATH"] == "/legacy-root/github-actions/legacy-webhook/runner-matcher-config" + && output.runners_map["linux"].lambda_up.environment[0].variables["SSM_TOKEN_PATH"] == "/legacy-root/github-actions/linux/legacy-runners/tokens" + && output.runners_map["linux"].lambda_up.environment[0].variables["SSM_CONFIG_PATH"] == "/legacy-root/github-actions/linux/legacy-runners/config" + && tomap({ + for tag in jsondecode(output.runners_map["linux"].lambda_up.environment[0].variables["SSM_PARAMETER_STORE_TAGS"]) : + tag.Key => tag.Value + }) == tomap({ + StableGlobal = "global" + LegacyParameter = "legacy" + "ghr:environment" = "github-actions-linux" + Precedence = "legacy-parameter" + }) + ) + error_message = "Experimental SSM globals must not affect stable v1 shared paths, runner paths, KMS selection, or parameter tags." + } + + assert { + condition = keys(output.runners_map) == ["linux"] + error_message = "Stable multi_runner_config must preserve the public runner map key." + } + + assert { + condition = length(output.runners_map_v2) == 0 + error_message = "Stable multi_runner_config must not add entries to the experimental runners_map_v2 output." + } + + assert { + condition = toset(keys(output.runners_map["linux"])) == toset( + [ + "launch_template_name", + "launch_template_id", + "launch_template_version", + "launch_template_ami_id", + "lambda_up", + "lambda_up_log_group", + "lambda_down", + "lambda_down_log_group", + "lambda_pool", + "lambda_pool_log_group", + "role_runner", + "role_scale_up", + "role_scale_down", + "role_pool", + "runners_log_groups", + "logfiles", + ] + ) + error_message = "Stable multi_runner_config must retain its existing flat runners_map entry shape." + } +} + +run "experimental_v2_routes_through_provider_stack" { + command = plan + + variables { + additional_github_apps = [{ + id_ssm = { + name = "/github-runner/additional-app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/additional-app-id" + } + key_base64_ssm = { + name = "/github-runner/additional-key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/additional-key-base64" + } + installation_id_ssm = { + name = "/github-runner/additional-installation-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/additional-installation-id" + } + }] + + tags = { + FlatModule = "ignored" + } + + repository_white_list = ["flat-owner/flat-repository"] + queue_selection_strategy = "all" + eventbridge = { + enable = false + accept_events = ["workflow_job"] + } + matcher_config_parameter_store_tier = "Advanced" + webhook_lambda_apigateway_access_log_settings = { + destination_arn = "arn:aws:logs:eu-west-1:123456789012:log-group:flat-api-access" + format = "$context.requestId" + } + webhook_lambda_s3_object_version = "flat-webhook-version" + + role_path = "/flat-role/" + role_permissions_boundary = "arn:aws:iam::123456789012:policy/flat-boundary" + ghes_url = "https://flat.example.com" + ghes_ssl_verify = false + user_agent = "flat-user-agent" + + lambda_runtime = "nodejs20.x" + lambda_architecture = "x86_64" + runners_lambda_zip = "flat-runners-ignored.zip" + lambda_subnet_ids = ["subnet-flat-lambda"] + lambda_security_group_ids = ["sg-flat-lambda"] + lambda_principals = [{ + type = "AWS" + identifiers = ["arn:aws:iam::123456789012:role/flat-lambda-principal"] + }] + scale_up_lambda_memory_size = 600 + runners_scale_up_lambda_timeout = 45 + scale_down_lambda_memory_size = 700 + runners_scale_down_lambda_timeout = 75 + webhook_lambda_memory_size = 384 + webhook_lambda_timeout = 20 + runner_binaries_syncer_memory_size = 704 + runner_binaries_syncer_lambda_timeout = 80 + pool_lambda_timeout = 90 + pool_lambda_reserved_concurrent_executions = 3 + lambda_event_source_mapping_batch_size = 7 + lambda_event_source_mapping_maximum_batching_window_in_seconds = 2 + log_level = "error" + logging_retention_in_days = 60 + logging_kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/flat-logs" + log_class = "INFREQUENT_ACCESS" + kms_key_arn = null + + queue_encryption = { + kms_data_key_reuse_period_seconds = 600 + kms_master_key_id = "arn:aws:kms:eu-west-1:123456789012:key/flat-queue" + sqs_managed_sse_enabled = null + } + + lambda_tags = { + FlatLambda = "ignored" + } + + enable_managed_runner_security_group = false + runner_additional_security_group_ids = ["sg-flat-runner"] + cloudwatch_config = "flat-cloudwatch-config" + instance_profile_path = "/flat-instance-profile/" + key_name = "flat-key" + associate_public_ipv4_address = true + + runner_egress_rules = [{ + cidr_blocks = ["10.0.0.0/8"] + ipv6_cidr_blocks = [] + prefix_list_ids = [] + from_port = 443 + protocol = "tcp" + security_groups = [] + self = false + to_port = 443 + description = "flat-only" + }] + + tracing_config = { + mode = "Active" + capture_http_requests = true + capture_error = false + } + + metrics = { + enable = true + namespace = "FlatMetrics" + metric = { + enable_github_app_rate_limit = false + enable_job_retry = true + enable_spot_termination_warning = false + } + } + + ssm_paths = { + root = "flat-root" + app = "flat-app" + runners = "flat-runners" + webhook = "flat-webhook" + } + + parameter_store_tags = { + FlatParameter = "flat" + } + + runners_ssm_housekeeper = { + schedule_expression = "rate(8 hours)" + enabled = false + lambda_memory_size = 640 + lambda_timeout = 55 + config = { + tokenPath = "/flat/cleanup/tokens" + minimumDaysOld = 4 + dryRun = true + } + } + + instance_termination_watcher = { + enable = true + memory_size = 900 + timeout = 90 + s3_key = "flat-termination-watcher.zip" + environment_variables = { + FLAT_WATCHER = "ignored" + } + } + + enable_ami_housekeeper = true + ami_housekeeper_lambda_memory_size = 900 + ami_housekeeper_lambda_timeout = 90 + ami_housekeeper_lambda_s3_key = "flat-ami-housekeeper.zip" + ami_housekeeper_lambda_schedule_expression = "rate(1 hour)" + + multi_runner_config = { + legacy = { + runner_config = { + runner_os = "linux" + runner_architecture = "x64" + instance_types = ["t3.large"] + runners_maximum_count = 1 + enable_runner_binaries_syncer = false + } + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "legacy"]] + } + } + } + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + additional_apps = [{ + id_ssm = { + name = "/github-runner/additional-app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/additional-app-id" + } + key_base64_ssm = { + name = "/github-runner/additional-key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/additional-key-base64" + } + installation_id_ssm = { + name = "/github-runner/additional-installation-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/additional-installation-id" + } + }] + } + + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-experimental-defaults" + subnet_ids = ["subnet-experimental-defaults"] + runner_binaries = { + syncer = { + artifact = { + zip = "README.md" + } + } + } + } + } + + multi_runner_config = { + linux = { + runner = { + os = "linux" + architecture = "x64" + hooks = { + job_started = "/opt/actions/job-started.sh" + } + iam = { + managed_policy_arns = { + readonly = "arn:aws:iam::aws:policy/ReadOnlyAccess" + } + } + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + github = { + organization_runners = true + } + + lambda = { + scale = { + down = { + idle_config = [{ + cron = "* * * * *" + timeZone = "UTC" + idleCount = 1 + }] + } + } + + pool = { + config = [{ + schedule_expression = "cron(0 8 * * ? *)" + size = 1 + }] + } + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + enableDynamicLabels = true + awsDynamicLabelsPolicy = { + blocked_keys = ["image-id"] + restricted_keys = { + "instance-type" = { + allowed = ["m5.*", "c5.*"] + denied = ["*.metal"] + } + "ebs-volume-size" = { + max = 200 + } + } + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = true + } + } + } + } + } + } + } + + assert { + condition = ( + local.use_multi_runner_config_v2 + && jsonencode(local.raw_translated_experimental) == jsonencode(var.experimental) + ) + error_message = "A non-empty experimental v2 map must pass through the exact experimental object without translation-time default resolution or stable-input fallback." + } + + assert { + condition = keys(local.runner_config_by_provider.ec2) == ["linux"] + error_message = "Experimental multi_runner_config entries must route to the EC2 provider." + } + + assert { + condition = ( + local.compute_provider_types["linux"] == "ec2" + && local.runner_matcher_config["linux"].computeProvider == "ec2" + ) + error_message = "Compute-provider selection must supply the webhook routing contract." + } + + assert { + condition = toset(keys(module.runner_configs)) == toset(["linux"]) && toset(keys(local.translated_experimental.multi_runner_config)) == toset(["linux"]) + error_message = "Experimental multi_runner_config entries must remain isolated in the v2 configuration map." + } + + assert { + condition = ( + toset(keys(local.translated_experimental_base.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer)) == toset(["enabled"]) + && toset(keys(local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer)) == toset(["enabled", "s3"]) + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.binaries_syncer.s3 != null + && keys(output.binaries_syncer_map) == ["linux_x64"] + ) + error_message = "V2 binary discovery must use the pure base runner configuration, enrich the final canonical configuration with S3, and create the corresponding shared syncer resources." + } + + assert { + condition = toset(flatten(local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.matcherConfig.labelMatchers)) == toset(["self-hosted", "linux", "x64"]) + error_message = "The canonical experimental runner configuration must retain labels declared by its matcher configuration for the runner adapter." + } + + assert { + condition = ( + local.runner_matcher_config["linux"].matcherConfig.awsDynamicLabelsPolicy.blocked_keys == tolist(["image-id"]) + && local.runner_matcher_config["linux"].matcherConfig.awsDynamicLabelsPolicy.restricted_keys["instance-type"].allowed == tolist(["m5.*", "c5.*"]) + && local.runner_matcher_config["linux"].matcherConfig.awsDynamicLabelsPolicy.restricted_keys["instance-type"].denied == tolist(["*.metal"]) + && local.runner_matcher_config["linux"].matcherConfig.awsDynamicLabelsPolicy.restricted_keys["ebs-volume-size"].max == "200" + ) + error_message = "Experimental matcher config must preserve the typed AWS dynamic-label policy contract." + } + + assert { + condition = length(module.runners) == 0 && keys(module.runner_configs) == ["linux"] + error_message = "A non-empty experimental.multi_runner_config map must take priority over stable multi_runner_config and dispatch only through module.runner_configs." + } + + assert { + condition = ( + length(local.translated_experimental.tags) == 0 + && local.translated_experimental.roles.path == null + && local.translated_experimental.roles.permissions_boundary == null + && !local.translated_experimental.multi_runner_config["linux"].runner.disable_default_labels + && local.translated_experimental.multi_runner_config["linux"].runner.group_name == "Default" + && local.translated_experimental.multi_runner_config["linux"].runner.name_prefix == "" + && !local.translated_experimental.multi_runner_config["linux"].runner.run_as_root + && local.translated_experimental.multi_runner_config["linux"].runner.run_as == "ec2-user" + && !local.translated_experimental.multi_runner_config["linux"].runner.auto_update_disabled + && local.translated_experimental.multi_runner_config["linux"].runner.hooks.job_completed == "" + && local.translated_experimental.multi_runner_config["linux"].runner.iam.path == null + && local.translated_experimental.multi_runner_config["linux"].runner.iam.permissions_boundary == null + && !contains(keys(local.translated_experimental.multi_runner_config["linux"].runner), "boot_time_in_minutes") + && !contains(keys(local.translated_experimental.multi_runner_config["linux"].runner), "ephemeral") + && !contains(keys(local.translated_experimental.multi_runner_config["linux"].runner), "jit_config_enabled") + && !contains(keys(local.translated_experimental.multi_runner_config["linux"].runner), "maximum_count") + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.boot_time_in_minutes == 5 + && !local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.ephemeral + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.jit_config_enabled == null + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.runner.maximum_count == 2 + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "2" + && module.runner_configs["linux"].orchestration.webhook.scale_down.lambda.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "5" + && module.runner_configs["linux"].orchestration.webhook.pool.lambda.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "2" + && module.runner_configs["linux"].orchestration.webhook.pool.lambda.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "5" + ) + error_message = "Experimental v2 common runner defaults must stay provider-neutral while webhook-owned lifecycle, capacity, and boot time reach their controls without stable-input fallback." + } + + assert { + condition = ( + local.translated_experimental.orchestration.webhook.lambda.artifact.zip == "README.md" + && local.translated_experimental.orchestration.webhook.lambda.artifact.s3 == null + && local.translated_experimental.lambda.artifact.s3.bucket == null + && local.translated_experimental.multi_runner_config["linux"].lambda.artifact.s3.bucket == null + && toset(keys(local.translated_experimental.multi_runner_config["linux"].lambda)) == toset([ + "artifact", + "runtime", + "architecture", + "subnet_ids", + "security_group_ids", + "tags", + "role", + "principals", + ]) + && !contains(keys(local.translated_experimental.multi_runner_config["linux"].lambda), "zip") + && !contains(keys(local.translated_experimental.multi_runner_config["linux"].lambda), "s3") + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.artifact.zip == "README.md" + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.artifact.s3 == null + && toset(keys(local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda)) == toset([ + "artifact", + "scale", + "pool", + ]) + && toset(keys(local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale)) == toset([ + "up", + "down", + ]) + && toset(keys(local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue)) == toset([ + "delay_webhook_event", + "job_queue_retention_in_seconds", + "visibility_timeout_seconds", + "redrive_build_queue", + "tags", + "kms_key_id", + ]) + && length(local.translated_experimental.lambda.principals) == 0 + && local.translated_experimental.multi_runner_config["linux"].lambda.runtime == "nodejs24.x" + && local.translated_experimental.multi_runner_config["linux"].lambda.architecture == "arm64" + && length(local.translated_experimental.multi_runner_config["linux"].lambda.subnet_ids) == 0 + && length(local.translated_experimental.multi_runner_config["linux"].lambda.security_group_ids) == 0 + && length(local.translated_experimental.multi_runner_config["linux"].lambda.tags) == 0 + && local.translated_experimental.multi_runner_config["linux"].lambda.role.path == null + && local.translated_experimental.multi_runner_config["linux"].lambda.role.permissions_boundary == null + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.runtime == "nodejs24.x" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.filename == "README.md" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.s3_bucket == null + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.memory_size == 512 + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.timeout == 30 + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale.up.reserved_concurrent_executions == 1 + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale.up.job_queued_check_enabled == null + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size == 10 + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds == 0 + && module.runner_configs["linux"].orchestration.webhook.scale_down.lambda.memory_size == 512 + && module.runner_configs["linux"].orchestration.webhook.scale_down.lambda.timeout == 60 + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale.down.schedule_expression == "cron(*/5 * * * ? *)" + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes == null + && module.runner_configs["linux"].orchestration.webhook.pool.lambda.memory_size == 512 + && module.runner_configs["linux"].orchestration.webhook.pool.lambda.timeout == 60 + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.pool.reserved_concurrent_executions == 1 + && !local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.pool.include_busy_runners + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.lambda.pool.runner_owner == null + ) + error_message = "Experimental v2 runner-config Lambda components must inherit the concrete nested defaults and ignore every corresponding stable Lambda input." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.delay_webhook_event == 30 + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.job_queue_retention_in_seconds == 86400 + && local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.visibility_timeout_seconds == 180 + && !local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.redrive_build_queue.enabled + && length(local.translated_experimental.multi_runner_config["linux"].orchestration.webhook.queue.tags) == 0 + && local.translated_experimental.orchestration.webhook.queue.encryption == var.experimental.orchestration.webhook.queue.encryption + && local.translated_experimental.orchestration.webhook.queue.encryption.sqs_managed_sse_enabled + && local.translated_experimental.orchestration.webhook.queue.encryption.kms_master_key_id == null + && local.translated_experimental.orchestration.webhook.queue.encryption.kms_data_key_reuse_period_seconds == null + && aws_sqs_queue.queued_builds["linux"].delay_seconds == 30 + && aws_sqs_queue.queued_builds["linux"].message_retention_seconds == 86400 + && aws_sqs_queue.queued_builds["linux"].visibility_timeout_seconds == 180 + && aws_sqs_queue.queued_builds["linux"].sqs_managed_sse_enabled + && aws_sqs_queue.queued_builds["linux"].kms_master_key_id == null + ) + error_message = "Experimental v2 queues must use orchestration.webhook.queue defaults, including a six-times-Lambda visibility timeout and SQS-managed encryption, instead of stable flat inputs." + } + + assert { + condition = ( + local.translated_experimental.github.app == var.experimental.github.app + && local.translated_experimental.github.additional_apps == var.experimental.github.additional_apps + && length(local.translated_experimental.orchestration.webhook.github.repository_white_list) == 0 + && !contains(keys(local.translated_experimental), "enterprise_server") + && !contains(keys(local.translated_experimental), "user_agent") + && local.translated_experimental.github.enterprise_server == var.experimental.github.enterprise_server + && local.translated_experimental.github.user_agent == var.experimental.github.user_agent + && local.translated_experimental.github.enterprise_server.url == null + && local.translated_experimental.github.enterprise_server.ssl_verify + && local.translated_experimental.github.user_agent == "github-aws-runners" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["GHES_URL"] == null + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["NODE_TLS_REJECT_UNAUTHORIZED"] == "1" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["USER_AGENT"] == "github-aws-runners" + && module.runner_configs["linux"].orchestration.webhook.scale_down.lambda.environment[0].variables["USER_AGENT"] == "github-aws-runners" + && module.runner_configs["linux"].orchestration.webhook.pool.lambda.environment[0].variables["USER_AGENT"] == "github-aws-runners" + ) + error_message = "V2 runner configurations must use concrete nested GitHub connection defaults and the webhook-owned repository allow-list rather than deliberately different flat inputs." + } + + assert { + condition = ( + local.translated_experimental.orchestration.webhook.queue_selection_strategy == "first" + && local.translated_experimental.orchestration.webhook.eventbridge.enable + && length(local.translated_experimental.orchestration.webhook.eventbridge.accept_events) == 0 + && local.translated_experimental.orchestration.webhook.matcher_config_parameter_store_tier == "Standard" + && local.translated_experimental.orchestration.webhook.lambda.webhook.artifact.zip == "README.md" + && local.translated_experimental.orchestration.webhook.lambda.webhook.artifact.s3 == null + && local.translated_experimental.orchestration.webhook.lambda.webhook.api_gateway_access_log_settings == null + && local.translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size == 10 + && local.translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds == 0 + ) + error_message = "V2 webhook controls, the explicitly nested local artifact, API access-log defaults, and scale-up event-source mappings must avoid flat-input fallback." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["linux"].observability.logs.level == "info" + && local.translated_experimental.multi_runner_config["linux"].observability.logs.retention_in_days == 180 + && local.translated_experimental.multi_runner_config["linux"].observability.logs.kms_key_id == null + && local.translated_experimental.multi_runner_config["linux"].observability.logs.class == "STANDARD" + && length(local.translated_experimental.multi_runner_config["linux"].observability.logs.tags) == 0 + && local.translated_experimental.multi_runner_config["linux"].observability.tracing.mode == null + && !local.translated_experimental.multi_runner_config["linux"].observability.tracing.capture_http_requests + && !local.translated_experimental.multi_runner_config["linux"].observability.tracing.capture_error + && !local.translated_experimental.multi_runner_config["linux"].observability.metrics.enable + && local.translated_experimental.multi_runner_config["linux"].observability.metrics.namespace == "GitHub Runners" + && local.translated_experimental.multi_runner_config["linux"].observability.metrics.metric.enable_github_app_rate_limit + && local.translated_experimental.multi_runner_config["linux"].observability.metrics.metric.enable_job_retry + ) + error_message = "Experimental v2 observability must use its concrete nested logging, tracing, and metrics defaults instead of stable inputs." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["linux"].ssm.paths.root == "/github-action-runners/github-actions/linux" + && local.translated_experimental.multi_runner_config["linux"].ssm.paths.tokens == "runners/tokens" + && local.translated_experimental.multi_runner_config["linux"].ssm.paths.config == "runners/config" + && var.kms_key_arn == null + && local.translated_experimental.ssm.kms_key_id == null + && length(local.translated_experimental.multi_runner_config["linux"].ssm.tags) == 0 + && length(local.translated_experimental.multi_runner_config["linux"].ssm.parameters.tags) == 0 + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.schedule_expression == "rate(1 day)" + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.state == "ENABLED" + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.lambda.memory_size == 512 + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.lambda.timeout == 60 + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.lambda.artifact.zip == "README.md" + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.lambda.artifact.s3 == null + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.config.tokenPath == null + && local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.config.minimumDaysOld == 1 + && !local.translated_experimental.multi_runner_config["linux"].ssm.housekeeper.config.dryRun + ) + error_message = "Experimental v2 SSM must use self-contained path, tag, and housekeeper defaults without deriving ownership or values from stable SSM inputs." + } + + assert { + condition = ( + module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["LOG_LEVEL"] == "INFO" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_METRICS_NAMESPACE"] == "GitHub Runners" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "false" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "false" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_TOKEN_PATH"] == "/github-action-runners/github-actions/linux/runners/tokens" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_CONFIG_PATH"] == "/github-action-runners/github-actions/linux/runners/config" + && module.runner_configs["linux"].orchestration.webhook.scale_up.log_group.retention_in_days == 180 + && module.runner_configs["linux"].orchestration.webhook.scale_up.log_group.kms_key_id == null + && module.runner_configs["linux"].orchestration.webhook.scale_up.log_group.log_group_class == "STANDARD" + && length(module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.tracing_config) == 0 + && jsondecode(module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_PARAMETER_STORE_TAGS"]) == [{ + Key = "ghr:environment" + Value = "github-actions" + }] + ) + error_message = "Concrete experimental observability and SSM defaults must reach runner-config resources without stable-input leakage." + } + + assert { + condition = ( + output.webhook.lambda.runtime == "nodejs24.x" + && output.webhook.lambda.architectures == tolist(["arm64"]) + && output.webhook.lambda.memory_size == 256 + && output.webhook.lambda.timeout == 10 + && output.webhook.lambda.s3_bucket == null + && output.webhook.lambda.s3_key == null + && output.webhook.lambda.s3_object_version == null + && length(output.webhook.lambda.vpc_config) == 1 + && length(output.webhook.lambda.vpc_config[0].subnet_ids) == 0 + && length(output.webhook.lambda.vpc_config[0].security_group_ids) == 0 + && !contains(keys(output.webhook.lambda.tags), "FlatModule") + && !contains(keys(output.webhook.lambda.tags), "FlatLambda") + && output.webhook.lambda_role.path == "/github-actions/" + && output.webhook.lambda_role.permissions_boundary == null + && output.webhook.eventbridge != null + && output.webhook.dispatcher != null + && jsondecode(output.webhook.dispatcher.lambda.environment[0].variables["REPOSITORY_ALLOW_LIST"]) == [] + && output.webhook.dispatcher.lambda.environment[0].variables["QUEUE_SELECTION_STRATEGY"] == "first" + && output.webhook.lambda.environment[0].variables["PARAMETER_RUNNER_MATCHER_CONFIG_PATH"] == "/github-action-runners/github-actions/webhook/runner-matcher-config" + && output.webhook.lambda.environment[0].variables["LOG_LEVEL"] == "INFO" + && output.webhook.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "false" + && output.webhook.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "false" + && length(output.webhook.lambda.tracing_config) == 0 + && output.webhook.lambda_log_group.retention_in_days == 180 + && output.webhook.lambda_log_group.kms_key_id == null + && output.webhook.lambda_log_group.log_group_class == "STANDARD" + && var.kms_key_arn == null + ) + error_message = "The shared webhook must use translated v2 Lambda, nested artifact, network, tag, role, SSM/KMS, and observability values without flat-input leakage." + } + + assert { + condition = ( + local.translated_experimental.ssm.paths.app == "app" + && output.ssm_parameters.id.name == "/github-action-runners/github-actions/app/github_app_id" + ) + error_message = "Shared SSM parameters must use the translated v2 root and app defaults instead of flat ssm_paths." + } + + assert { + condition = ( + local.translated_experimental.compute_provider.ec2.runner_binaries.enabled + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.encryption.enabled + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm == "AES256" + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.encryption.kms_master_key_id == null + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.versioning == "Disabled" + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.logging.bucket == null + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.logging.prefix == null + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.artifact.zip == "README.md" + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3 == null + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.lambda.memory_size == 256 + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.lambda.timeout == 300 + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.schedule.expression == "cron(27 * * * ? *)" + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.schedule.state == "ENABLED" + ) + error_message = "The nested v2 runner-binary block must own concrete defaults independently of matching flat syncer and bucket inputs." + } + + assert { + condition = ( + keys(output.binaries_syncer_map) == ["linux_x64"] + && output.binaries_syncer_map["linux_x64"].lambda.runtime == "nodejs24.x" + && output.binaries_syncer_map["linux_x64"].lambda.architectures == tolist(["arm64"]) + && output.binaries_syncer_map["linux_x64"].lambda.memory_size == 256 + && output.binaries_syncer_map["linux_x64"].lambda.timeout == 300 + && output.binaries_syncer_map["linux_x64"].lambda.filename == "README.md" + && output.binaries_syncer_map["linux_x64"].lambda.s3_bucket == null + && output.binaries_syncer_map["linux_x64"].lambda.s3_key == null + && output.binaries_syncer_map["linux_x64"].lambda.s3_object_version == null + && length(output.binaries_syncer_map["linux_x64"].lambda.vpc_config) == 1 + && length(output.binaries_syncer_map["linux_x64"].lambda.vpc_config[0].subnet_ids) == 0 + && length(output.binaries_syncer_map["linux_x64"].lambda.vpc_config[0].security_group_ids) == 0 + && !contains(keys(output.binaries_syncer_map["linux_x64"].lambda.tags), "FlatModule") + && !contains(keys(output.binaries_syncer_map["linux_x64"].lambda.tags), "FlatLambda") + && output.binaries_syncer_map["linux_x64"].lambda_role.path == "/github-actions-linux-x64/" + && output.binaries_syncer_map["linux_x64"].lambda_role.permissions_boundary == null + && output.binaries_syncer_map["linux_x64"].lambda.environment[0].variables["LOG_LEVEL"] == "INFO" + && length(output.binaries_syncer_map["linux_x64"].lambda.tracing_config) == 0 + && output.binaries_syncer_map["linux_x64"].lambda_log_group.retention_in_days == 180 + && output.binaries_syncer_map["linux_x64"].lambda_log_group.kms_key_id == null + && output.binaries_syncer_map["linux_x64"].lambda_log_group.log_group_class == "STANDARD" + ) + error_message = "The v2 binary syncer must inherit translated global Lambda, role, tags, observability, artifact, and component defaults without flat-input leakage." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.vpc_id == "vpc-experimental-defaults" + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.subnet_ids == tolist(["subnet-experimental-defaults"]) + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.managed_security_group_enabled + && length(local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.egress_rules) == 1 + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.egress_rules[0].cidr_blocks == tolist(["0.0.0.0/0"]) + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.egress_rules[0].ipv6_cidr_blocks == tolist(["::/0"]) + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.egress_rules[0].protocol == "-1" + && length(local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.additional_security_group_ids) == 0 + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.cloudwatch_agent.config == null + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.instance_profile_path == null + && local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.key_name == null + && !local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.associate_public_ipv4_address + && length(local.translated_experimental.multi_runner_config["linux"].compute_provider.ec2.tags) == 0 + && !local.translated_experimental.compute_provider.ec2.ami.housekeeper.enabled + && !local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enabled + && length(module.ami_housekeeper) == 0 + && length(module.instance_termination_watcher) == 0 + && output.instance_termination_watcher == null + ) + error_message = "V2 EC2 runner configurations must use nested network inputs and concrete nested EC2 defaults instead of corresponding stable inputs." + } + + assert { + condition = ( + local.translated_experimental.github.app == var.experimental.github.app + && local.translated_experimental.github.additional_apps == var.experimental.github.additional_apps + && local.translated_experimental.github.app == var.github_app + && local.translated_experimental.github.additional_apps == var.additional_github_apps + && length(local.github_app_parameters.id) == 2 + && length(module.ssm.additional_app_parameters) == 1 + && module.ssm.additional_app_parameters[0].id.name == "/github-runner/additional-app-id" + && module.runner_configs["linux"].orchestration.webhook.scale_up.lambda.environment[0].variables["PARAMETER_GITHUB_APP_ID_NAME"] == join(":", [for p in local.github_app_parameters.id : p.name]) + && module.runner_configs["linux"].orchestration.webhook.scale_down.lambda.environment[0].variables["PARAMETER_GITHUB_APP_KEY_BASE64_NAME"] == join(":", [for p in local.github_app_parameters.key_base64 : p.name]) + && module.runner_configs["linux"].orchestration.webhook.pool.lambda.environment[0].variables["PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME"] == join(":", [for p in local.github_app_parameters.installation_id : p != null ? p.name : ""]) + ) + error_message = "Experimental v2 control-plane Lambdas must preserve the complete multi-app parameter lists from the shared multi-runner configuration." + } + + assert { + condition = keys(aws_sqs_queue.queued_builds) == ["linux"] && keys(local.runner_matcher_config) == ["linux"] + error_message = "Common queues and webhook matcher configuration must contain only the selected experimental runner configuration key." + } + + assert { + condition = length(output.runners_map) == 0 + error_message = "Experimental multi_runner_config must not add nested entries to the stable runners_map output." + } + + assert { + condition = keys(output.runners_map_v2) == ["linux"] + error_message = "Experimental multi_runner_config must expose its runner configuration key through runners_map_v2." + } + + assert { + condition = toset(keys(output.runners_map_v2["linux"])) == toset( + [ + "provider", + "runner", + "orchestration", + "scale_up", + "scale_down", + "pool", + ] + ) + error_message = "Experimental v2 runners_map_v2 entries must add canonical orchestration while retaining the existing component aliases." + } + + assert { + condition = ( + toset(keys(output.runners_map_v2["linux"].runner)) == toset(["role"]) + && toset(keys(output.runners_map_v2["linux"].orchestration.webhook.scale_up)) == toset(["lambda", "log_group", "role"]) + && toset(keys(output.runners_map_v2["linux"].orchestration.webhook.scale_down)) == toset(["lambda", "log_group", "role"]) + && toset(keys(output.runners_map_v2["linux"].orchestration.webhook.pool)) == toset(["lambda", "log_group", "role"]) + && output.runners_map_v2["linux"].scale_up == output.runners_map_v2["linux"].orchestration.webhook.scale_up + && output.runners_map_v2["linux"].scale_down == output.runners_map_v2["linux"].orchestration.webhook.scale_down + && output.runners_map_v2["linux"].pool == output.runners_map_v2["linux"].orchestration.webhook.pool + ) + error_message = "Experimental v2 common resources must use the nested runner and orchestration contracts while preserving compatibility output aliases." + } + + assert { + condition = ( + toset(keys(output.runners_map_v2["linux"].provider)) == toset(["ec2"]) + && toset(keys(output.runners_map_v2["linux"].provider.ec2)) == toset([ + "launch_template", + "runners_log_groups", + "logfiles", + ]) + ) + error_message = "Experimental v2 must expose only EC2-owned resources under runners_map_v2..provider.ec2." + } + + assert { + condition = ( + !contains(keys(output.runners_map_v2["linux"]), "launch_template_name") + && output.runners_map_v2["linux"].runner.role != null + && !contains(keys(output.runners_map_v2["linux"].provider.ec2), "role_runner") + && !contains(keys(output.runners_map_v2["linux"]), "runners_log_groups") + && !contains(keys(output.runners_map_v2["linux"]), "logfiles") + ) + error_message = "Experimental v2 must expose only its nested schema through runners_map_v2 without legacy flat fields." + } + + assert { + condition = local.runner_config_by_provider.ec2["linux"].orchestration.webhook.lambda.scale.down.idle_config[0].idleCount == 1 + error_message = "Webhook-owned idle configuration must remain in the orchestration provider input contract." + } + + assert { + condition = local.runner_config_by_provider.ec2["linux"].runner.iam.managed_policy_arns.readonly == "arn:aws:iam::aws:policy/ReadOnlyAccess" + error_message = "Runner-role policies must remain in the common runner contract." + } + + assert { + condition = ( + local.runner_config_by_provider.ec2["linux"].runner.hooks.job_started == "/opt/actions/job-started.sh" + && !contains(keys(local.runner_config_by_provider.ec2["linux"].compute_provider.ec2), "hooks") + ) + error_message = "Runner lifecycle hooks must remain in the common runner contract." + } +} + +run "experimental_v2_rejects_missing_orchestration_block" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-orchestration" + subnet_ids = ["subnet-missing-orchestration"] + } + } + multi_runner_config = { + invalid = { + runner = { + os = "linux" + architecture = "x64" + } + orchestration = {} + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_requires_webhook_maximum_count" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-webhook-maximum" + subnet_ids = ["subnet-missing-webhook-maximum"] + } + } + multi_runner_config = { + invalid = { + runner = { + os = "linux" + architecture = "x64" + } + orchestration = { + webhook = { + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_applies_global_defaults_and_configuration_overrides" { + command = plan + + variables { + lambda_runtime = "nodejs20.x" + lambda_s3_bucket = "flat-lambda-artifacts" + role_path = "/flat/" + runner_egress_rules = null + ghes_url = "https://flat-termination.example.com" + ghes_ssl_verify = true + user_agent = "flat-shared-user-agent" + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/experimental-queue" + runners_lambda_s3_key = "flat-runners-ignored.zip" + runners_lambda_s3_object_version = "flat-runners-ignored-version" + repository_white_list = ["flat-owner/flat-repository"] + queue_selection_strategy = "random" + eventbridge = { + enable = true + accept_events = ["push"] + } + matcher_config_parameter_store_tier = "Standard" + webhook_lambda_apigateway_access_log_settings = { + destination_arn = "arn:aws:logs:eu-west-1:123456789012:log-group:flat-api-access" + format = "$context.requestId" + } + webhook_lambda_s3_object_version = "flat-webhook-version" + + lambda_principals = [{ + type = "AWS" + identifiers = ["arn:aws:iam::123456789012:role/flat-lambda-principal"] + }] + + instance_termination_watcher = { + enable = false + memory_size = 999 + timeout = 99 + s3_key = "flat-termination-watcher.zip" + } + + enable_ami_housekeeper = false + ami_housekeeper_lambda_memory_size = 999 + ami_housekeeper_lambda_timeout = 99 + ami_housekeeper_lambda_s3_key = "flat-ami-housekeeper.zip" + ami_housekeeper_lambda_schedule_expression = "rate(1 hour)" + + experimental = { + roles = { + path = "/experimental/" + } + + runner = { + os = "linux" + architecture = "x64" + group_name = "global-group" + } + + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + enterprise_server = { + url = "https://experimental-shared.example.com" + ssl_verify = false + } + user_agent = "experimental-runner-user-agent" + } + + lambda = { + artifact = { + s3 = { + bucket = "experimental-lambda-artifacts" + } + } + runtime = "nodejs22.x" + principals = [{ + type = "Service" + identifiers = ["states.amazonaws.com"] + }] + } + + orchestration = { + webhook = { + runner = { + boot_time_in_minutes = 6 + ephemeral = true + jit_config_enabled = true + maximum_count = 2 + } + + github = { + repository_white_list = ["nested-owner/nested-repository"] + } + + queue_selection_strategy = "all" + eventbridge = { + enable = false + accept_events = ["workflow_job"] + } + matcher_config_parameter_store_tier = "Advanced" + + lambda = { + artifact = { + s3 = { + key = "nested-runners.zip" + object_version = "nested-runners-version" + } + } + + scale = { + up = { + memory_size = 768 + timeout = 40 + event_source_mapping = { + batch_size = 25 + } + } + + down = { + timeout = 75 + } + } + + webhook = { + artifact = { + s3 = { + key = "nested-webhook.zip" + object_version = "nested-webhook-version" + } + } + api_gateway_access_log_settings = { + destination_arn = "arn:aws:logs:eu-west-1:123456789012:log-group:nested-api-access" + format = "$context.requestId $context.status" + } + memory_size = 384 + } + + pool = { + memory_size = 384 + config = [{ + schedule_expression = "cron(0 8 * * ? *)" + size = 1 + }] + } + } + + queue = { + delay_webhook_event = 23 + job_queue_retention_in_seconds = 172800 + visibility_timeout_seconds = 240 + redrive_build_queue = { + enabled = true + maxReceiveCount = 7 + } + tags = { + GlobalQueue = "global" + Precedence = "global" + } + encryption = { + kms_data_key_reuse_period_seconds = 900 + kms_master_key_id = "arn:aws:kms:eu-west-1:123456789012:key/experimental-queue" + sqs_managed_sse_enabled = null + } + } + } + } + + ssm = { + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/experimental-queue" + housekeeper = { + lambda = { + artifact = { + s3 = { + key = "global-ssm-housekeeper.zip" + object_version = "global-ssm-housekeeper-version" + } + } + } + } + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-experimental" + subnet_ids = ["subnet-experimental"] + ami = { + housekeeper = { + enabled = true + cleanup_config = { + maxItems = 5 + minimumDaysOld = 10 + dryRun = true + } + artifact = { + s3 = { + key = "nested-ami-housekeeper.zip" + object_version = "nested-ami-housekeeper-version" + } + } + lambda = { + memory_size = 448 + timeout = 120 + } + schedule = { + expression = "rate(3 days)" + } + } + } + instance_termination_watcher = { + enabled = true + features = { + enable_spot_termination_handler = false + enable_spot_termination_notification_watcher = true + } + enable_runner_deregistration = true + environment_variables = { + NESTED_WATCHER = "true" + } + artifact = { + s3 = { + key = "nested-termination-watcher.zip" + object_version = "nested-watcher-version" + } + } + lambda = { + memory_size = 432 + timeout = 41 + } + } + runner_binaries = { + enabled = false + s3 = { + tags = { + BinaryBucket = "global" + } + versioning = "Enabled" + logging = { + bucket = "runner-binaries-access-logs" + prefix = "runner-binaries/" + } + } + syncer = { + artifact = { + s3 = { + key = "nested-runner-binaries-syncer.zip" + object_version = "nested-version" + } + } + lambda = { + memory_size = 384 + timeout = 240 + } + schedule = { + expression = "rate(2 hours)" + state = "DISABLED" + } + } + } + } + } + + multi_runner_config = { + resolved = { + runner = { + group_name = "lane-group" + } + + lambda = { + role = { + path = "/lane-lambda/" + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + orchestration = { + webhook = { + runner = { + boot_time_in_minutes = 7 + ephemeral = false + jit_config_enabled = false + maximum_count = 4 + } + + lambda = { + scale = { + up = { + memory_size = 896 + event_source_mapping = { + batch_size = 50 + } + } + } + + pool = { + memory_size = 448 + } + } + + queue = { + delay_webhook_event = 11 + visibility_timeout_seconds = 300 + tags = { + LaneQueue = "lane" + Precedence = "lane" + } + } + + job_retry = { + enabled = true + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "resolved"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + subnet_ids = ["subnet-lane"] + binaries_syncer = { + enabled = true + } + } + } + } + } + } + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["resolved"].runner.os == "linux" + && local.translated_experimental.multi_runner_config["resolved"].runner.architecture == "x64" + && !contains(keys(local.translated_experimental.multi_runner_config["resolved"].runner), "boot_time_in_minutes") + && !contains(keys(local.translated_experimental.multi_runner_config["resolved"].runner), "ephemeral") + && !contains(keys(local.translated_experimental.multi_runner_config["resolved"].runner), "jit_config_enabled") + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.runner.boot_time_in_minutes == 7 + && !local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.runner.ephemeral + && !local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.runner.jit_config_enabled + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.runner.maximum_count == 4 + && local.translated_experimental.multi_runner_config["resolved"].runner.group_name == "lane-group" + && local.translated_experimental.ssm.housekeeper.lambda.artifact.s3.key == "global-ssm-housekeeper.zip" + && local.translated_experimental.multi_runner_config["resolved"].ssm.housekeeper.lambda.artifact.zip == "README.md" + && local.translated_experimental.multi_runner_config["resolved"].ssm.housekeeper.lambda.artifact.s3 == null + ) + error_message = "Common runner fields and webhook-owned lifecycle, capacity, and boot time must resolve from their experimental global defaults before applying per-configuration overrides." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.vpc_id == "vpc-experimental" + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.subnet_ids == tolist(["subnet-lane"]) + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.binaries_syncer.enabled + && toset(keys(local.translated_experimental_base.multi_runner_config["resolved"].compute_provider.ec2.binaries_syncer)) == toset(["enabled"]) + && toset(keys(local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.binaries_syncer)) == toset(["enabled", "s3"]) + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.binaries_syncer.s3 != null + && keys(output.binaries_syncer_map) == ["linux_x64"] + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.environment[0].variables["INSTANCE_TYPES"] == "m5.large" + ) + error_message = "Global compute-provider defaults must merge into the required runner-configuration selector while configuration values take precedence." + } + + assert { + condition = ( + !local.translated_experimental.compute_provider.ec2.runner_binaries.enabled + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.versioning == "Enabled" + && local.translated_experimental.compute_provider.ec2.runner_binaries.s3.logging.bucket == "runner-binaries-access-logs" + && local.translated_experimental.lambda.artifact.s3.bucket == "experimental-lambda-artifacts" + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.artifact.zip == null + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3.key == "nested-runner-binaries-syncer.zip" + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3.object_version == "nested-version" + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.schedule.expression == "rate(2 hours)" + && local.translated_experimental.compute_provider.ec2.runner_binaries.syncer.schedule.state == "DISABLED" + && keys(output.binaries_syncer_map) == ["linux_x64"] + && output.binaries_syncer_map["linux_x64"].lambda.s3_bucket == "experimental-lambda-artifacts" + && output.binaries_syncer_map["linux_x64"].lambda.s3_key == "nested-runner-binaries-syncer.zip" + && output.binaries_syncer_map["linux_x64"].lambda.s3_object_version == "nested-version" + && output.binaries_syncer_map["linux_x64"].lambda.memory_size == 384 + && output.binaries_syncer_map["linux_x64"].lambda.timeout == 240 + && output.binaries_syncer_map["linux_x64"].bucket.tags["BinaryBucket"] == "global" + ) + error_message = "A runner configuration must be able to enable the globally configured runner-binary distribution and syncer while the shared settings remain global." + } + + assert { + condition = ( + length(local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules) == 1 + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].cidr_blocks == tolist(["0.0.0.0/0"]) + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].ipv6_cidr_blocks == tolist(["::/0"]) + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].prefix_list_ids == null + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].from_port == 0 + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].protocol == "-1" + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].security_groups == null + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].self == null + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].to_port == 0 + && local.translated_experimental.multi_runner_config["resolved"].compute_provider.ec2.egress_rules[0].description == null + ) + error_message = "Omitted experimental EC2 egress rules must resolve to the concrete nested allow-all IPv4 and IPv6 default independently of the stable input." + } + + assert { + condition = ( + module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.runtime == "nodejs22.x" + && local.translated_experimental.orchestration.webhook.lambda.artifact.zip == null + && local.translated_experimental.orchestration.webhook.lambda.artifact.s3.key == "nested-runners.zip" + && local.translated_experimental.orchestration.webhook.lambda.artifact.s3.object_version == "nested-runners-version" + && local.translated_experimental.lambda.artifact.s3.bucket == "experimental-lambda-artifacts" + && local.translated_experimental.multi_runner_config["resolved"].lambda.artifact.s3.bucket == "experimental-lambda-artifacts" + && !contains(keys(local.translated_experimental.multi_runner_config["resolved"].lambda), "zip") + && !contains(keys(local.translated_experimental.multi_runner_config["resolved"].lambda), "s3") + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.lambda.artifact.zip == null + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.lambda.artifact.s3.key == "nested-runners.zip" + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.lambda.artifact.s3.object_version == "nested-runners-version" + && local.translated_experimental.lambda.principals == tolist([{ + type = "Service" + identifiers = tolist(["states.amazonaws.com"]) + }]) + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.s3_bucket == "experimental-lambda-artifacts" + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.s3_key == "nested-runners.zip" + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.s3_object_version == "nested-runners-version" + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.memory_size == 896 + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.timeout == 40 + && module.runner_configs["resolved"].orchestration.webhook.scale_down.lambda.timeout == 75 + && module.runner_configs["resolved"].orchestration.webhook.pool.lambda.memory_size == 448 + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size == 50 + && module.runner_configs["resolved"].runner.role.path == "/experimental/" + && module.runner_configs["resolved"].orchestration.webhook.scale_up.role.path == "/lane-lambda/" + ) + error_message = "V2 values must resolve in configuration-over-experimental-global precedence order without stable-input fallback." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.queue.delay_webhook_event == 11 + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.queue.job_queue_retention_in_seconds == 172800 + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.queue.visibility_timeout_seconds == 300 + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.queue.redrive_build_queue.enabled + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.queue.redrive_build_queue.maxReceiveCount == 7 + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.queue.tags == tomap({ + GlobalQueue = "global" + LaneQueue = "lane" + Precedence = "lane" + }) + && local.translated_experimental.orchestration.webhook.queue.encryption == var.experimental.orchestration.webhook.queue.encryption + && local.translated_experimental.ssm.kms_key_id == local.translated_experimental.orchestration.webhook.queue.encryption.kms_master_key_id + && aws_sqs_queue.queued_builds["resolved"].delay_seconds == 11 + && aws_sqs_queue.queued_builds["resolved"].message_retention_seconds == 172800 + && aws_sqs_queue.queued_builds["resolved"].visibility_timeout_seconds == 300 + && aws_sqs_queue.queued_builds["resolved"].kms_master_key_id == "arn:aws:kms:eu-west-1:123456789012:key/experimental-queue" + && aws_sqs_queue.queued_builds["resolved"].kms_data_key_reuse_period_seconds == 900 + && aws_sqs_queue.queued_builds["resolved"].tags == tomap({ + GlobalQueue = "global" + LaneQueue = "lane" + Precedence = "lane" + }) + && aws_sqs_queue.queued_builds_dlq["resolved"].kms_master_key_id == "arn:aws:kms:eu-west-1:123456789012:key/experimental-queue" + && aws_sqs_queue.queued_builds_dlq["resolved"].tags == tomap({ + GlobalQueue = "global" + LaneQueue = "lane" + Precedence = "lane" + }) + ) + error_message = "V2 queue leaves must resolve configuration over experimental-global values, merge queue tags, and apply global nested encryption to the build queue and DLQ." + } + + assert { + condition = ( + local.translated_experimental.github.app == var.experimental.github.app + && local.translated_experimental.github.additional_apps == var.experimental.github.additional_apps + && local.translated_experimental.orchestration.webhook.github.repository_white_list == var.experimental.orchestration.webhook.github.repository_white_list + && !contains(keys(local.translated_experimental), "enterprise_server") + && !contains(keys(local.translated_experimental), "user_agent") + && local.translated_experimental.github.enterprise_server == var.experimental.github.enterprise_server + && local.translated_experimental.github.user_agent == var.experimental.github.user_agent + && local.translated_experimental.github.enterprise_server.url == "https://experimental-shared.example.com" + && !local.translated_experimental.github.enterprise_server.ssl_verify + && local.translated_experimental.github.user_agent == "experimental-runner-user-agent" + && length(local.translated_experimental.github.additional_apps) == 0 + && local.translated_experimental.multi_runner_config["resolved"].orchestration.webhook.job_retry.enabled + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.environment[0].variables["GHES_URL"] == "https://experimental-shared.example.com" + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.environment[0].variables["NODE_TLS_REJECT_UNAUTHORIZED"] == "0" + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.environment[0].variables["USER_AGENT"] == "experimental-runner-user-agent" + && module.runner_configs["resolved"].orchestration.webhook.scale_down.lambda.environment[0].variables["GHES_URL"] == "https://experimental-shared.example.com" + && module.runner_configs["resolved"].orchestration.webhook.pool.lambda.environment[0].variables["USER_AGENT"] == "experimental-runner-user-agent" + && module.runner_configs["resolved"].orchestration.webhook.scale_up.lambda.environment[0].variables["PARAMETER_GITHUB_APP_ID_NAME"] == module.ssm.parameters.github_app_id.name + && local.translated_experimental.compute_provider.ec2.instance_termination_watcher.environment_variables["NESTED_WATCHER"] == "true" + && output.instance_termination_watcher.lambda.function.runtime == "nodejs22.x" + && output.instance_termination_watcher.lambda.function.architectures == tolist(["arm64"]) + && output.instance_termination_watcher.lambda.function.memory_size == 432 + && output.instance_termination_watcher.lambda.function.timeout == 41 + && output.instance_termination_watcher.lambda.function.s3_bucket == "experimental-lambda-artifacts" + && output.instance_termination_watcher.lambda.function.s3_key == "nested-termination-watcher.zip" + && output.instance_termination_watcher.lambda.function.s3_object_version == "nested-watcher-version" + && length(output.instance_termination_watcher.lambda.function.vpc_config) == 1 + && length(output.instance_termination_watcher.lambda.function.vpc_config[0].subnet_ids) == 0 + && length(output.instance_termination_watcher.lambda.function.vpc_config[0].security_group_ids) == 0 + && output.instance_termination_watcher.lambda_role.path == "/experimental/" + && output.instance_termination_watcher.lambda.function.environment[0].variables["GHES_URL"] == "https://experimental-shared.example.com" + && output.instance_termination_watcher.lambda.function.environment[0].variables["LOG_LEVEL"] == "info" + && output.instance_termination_watcher.lambda_log_group.retention_in_days == 180 + && output.instance_termination_watcher.lambda_log_group.log_group_class == "STANDARD" + && output.instance_termination_handler == null + ) + error_message = "V2 runner configurations and the termination watcher must use nested GitHub, Lambda, role, observability, feature, artifact, sizing, and environment settings without flat component fallback." + } + + assert { + condition = ( + local.translated_experimental.compute_provider.ec2.ami.housekeeper.enabled + && length(module.ami_housekeeper) == 1 + && module.ami_housekeeper[0].lambda.runtime == "nodejs22.x" + && module.ami_housekeeper[0].lambda.architectures == tolist(["arm64"]) + && module.ami_housekeeper[0].lambda.memory_size == 448 + && module.ami_housekeeper[0].lambda.timeout == 120 + && module.ami_housekeeper[0].lambda.s3_bucket == "experimental-lambda-artifacts" + && module.ami_housekeeper[0].lambda.s3_key == "nested-ami-housekeeper.zip" + && module.ami_housekeeper[0].lambda.s3_object_version == "nested-ami-housekeeper-version" + && jsondecode(module.ami_housekeeper[0].lambda.environment[0].variables["AMI_CLEANUP_OPTIONS"]).maxItems == 5 + && jsondecode(module.ami_housekeeper[0].lambda.environment[0].variables["AMI_CLEANUP_OPTIONS"]).minimumDaysOld == 10 + && jsondecode(module.ami_housekeeper[0].lambda.environment[0].variables["AMI_CLEANUP_OPTIONS"]).dryRun + && module.ami_housekeeper[0].lambda_role.path == "/experimental/" + ) + error_message = "The v2 AMI housekeeper must be owned by the nested EC2 global and inherit nested Lambda and role globals while ignoring all matching flat component inputs." + } + + assert { + condition = ( + local.translated_experimental.lambda.runtime == "nodejs22.x" + && var.experimental.orchestration.webhook.lambda.webhook.memory_size == 384 + && output.webhook.lambda.runtime == "nodejs22.x" + && output.webhook.lambda.architectures == tolist(["arm64"]) + && output.webhook.lambda.memory_size == 384 + && output.webhook.lambda.timeout == 10 + && output.webhook.lambda.s3_bucket == "experimental-lambda-artifacts" + && output.webhook.lambda.s3_key == "nested-webhook.zip" + && output.webhook.lambda.s3_object_version == "nested-webhook-version" + && output.webhook.lambda_role.path == "/experimental/" + && toset(jsondecode(output.webhook.lambda.environment[0].variables["REPOSITORY_ALLOW_LIST"])) == toset(["nested-owner/nested-repository"]) + && output.webhook.lambda.environment[0].variables["QUEUE_SELECTION_STRATEGY"] == "all" + && output.webhook.eventbridge == null + && output.webhook.dispatcher == null + && local.translated_experimental.orchestration.webhook.matcher_config_parameter_store_tier == "Advanced" + && local.translated_experimental.orchestration.webhook.lambda.webhook.api_gateway_access_log_settings.destination_arn == "arn:aws:logs:eu-west-1:123456789012:log-group:nested-api-access" + && local.translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size == 25 + && local.translated_experimental.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds == 0 + && !contains(keys(output.webhook.lambda.environment[0].variables), "GHES_URL") + ) + error_message = "The shared webhook must consume its provider-owned repository allow-list plus nested GitHub connection, routing, eventbridge, matcher-tier, artifact, API-access-log, Lambda, and role globals without flat-input leakage." + } +} + +run "experimental_v2_layers_observability_and_ssm" { + command = plan + + variables { + tags = { + ModuleOnly = "module" + Precedence = "module" + } + + log_level = "error" + logging_retention_in_days = 90 + logging_kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/flat-logs" + log_class = "STANDARD" + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/global-ssm" + ghes_url = "https://flat-observability.example.com" + ghes_ssl_verify = true + user_agent = "flat-observability-user-agent" + + tracing_config = { + mode = null + capture_http_requests = false + capture_error = false + } + + metrics = { + enable = false + namespace = "FlatMetrics" + metric = { + enable_github_app_rate_limit = false + enable_job_retry = false + enable_spot_termination_warning = false + } + } + + ssm_paths = { + root = "flat-root" + app = "shared-app" + runners = "flat-runners" + webhook = "shared-webhook" + } + + parameter_store_tags = { + FlatParameterOnly = "flat-parameter" + Precedence = "flat-parameter" + } + + runners_ssm_housekeeper = { + schedule_expression = "rate(1 day)" + enabled = true + lambda_memory_size = 512 + lambda_timeout = 60 + config = { + tokenPath = "/flat/cleanup/tokens" + minimumDaysOld = 1 + dryRun = false + } + } + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + enterprise_server = { + url = "https://experimental-observability.example.com" + ssl_verify = false + } + user_agent = "experimental-observability-user-agent" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + + tags = { + ExperimentalOnly = "experimental" + Precedence = "experimental" + } + + runner = { + os = "linux" + architecture = "x64" + } + + ssm = { + paths = { + root = "/global-ssm" + app = "global-app" + webhook = "global-webhook" + tokens = "global-tokens" + config = "global-config" + } + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/global-ssm" + tags = { + GlobalSsmOnly = "global-ssm" + Precedence = "global-ssm" + } + parameters = { + tags = { + GlobalParameterOnly = "global-parameter" + Precedence = "global-parameter" + } + } + housekeeper = { + schedule_expression = "rate(6 hours)" + state = "DISABLED" + tags = { + GlobalHousekeeperOnly = "global-housekeeper" + Precedence = "global-housekeeper" + } + lambda = { + artifact = { + zip = "README.md" + } + memory_size = 640 + timeout = 70 + } + config = { + tokenPath = "/global/cleanup/tokens" + minimumDaysOld = 6 + dryRun = true + } + } + } + + observability = { + logs = { + level = "debug" + retention_in_days = 30 + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/global-logs" + class = "INFREQUENT_ACCESS" + tags = { + GlobalLogOnly = "global-log" + Precedence = "global-log" + } + } + tracing = { + mode = "Active" + capture_http_requests = true + capture_error = false + } + metrics = { + enable = true + namespace = "GlobalMetrics" + metric = { + enable_github_app_rate_limit = true + enable_job_retry = false + enable_spot_termination_warning = false + } + } + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-global-observability" + subnet_ids = ["subnet-global-observability"] + } + } + + multi_runner_config = { + inherited = { + tags = { + InheritedOnly = "inherited" + Precedence = "inherited" + } + + orchestration = { + webhook = { + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "inherited"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + + overridden = { + tags = { + OverriddenOnly = "overridden" + Precedence = "overridden" + } + + orchestration = { + webhook = { + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "overridden"]] + } + } + } + + ssm = { + paths = { + root = "/lane-ssm" + tokens = "lane-tokens" + config = "lane-config" + } + tags = { + LaneSsmOnly = "lane-ssm" + Precedence = "lane-ssm" + } + parameters = { + tags = { + LaneParameterOnly = "lane-parameter" + Precedence = "lane-parameter" + } + } + housekeeper = { + schedule_expression = "rate(2 hours)" + state = "ENABLED" + tags = { + LaneHousekeeperOnly = "lane-housekeeper" + Precedence = "lane-housekeeper" + } + lambda = { + memory_size = 768 + timeout = 45 + } + config = { + tokenPath = "/lane/cleanup/tokens" + minimumDaysOld = 2 + dryRun = false + } + } + } + + observability = { + logs = { + level = "warn" + retention_in_days = 7 + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/lane-logs" + class = "STANDARD" + tags = { + LaneLogOnly = "lane-log" + Precedence = "lane-log" + } + } + tracing = { + mode = "PassThrough" + capture_http_requests = false + capture_error = true + } + metrics = { + enable = false + namespace = "LaneMetrics" + metric = { + enable_github_app_rate_limit = false + enable_job_retry = true + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["c5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + toset(keys(local.translated_experimental_base.multi_runner_config["inherited"].compute_provider.ec2.binaries_syncer)) == toset(["enabled"]) + && toset(keys(local.translated_experimental.multi_runner_config["inherited"].compute_provider.ec2.binaries_syncer)) == toset(["enabled", "s3"]) + && !local.translated_experimental.multi_runner_config["inherited"].compute_provider.ec2.binaries_syncer.enabled + && local.translated_experimental.multi_runner_config["inherited"].compute_provider.ec2.binaries_syncer.s3 == null + && !contains(keys(output.binaries_syncer_map), "linux_x64") + ) + error_message = "A disabled binary syncer must gain a known null S3 value only in the final canonical runner configuration and create no shared syncer resources." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["inherited"].observability.logs.level == "debug" + && local.translated_experimental.multi_runner_config["inherited"].observability.logs.retention_in_days == 30 + && local.translated_experimental.multi_runner_config["inherited"].observability.logs.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/global-logs" + && local.translated_experimental.multi_runner_config["inherited"].observability.logs.class == "INFREQUENT_ACCESS" + && local.translated_experimental.multi_runner_config["inherited"].observability.tracing.mode == "Active" + && local.translated_experimental.multi_runner_config["inherited"].observability.tracing.capture_http_requests + && !local.translated_experimental.multi_runner_config["inherited"].observability.tracing.capture_error + && local.translated_experimental.multi_runner_config["inherited"].observability.metrics.enable + && local.translated_experimental.multi_runner_config["inherited"].observability.metrics.namespace == "GlobalMetrics" + && local.translated_experimental.multi_runner_config["inherited"].observability.metrics.metric.enable_github_app_rate_limit + && !local.translated_experimental.multi_runner_config["inherited"].observability.metrics.metric.enable_job_retry + && local.translated_experimental.observability.metrics.metric.enable_spot_termination + && !local.translated_experimental.observability.metrics.metric.enable_spot_termination_warning + ) + error_message = "A runner configuration omitting observability must inherit every runner-config logging, tracing, and metrics leaf while watcher-only metric switches remain global." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["overridden"].observability.logs.level == "warn" + && local.translated_experimental.multi_runner_config["overridden"].observability.logs.retention_in_days == 7 + && local.translated_experimental.multi_runner_config["overridden"].observability.logs.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/lane-logs" + && local.translated_experimental.multi_runner_config["overridden"].observability.logs.class == "STANDARD" + && local.translated_experimental.multi_runner_config["overridden"].observability.tracing.mode == "PassThrough" + && !local.translated_experimental.multi_runner_config["overridden"].observability.tracing.capture_http_requests + && local.translated_experimental.multi_runner_config["overridden"].observability.tracing.capture_error + && !local.translated_experimental.multi_runner_config["overridden"].observability.metrics.enable + && local.translated_experimental.multi_runner_config["overridden"].observability.metrics.namespace == "LaneMetrics" + && !local.translated_experimental.multi_runner_config["overridden"].observability.metrics.metric.enable_github_app_rate_limit + && local.translated_experimental.multi_runner_config["overridden"].observability.metrics.metric.enable_job_retry + ) + error_message = "Runner-configuration observability values must override every configuration-owned logging, tracing, and metrics leaf." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["inherited"].ssm.paths.root == "/global-ssm/inherited" + && local.translated_experimental.multi_runner_config["inherited"].ssm.paths.tokens == "global-tokens" + && local.translated_experimental.multi_runner_config["inherited"].ssm.paths.config == "global-config" + && local.translated_experimental.ssm.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/global-ssm" + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.schedule_expression == "rate(6 hours)" + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.state == "DISABLED" + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.lambda.memory_size == 640 + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.lambda.timeout == 70 + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.lambda.artifact.zip == "README.md" + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.lambda.artifact.s3 == null + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.config.tokenPath == "/global/cleanup/tokens" + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.config.minimumDaysOld == 6 + && local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.config.dryRun + ) + error_message = "A runner configuration omitting SSM values must inherit global paths, KMS ownership, and housekeeper settings." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["overridden"].ssm.paths.root == "/lane-ssm/overridden" + && local.translated_experimental.multi_runner_config["overridden"].ssm.paths.tokens == "lane-tokens" + && local.translated_experimental.multi_runner_config["overridden"].ssm.paths.config == "lane-config" + && local.translated_experimental.ssm.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/global-ssm" + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.schedule_expression == "rate(2 hours)" + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.state == "ENABLED" + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.lambda.memory_size == 768 + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.lambda.timeout == 45 + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.lambda.artifact.zip == "README.md" + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.lambda.artifact.s3 == null + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.config.tokenPath == "/lane/cleanup/tokens" + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.config.minimumDaysOld == 2 + && !local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.config.dryRun + ) + error_message = "Runner-configuration SSM paths and housekeeper leaves must override globals while the global KMS key ID remains shared by every runner configuration." + } + + assert { + condition = ( + module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["LOG_LEVEL"] == "DEBUG" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["GHES_URL"] == "https://experimental-observability.example.com" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["NODE_TLS_REJECT_UNAUTHORIZED"] == "0" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["USER_AGENT"] == "experimental-observability-user-agent" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_METRICS_NAMESPACE"] == "GlobalMetrics" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["ENABLE_METRIC_GITHUB_APP_RATE_LIMIT"] == "true" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "true" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "false" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.tracing_config[0].mode == "Active" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.log_group.retention_in_days == 30 + && module.runner_configs["inherited"].orchestration.webhook.scale_up.log_group.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/global-logs" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.log_group.log_group_class == "INFREQUENT_ACCESS" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["LOG_LEVEL"] == "WARN" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_METRICS_NAMESPACE"] == "LaneMetrics" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["ENABLE_METRIC_GITHUB_APP_RATE_LIMIT"] == "false" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "false" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "true" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.tracing_config[0].mode == "PassThrough" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.log_group.retention_in_days == 7 + && module.runner_configs["overridden"].orchestration.webhook.scale_up.log_group.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/lane-logs" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.log_group.log_group_class == "STANDARD" + ) + error_message = "Resolved global GitHub connection settings and global/per-configuration observability must reach runner-config Lambda and log-group resources." + } + + assert { + condition = ( + module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_TOKEN_PATH"] == "/global-ssm/inherited/global-tokens" + && module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_CONFIG_PATH"] == "/global-ssm/inherited/global-config" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_TOKEN_PATH"] == "/lane-ssm/overridden/lane-tokens" + && module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_CONFIG_PATH"] == "/lane-ssm/overridden/lane-config" + && tomap({ + for tag in jsondecode(module.runner_configs["inherited"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_PARAMETER_STORE_TAGS"]) : + tag.Key => tag.Value + }) == tomap({ + ExperimentalOnly = "experimental" + InheritedOnly = "inherited" + GlobalSsmOnly = "global-ssm" + GlobalParameterOnly = "global-parameter" + Precedence = "global-parameter" + "ghr:environment" = "github-actions" + }) + && tomap({ + for tag in jsondecode(module.runner_configs["overridden"].orchestration.webhook.scale_up.lambda.environment[0].variables["SSM_PARAMETER_STORE_TAGS"]) : + tag.Key => tag.Value + }) == tomap({ + ExperimentalOnly = "experimental" + OverriddenOnly = "overridden" + GlobalSsmOnly = "global-ssm" + LaneSsmOnly = "lane-ssm" + GlobalParameterOnly = "global-parameter" + LaneParameterOnly = "lane-parameter" + Precedence = "lane-parameter" + "ghr:environment" = "github-actions" + }) + ) + error_message = "Resolved runner-configuration roots and layered SSM parameter tags must reach runner-config runtime configuration." + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["inherited"].ssm.housekeeper.tags == tomap({ + GlobalHousekeeperOnly = "global-housekeeper" + Precedence = "global-housekeeper" + }) + && local.translated_experimental.multi_runner_config["overridden"].ssm.housekeeper.tags == tomap({ + GlobalHousekeeperOnly = "global-housekeeper" + LaneHousekeeperOnly = "lane-housekeeper" + Precedence = "lane-housekeeper" + }) + && module.runner_configs["inherited"].orchestration.webhook.scale_up.log_group.tags == tomap({ + ExperimentalOnly = "experimental" + InheritedOnly = "inherited" + GlobalLogOnly = "global-log" + Precedence = "global-log" + "ghr:environment" = "github-actions" + }) + && module.runner_configs["overridden"].orchestration.webhook.scale_up.log_group.tags == tomap({ + ExperimentalOnly = "experimental" + OverriddenOnly = "overridden" + GlobalLogOnly = "global-log" + LaneLogOnly = "lane-log" + Precedence = "lane-log" + "ghr:environment" = "github-actions" + }) + ) + error_message = "Global and per-configuration observability and SSM housekeeper tags must merge with narrower scopes taking precedence." + } + + assert { + condition = ( + var.ssm_paths.root == "flat-root" + && local.translated_experimental.ssm.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/global-ssm" + && var.kms_key_arn == local.translated_experimental.ssm.kms_key_id + && output.webhook.lambda.runtime == "nodejs24.x" + && output.webhook.lambda.architectures == tolist(["arm64"]) + && output.webhook.lambda.environment[0].variables["PARAMETER_RUNNER_MATCHER_CONFIG_PATH"] == "/global-ssm/global-webhook/runner-matcher-config" + && output.webhook.lambda.environment[0].variables["LOG_LEVEL"] == "DEBUG" + && output.webhook.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "true" + && output.webhook.lambda.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "false" + && output.webhook.lambda.tracing_config[0].mode == "Active" + && output.webhook.lambda_log_group.retention_in_days == 30 + && output.webhook.lambda_log_group.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/global-logs" + && output.webhook.lambda_log_group.log_group_class == "INFREQUENT_ACCESS" + && output.webhook.lambda.tags["ExperimentalOnly"] == "experimental" + && !contains(keys(output.webhook.lambda.tags), "ModuleOnly") + ) + error_message = "The shared webhook must use translated global SSM/KMS, observability, Lambda, and tag inputs rather than flat compatibility values." + } + + assert { + condition = output.ssm_parameters.id.name == "/global-ssm/global-app/github_app_id" + error_message = "Shared SSM parameters must use translated global root and app paths in v2 mode." + } +} + +run "experimental_v2_requires_global_github_app" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + override_module { + target = module.ssm + outputs = { + parameters = { + github_app_id = { name = "/mock/app-id", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/app-id" } + github_app_key_base64 = { name = "/mock/key", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/key" } + github_app_webhook_secret = { name = "/mock/webhook-secret", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/webhook-secret" } + } + additional_app_parameters = [] + } + } + + variables { + experimental = { + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-github-app" + subnet_ids = ["subnet-missing-github-app"] + } + } + multi_runner_config = { + missing_github_app = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "missing-github-app"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_incomplete_global_github_app" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + override_module { + target = module.ssm + outputs = { + parameters = { + github_app_id = { name = "/mock/app-id", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/app-id" } + github_app_key_base64 = { name = "/mock/key", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/key" } + github_app_webhook_secret = { name = "/mock/webhook-secret", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/webhook-secret" } + } + additional_app_parameters = [] + } + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-incomplete-github-app" + subnet_ids = ["subnet-incomplete-github-app"] + } + } + multi_runner_config = { + incomplete_github_app = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "incomplete-github-app"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_incomplete_additional_github_app" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + override_module { + target = module.ssm + outputs = { + parameters = { + github_app_id = { name = "/mock/app-id", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/app-id" } + github_app_key_base64 = { name = "/mock/key", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/key" } + github_app_webhook_secret = { name = "/mock/webhook-secret", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/mock/webhook-secret" } + } + additional_app_parameters = [] + } + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + additional_apps = [{ + id = "incomplete-additional-app" + }] + } + compute_provider = { + ec2 = { + vpc_id = "vpc-incomplete-additional-app" + subnet_ids = ["subnet-incomplete-additional-app"] + } + } + multi_runner_config = { + incomplete_additional_app = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "incomplete-additional-app"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_prefers_nested_primary_github_app_over_flat" { + command = plan + + variables { + experimental = { + github = { + app = { + id = "different-app-id" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-mismatched-primary-app" + subnet_ids = ["subnet-mismatched-primary-app"] + } + } + multi_runner_config = { + mismatched_primary_app = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "mismatched-primary-app"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + var.github_app.id == "123456" + && local.translated_experimental.github.app.id == "different-app-id" + && length(local.github_app_parameters.id) == 1 + && output.ssm_parameters.id.name == "/github-action-runners/github-actions/app/github_app_id" + ) + error_message = "V2 must use the nested primary GitHub App and generated parameter references even when the stable flat app differs." + } +} + +run "experimental_v2_prefers_nested_additional_github_apps_over_flat" { + command = plan + + variables { + additional_github_apps = [{ + id_ssm = { + name = "/github-runner/flat-additional-app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/flat-additional-app-id" + } + key_base64_ssm = { + name = "/github-runner/flat-additional-key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/flat-additional-key-base64" + } + }] + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-mismatched-additional-apps" + subnet_ids = ["subnet-mismatched-additional-apps"] + } + } + multi_runner_config = { + mismatched_additional_apps = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "mismatched-additional-apps"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + length(var.additional_github_apps) == 1 + && length(local.translated_experimental.github.additional_apps) == 0 + && length(local.github_app_parameters.id) == 1 + && !contains(keys(output.ssm_parameters), "github_app_id_1") + ) + error_message = "V2 must ignore stable flat additional GitHub Apps when the nested additional-app list is empty." + } +} + +run "experimental_v2_allows_mismatched_watcher_ghes_when_deregistration_disabled" { + command = plan + + variables { + ghes_url = "https://flat-disabled-deregistration.example.com" + instance_termination_watcher = { + enable = false + enable_runner_deregistration = true + } + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + enterprise_server = { + url = "https://experimental-disabled-deregistration.example.com" + } + } + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-disabled-deregistration" + subnet_ids = ["subnet-disabled-deregistration"] + instance_termination_watcher = { + enabled = true + enable_runner_deregistration = false + artifact = { + zip = "README.md" + } + } + } + } + multi_runner_config = { + disabled_deregistration = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "disabled-deregistration"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + !var.instance_termination_watcher.enable + && local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enabled + && !local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enable_runner_deregistration + && output.instance_termination_watcher != null + && module.runner_configs["disabled_deregistration"].orchestration.webhook.scale_up.lambda.environment[0].variables["GHES_URL"] == "https://experimental-disabled-deregistration.example.com" + ) + error_message = "The termination watcher must remain enabled while the v2 runner configuration uses the translated enterprise-server URL when deregistration is disabled." + } +} + +run "experimental_v2_termination_watcher_ignores_mismatched_flat_ghes_url" { + command = plan + + variables { + ghes_url = "https://flat-watcher.example.com" + instance_termination_watcher = { + enable = false + enable_runner_deregistration = false + } + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + enterprise_server = { + url = "https://experimental-watcher.example.com" + } + } + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-mismatched-watcher-ghes" + subnet_ids = ["subnet-mismatched-watcher-ghes"] + instance_termination_watcher = { + enabled = true + enable_runner_deregistration = true + artifact = { + zip = "README.md" + } + } + } + } + multi_runner_config = { + mismatched_watcher_ghes = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "mismatched-watcher-ghes"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + !var.instance_termination_watcher.enable + && local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enabled + && local.translated_experimental.compute_provider.ec2.instance_termination_watcher.enable_runner_deregistration + && output.instance_termination_watcher.lambda.function.environment[0].variables["GHES_URL"] == "https://experimental-watcher.example.com" + && module.runner_configs["mismatched_watcher_ghes"].orchestration.webhook.scale_up.lambda.environment[0].variables["GHES_URL"] == "https://experimental-watcher.example.com" + && var.ghes_url == "https://flat-watcher.example.com" + ) + error_message = "An enabled v2 termination watcher must use the translated enterprise-server URL instead of a deliberately different flat GHES URL." + } +} + +run "experimental_v2_ignores_flat_only_shared_ssm_kms_key" { + command = plan + + variables { + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/flat-only" + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + runner = { + os = "linux" + architecture = "x64" + } + compute_provider = { + ec2 = { + vpc_id = "vpc-flat-only-kms" + subnet_ids = ["subnet-flat-only-kms"] + } + } + multi_runner_config = { + flat_only = { + orchestration = { + webhook = { + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "flat-only-kms"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + var.kms_key_arn == "arn:aws:kms:eu-west-1:123456789012:key/flat-only" + && local.translated_experimental.ssm.kms_key_id == null + && output.ssm_parameters.id.name == "/github-action-runners/github-actions/app/github_app_id" + ) + error_message = "V2 shared SSM resources must ignore a flat-only KMS key when the nested KMS key ID is absent." + } +} + +run "experimental_v2_uses_experimental_only_shared_ssm_kms_key" { + command = plan + + variables { + kms_key_arn = null + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + runner = { + os = "linux" + architecture = "x64" + } + ssm = { + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/experimental-only" + } + compute_provider = { + ec2 = { + vpc_id = "vpc-experimental-only-kms" + subnet_ids = ["subnet-experimental-only-kms"] + } + } + multi_runner_config = { + experimental_only = { + orchestration = { + webhook = { + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "experimental-only-kms"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + var.kms_key_arn == null + && local.translated_experimental.ssm.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/experimental-only" + && output.ssm_parameters.id.name == "/github-action-runners/github-actions/app/github_app_id" + ) + error_message = "V2 shared SSM resources must accept a nested KMS key ID without a flat KMS key." + } +} + +run "experimental_v2_prefers_nested_shared_ssm_kms_key_over_flat" { + command = plan + + variables { + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/flat-mismatch" + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + runner = { + os = "linux" + architecture = "x64" + } + ssm = { + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/experimental-mismatch" + } + compute_provider = { + ec2 = { + vpc_id = "vpc-mismatched-kms" + subnet_ids = ["subnet-mismatched-kms"] + } + } + multi_runner_config = { + mismatched = { + orchestration = { + webhook = { + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "mismatched-kms"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + var.kms_key_arn == "arn:aws:kms:eu-west-1:123456789012:key/flat-mismatch" + && local.translated_experimental.ssm.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/experimental-mismatch" + ) + error_message = "V2 shared SSM resources must prefer the nested KMS key ID over a deliberately different flat KMS key." + } +} + +run "experimental_v2_external_role_ignores_global_iam_management" { + command = plan + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + runner = { + iam = { + managed_policy_arns = { + readonly = "arn:aws:iam::aws:policy/ReadOnlyAccess" + } + additional_trust_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [] + }) + } + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-external-role" + subnet_ids = ["subnet-external-role"] + } + } + + multi_runner_config = { + external = { + runner = { + os = "linux" + architecture = "x64" + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/external-runner" + } + } + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "external"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + local.translated_experimental.multi_runner_config["external"].runner.iam.role.arn == "arn:aws:iam::123456789012:role/external-runner" + && length(local.translated_experimental.multi_runner_config["external"].runner.iam.managed_policy_arns) == 0 + && local.translated_experimental.multi_runner_config["external"].runner.iam.additional_trust_policy_json == null + ) + error_message = "A runner configuration selecting an external runner role must not inherit global managed policies or trust-policy additions." + } +} + +run "experimental_v2_rejects_explicit_iam_management_with_external_role" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + override_module { + target = module.runner_configs["invalid"] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + runner = { + iam = { + managed_policy_arns = { + readonly = "arn:aws:iam::aws:policy/ReadOnlyAccess" + } + } + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-invalid-external-role" + subnet_ids = ["subnet-invalid-external-role"] + } + } + + multi_runner_config = { + invalid = { + runner = { + os = "linux" + architecture = "x64" + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/external-runner" + } + managed_policy_arns = { + explicit = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" + } + additional_trust_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [] + }) + } + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "invalid"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_layers_shared_and_component_tags" { + command = plan + + variables { + tags = { + GlobalOnly = "global" + Precedence = "global" + } + + lambda_tags = { + SharedLambdaOnly = "shared-lambda" + Precedence = "shared-lambda" + } + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + + tags = { + ExperimentalOnly = "experimental" + Precedence = "experimental" + } + + lambda = { + tags = { + ExperimentalLambdaOnly = "experimental-lambda" + Precedence = "experimental-lambda" + } + } + + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + } + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-tagged" + subnet_ids = ["subnet-tagged"] + } + } + + multi_runner_config = { + tagged = { + tags = { + RunnerConfigOnly = "runner-config" + Precedence = "runner-config" + } + + runner = { + os = "linux" + architecture = "x64" + tags = { + RunnerOnly = "runner" + Precedence = "runner" + } + } + + lambda = { + tags = { + ConfigLambdaOnly = "config-lambda" + Precedence = "config-lambda" + } + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + lambda = { + scale = { + up = { + tags = { + ScaleUpOnly = "scale-up" + Precedence = "scale-up" + } + } + + down = { + tags = { + ScaleDownOnly = "scale-down" + Precedence = "scale-down" + } + } + } + } + + queue = { + redrive_build_queue = { + enabled = true + maxReceiveCount = 3 + } + tags = { + SharedQueueOnly = "shared-queue" + Precedence = "shared-queue" + } + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64", "tagged"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + observability = { + logs = { + tags = { + SharedLogOnly = "shared-log" + Precedence = "shared-log" + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = aws_sqs_queue.queued_builds["tagged"].tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + SharedQueueOnly = "shared-queue" + Precedence = "shared-queue" + }) + error_message = "Experimental v2 build queue tags must merge global, runner-configuration, and queue tags in that precedence order." + } + + assert { + condition = aws_sqs_queue.queued_builds_dlq["tagged"].tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + SharedQueueOnly = "shared-queue" + Precedence = "shared-queue" + }) + error_message = "Experimental v2 dead-letter queue tags must use the same layered precedence as the build queue." + } + + assert { + condition = module.runner_configs["tagged"].orchestration.webhook.scale_up.lambda.tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + ExperimentalLambdaOnly = "experimental-lambda" + ConfigLambdaOnly = "config-lambda" + ScaleUpOnly = "scale-up" + Precedence = "scale-up" + "ghr:environment" = "github-actions" + }) + error_message = "Scale-up Lambda tags must merge global, runner-configuration, shared Lambda, configuration Lambda, and component tags in that precedence order." + } + + assert { + condition = module.runner_configs["tagged"].orchestration.webhook.scale_up.log_group.tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + SharedLogOnly = "shared-log" + ScaleUpOnly = "scale-up" + Precedence = "scale-up" + "ghr:environment" = "github-actions" + }) + error_message = "Scale-up log-group tags must merge global, runner-configuration, shared log, and component tags in that precedence order." + } + + assert { + condition = module.runner_configs["tagged"].orchestration.webhook.scale_up.role.tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + ScaleUpOnly = "scale-up" + Precedence = "scale-up" + "ghr:environment" = "github-actions" + }) + error_message = "Scale-up role tags must merge global, runner-configuration, and component tags without Lambda- or log-only tags." + } + + assert { + condition = module.runner_configs["tagged"].runner.role.tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + RunnerOnly = "runner" + Precedence = "runner" + "ghr:environment" = "github-actions" + }) + error_message = "Runner role tags must merge global, runner-configuration, and runner-component tags in that precedence order." + } + + assert { + condition = module.runner_configs["tagged"].orchestration.webhook.scale_down.lambda.tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + ExperimentalLambdaOnly = "experimental-lambda" + ConfigLambdaOnly = "config-lambda" + ScaleDownOnly = "scale-down" + Precedence = "scale-down" + "ghr:environment" = "github-actions" + }) + error_message = "Scale-down Lambda tags must preserve shared layers before applying scale-down component tags." + } + + assert { + condition = module.runner_configs["tagged"].orchestration.webhook.scale_down.log_group.tags == tomap({ + ExperimentalOnly = "experimental" + RunnerConfigOnly = "runner-config" + SharedLogOnly = "shared-log" + ScaleDownOnly = "scale-down" + Precedence = "scale-down" + "ghr:environment" = "github-actions" + }) + error_message = "Scale-down log-group tags must preserve shared log tags before applying scale-down component tags." + } + + assert { + condition = output.runners_map_v2["tagged"].orchestration.webhook.pool == null + error_message = "Experimental v2 must expose a null pool object when no pool configuration is supplied." + } +} + +run "experimental_v2_rejects_visibility_timeout_shorter_than_lambda_retry_window" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + lambda = { + scale = { + up = { + timeout = 40 + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-invalid-visibility" + subnet_ids = ["subnet-invalid-visibility"] + } + } + + multi_runner_config = { + invalid_visibility = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + queue = { + visibility_timeout_seconds = 239 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_conflicting_queue_encryption" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + queue = { + encryption = { + kms_data_key_reuse_period_seconds = null + kms_master_key_id = "arn:aws:kms:eu-west-1:123456789012:key/conflicting-queue" + sqs_managed_sse_enabled = true + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-invalid-encryption" + subnet_ids = ["subnet-invalid-encryption"] + } + } + + multi_runner_config = { + invalid_encryption = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_queue_kms_alias" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + queue = { + encryption = { + kms_data_key_reuse_period_seconds = 300 + kms_master_key_id = "alias/build-queue" + sqs_managed_sse_enabled = null + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-invalid-queue-kms" + subnet_ids = ["subnet-invalid-queue-kms"] + } + } + + multi_runner_config = { + invalid_queue_kms = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_queue_kms_key_id" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + queue = { + encryption = { + kms_data_key_reuse_period_seconds = 300 + kms_master_key_id = "12345678-1234-1234-1234-123456789012" + sqs_managed_sse_enabled = null + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-invalid-queue-kms-key-id" + subnet_ids = ["subnet-invalid-queue-kms-key-id"] + } + } + + multi_runner_config = { + invalid_queue_kms_key_id = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_redrive_without_max_receive_count" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + queue = { + redrive_build_queue = { + enabled = true + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-redrive-max" + subnet_ids = ["subnet-missing-redrive-max"] + } + } + multi_runner_config = { + missing_redrive_max = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_nonpositive_redrive_max_receive_count" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-nonpositive-redrive-max" + subnet_ids = ["subnet-nonpositive-redrive-max"] + } + } + multi_runner_config = { + nonpositive_redrive_max = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + queue = { + redrive_build_queue = { + enabled = true + maxReceiveCount = 0 + } + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_runner_artifact_zip_and_s3" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + } + + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + s3 = { + key = "runners.zip" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-conflicting-runner-artifact" + subnet_ids = ["subnet-conflicting-runner-artifact"] + } + } + multi_runner_config = { + conflicting_runner_artifact = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_runner_artifact_bucket_without_key" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + } + + orchestration = { + webhook = { + lambda = { + artifact = { + s3 = { + key = null + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-runner-artifact-key" + subnet_ids = ["subnet-missing-runner-artifact-key"] + } + } + multi_runner_config = { + missing_runner_artifact_key = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_runner_artifact_s3_without_bucket" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + lambda = { + artifact = { + s3 = { + key = "runners.zip" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-runner-artifact-bucket" + subnet_ids = ["subnet-missing-runner-artifact-bucket"] + } + } + multi_runner_config = { + missing_runner_artifact_bucket = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_ssm_housekeeper_artifact_zip_and_s3" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + } + ssm = { + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + s3 = { + key = "ssm-housekeeper.zip" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-conflicting-ssm-housekeeper-artifact" + subnet_ids = ["subnet-conflicting-ssm-housekeeper-artifact"] + } + } + multi_runner_config = { + conflicting_ssm_housekeeper_artifact = { + runner = { + os = "linux" + architecture = "x64" + } + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_ssm_housekeeper_artifact_s3_without_bucket" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + ssm = { + housekeeper = { + lambda = { + artifact = { + s3 = { + key = "ssm-housekeeper.zip" + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-ssm-housekeeper-artifact-bucket" + subnet_ids = ["subnet-missing-ssm-housekeeper-artifact-bucket"] + } + } + multi_runner_config = { + missing_ssm_housekeeper_artifact_bucket = { + runner = { + os = "linux" + architecture = "x64" + } + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_ssm_housekeeper_artifact_s3_without_key" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + } + ssm = { + housekeeper = { + lambda = { + artifact = { + s3 = { + key = null + } + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-missing-ssm-housekeeper-artifact-key" + subnet_ids = ["subnet-missing-ssm-housekeeper-artifact-key"] + } + } + multi_runner_config = { + missing_ssm_housekeeper_artifact_key = { + runner = { + os = "linux" + architecture = "x64" + } + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_runner_binaries_artifact_zip_and_s3" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-conflicting-binary-artifact" + subnet_ids = ["subnet-conflicting-binary-artifact"] + runner_binaries = { + syncer = { + artifact = { + zip = "runner-binaries-syncer.zip" + s3 = { + key = "runner-binaries-syncer.zip" + } + } + } + } + } + } + multi_runner_config = { + conflicting_binary_artifact = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_runner_binaries_logging_prefix_without_bucket" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-binary-logging-prefix" + subnet_ids = ["subnet-binary-logging-prefix"] + runner_binaries = { + s3 = { + logging = { + prefix = "runner-binaries/" + } + } + } + } + } + multi_runner_config = { + binary_logging_prefix = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_accepts_distinct_queue_and_ssm_kms_keys" { + command = plan + + variables { + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/shared-control-plane" + + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + orchestration = { + webhook = { + lambda = { + artifact = { + zip = "README.md" + } + + webhook = { + artifact = { + zip = "README.md" + } + } + } + + queue = { + encryption = { + kms_data_key_reuse_period_seconds = 300 + kms_master_key_id = "arn:aws:kms:eu-west-1:123456789012:key/queue-only" + sqs_managed_sse_enabled = null + } + } + } + } + ssm = { + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/shared-control-plane" + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-mismatched-queue-kms" + subnet_ids = ["subnet-mismatched-queue-kms"] + } + } + + multi_runner_config = { + mismatched_queue_kms = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + binaries_syncer = { + enabled = false + } + } + } + } + } + } + } + + assert { + condition = ( + local.translated_experimental.orchestration.webhook.queue.encryption.kms_master_key_id == "arn:aws:kms:eu-west-1:123456789012:key/queue-only" + && local.translated_experimental.ssm.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/shared-control-plane" + && local.translated_experimental.multi_runner_config["mismatched_queue_kms"].orchestration.webhook.queue.kms_key_id == "arn:aws:kms:eu-west-1:123456789012:key/queue-only" + && aws_sqs_queue.queued_builds["mismatched_queue_kms"].kms_master_key_id == "arn:aws:kms:eu-west-1:123456789012:key/queue-only" + ) + error_message = "V2 queue and shared SSM resources must accept and independently use distinct customer-managed KMS keys." + } +} + +run "experimental_v2_rejects_empty_compute_provider" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-invalid-provider" + subnet_ids = ["subnet-invalid-provider"] + } + } + + multi_runner_config = { + microvm = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + compute_provider = {} + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} + +run "experimental_v2_rejects_invalid_ssm_housekeeper_state" { + command = plan + + plan_options { + target = [terraform_data.validate_experimental] + } + + variables { + experimental = { + github = { + app = { + id = "123456" + key_base64 = "dGVzdA==" + webhook_secret = "test-secret" + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-invalid-housekeeper" + subnet_ids = ["subnet-invalid-housekeeper"] + } + } + + multi_runner_config = { + invalid = { + runner = { + os = "linux" + architecture = "x64" + } + + orchestration = { + webhook = { + runner = { + maximum_count = 2 + } + + matcherConfig = { + labelMatchers = [["self-hosted", "linux", "x64"]] + } + } + } + + ssm = { + housekeeper = { + state = "PAUSED" + } + } + + compute_provider = { + ec2 = { + instance_types = ["m5.large"] + } + } + } + } + } + } + + expect_failures = [terraform_data.validate_experimental] +} diff --git a/modules/multi-runner/validations.experimental.tf b/modules/multi-runner/validations.experimental.tf new file mode 100644 index 0000000000..d3c98b89c4 --- /dev/null +++ b/modules/multi-runner/validations.experimental.tf @@ -0,0 +1,456 @@ +resource "terraform_data" "validate_experimental" { + lifecycle { + precondition { + condition = local.use_multi_runner_config_v2 || var.github_app != null + error_message = "github_app is required when experimental.multi_runner_config is empty." + } + + precondition { + condition = local.use_multi_runner_config_v2 ? true : ( + var.github_app == null ? true : ( + (try(var.github_app.key_base64, null) != null || try(var.github_app.key_base64_ssm, null) != null) && + (try(var.github_app.id, null) != null || try(var.github_app.id_ssm, null) != null) && + (try(var.github_app.webhook_secret, null) != null || try(var.github_app.webhook_secret_ssm, null) != null) + ) + ) + error_message = "github_app must set one value from each pair: key_base64 or key_base64_ssm, id or id_ssm, and webhook_secret or webhook_secret_ssm." + } + + precondition { + condition = local.use_multi_runner_config_v2 || var.vpc_id != null + error_message = "vpc_id is required when experimental.multi_runner_config is empty." + } + + precondition { + condition = local.use_multi_runner_config_v2 || var.subnet_ids != null + error_message = "subnet_ids is required when experimental.multi_runner_config is empty." + } + + precondition { + condition = ( + length(var.experimental.multi_runner_config) == 0 || + var.experimental.github.app != null + ) + error_message = "experimental.github.app is required when experimental.multi_runner_config is not empty." + } + + precondition { + condition = !local.use_multi_runner_config_v2 ? true : ( + var.experimental.github.app == null ? true : ( + (var.experimental.github.app.key_base64 != null || var.experimental.github.app.key_base64_ssm != null) && + (var.experimental.github.app.id != null || var.experimental.github.app.id_ssm != null) && + (var.experimental.github.app.webhook_secret != null || var.experimental.github.app.webhook_secret_ssm != null) + ) + ) + error_message = "experimental.github.app must set one value from each pair: key_base64 or key_base64_ssm, id or id_ssm, and webhook_secret or webhook_secret_ssm." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || alltrue([ + for app in var.experimental.github.additional_apps : + (app.key_base64 != null || app.key_base64_ssm != null) && + (app.id != null || app.id_ssm != null) + ]) + error_message = "Each experimental.github.additional_apps entry must provide either key_base64 or key_base64_ssm, and either id or id_ssm." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + length([ + for provider_type, provider_config in runner_config.compute_provider : provider_type + if provider_config != null + ]) == 1 + ]) + error_message = "Each experimental runner configuration must set exactly one compute-provider block. Supported compute-provider blocks: ec2." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + length([ + for orchestration_type, orchestration_config in runner_config.orchestration : orchestration_type + if orchestration_config != null + ]) == 1 + ]) + error_message = "Each experimental runner configuration must set exactly one orchestration block. Supported orchestration blocks: webhook." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + try(coalesce(runner_config.runner.os, var.experimental.runner.os), null) != null && + try(coalesce(runner_config.runner.architecture, var.experimental.runner.architecture), null) != null + ]) + error_message = "Each experimental runner configuration must resolve runner.os and runner.architecture from the configuration or experimental global runner defaults." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.orchestration.webhook == null ? true : + try(coalesce( + runner_config.orchestration.webhook.runner.boot_time_in_minutes, + var.experimental.orchestration.webhook.runner.boot_time_in_minutes, + ), null) != null + ]) + error_message = "Each experimental webhook runner configuration must resolve orchestration.webhook.runner.boot_time_in_minutes from the configuration or experimental global webhook defaults." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.orchestration.webhook == null ? true : + try(coalesce( + runner_config.orchestration.webhook.runner.maximum_count, + var.experimental.orchestration.webhook.runner.maximum_count, + ), null) != null + ]) + error_message = "Each experimental webhook runner configuration must resolve orchestration.webhook.runner.maximum_count from the configuration or experimental global webhook defaults." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.compute_provider.ec2 == null ? true : ( + try(coalesce(runner_config.compute_provider.ec2.vpc_id, var.experimental.compute_provider.ec2.vpc_id), null) != null && + try(coalesce(runner_config.compute_provider.ec2.subnet_ids, var.experimental.compute_provider.ec2.subnet_ids), null) != null + ) + ]) + error_message = "Each experimental EC2 runner configuration must resolve compute_provider.ec2.vpc_id and subnet_ids from the configuration or experimental global EC2 defaults. Flat v1 inputs are not inherited by v2." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.orchestration.webhook == null ? true : ( + coalesce( + runner_config.orchestration.webhook.queue.visibility_timeout_seconds, + var.experimental.orchestration.webhook.queue.visibility_timeout_seconds, + ) >= 6 * coalesce( + runner_config.orchestration.webhook.lambda.scale.up.timeout, + var.experimental.orchestration.webhook.lambda.scale.up.timeout, + ) + ) + ]) + error_message = "Each experimental orchestration.webhook.queue.visibility_timeout_seconds must be at least six times the resolved orchestration.webhook.lambda.scale.up.timeout." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + ( + var.experimental.orchestration.webhook.queue.encryption.sqs_managed_sse_enabled != null && + var.experimental.orchestration.webhook.queue.encryption.kms_master_key_id == null && + var.experimental.orchestration.webhook.queue.encryption.kms_data_key_reuse_period_seconds == null + ) || ( + var.experimental.orchestration.webhook.queue.encryption.sqs_managed_sse_enabled == null && + var.experimental.orchestration.webhook.queue.encryption.kms_master_key_id != null + ) + ) + error_message = "Invalid experimental.orchestration.webhook.queue.encryption configuration for webhook orchestration. Use SQS-managed encryption, disable it, or configure a KMS key." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + var.experimental.orchestration.webhook.queue.encryption.kms_master_key_id == null || + can(regex( + "^arn:[^:]+:kms:[^:]+:[0-9]{12}:key/.+$", + var.experimental.orchestration.webhook.queue.encryption.kms_master_key_id, + )) + ) + error_message = "experimental.orchestration.webhook.queue.encryption.kms_master_key_id must be a KMS key ARN; key IDs and aliases cannot be used in runner-config IAM policies." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + try(contains(["linux", "osx", "windows"], coalesce(runner_config.runner.os, var.experimental.runner.os)), false) + ]) + error_message = "Experimental runner.os must be linux, osx, or windows." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + ( + var.experimental.lambda.architecture == null || + try(contains(["arm64", "x86_64"], var.experimental.lambda.architecture), false) + ) && alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.lambda.architecture == null || try(contains(["arm64", "x86_64"], runner_config.lambda.architecture), false) + ]) + ) + error_message = "Experimental lambda.architecture must be arm64 or x86_64." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + ( + var.experimental.observability.logs.level == null || + try(contains(["debug", "info", "warn", "error"], var.experimental.observability.logs.level), false) + ) && alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.observability.logs.level == null || + try(contains(["debug", "info", "warn", "error"], runner_config.observability.logs.level), false) + ]) + ) + error_message = "Experimental observability.logs.level must be debug, info, warn, or error." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + ( + var.experimental.observability.logs.class == null || + try(contains(["STANDARD", "INFREQUENT_ACCESS"], var.experimental.observability.logs.class), false) + ) && alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.observability.logs.class == null || + try(contains(["STANDARD", "INFREQUENT_ACCESS"], runner_config.observability.logs.class), false) + ]) + ) + error_message = "Experimental observability.logs.class must be STANDARD or INFREQUENT_ACCESS." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + ( + var.experimental.ssm.paths.root == null || + try(startswith(var.experimental.ssm.paths.root, "/"), false) + ) && alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.ssm.paths.root == null || try(startswith(runner_config.ssm.paths.root, "/"), false) + ]) + ) + error_message = "Experimental ssm.paths.root base paths must start with '/'. The configuration key is appended during normalization." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + ( + var.experimental.ssm.housekeeper.state == null || + try(contains(["DISABLED", "ENABLED", "ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS"], var.experimental.ssm.housekeeper.state), false) + ) && alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + runner_config.ssm.housekeeper.state == null || + try(contains(["DISABLED", "ENABLED", "ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS"], runner_config.ssm.housekeeper.state), false) + ]) + ) + error_message = "Experimental ssm.housekeeper.state must be DISABLED, ENABLED, or ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || !anytrue([ + for runner_config in values(local.translated_experimental_base.multi_runner_config) : + try(runner_config.compute_provider.ec2.binaries_syncer.enabled, false) + ]) || contains( + ["Disabled", "Enabled", "Suspended"], + var.experimental.compute_provider.ec2.runner_binaries.s3.versioning, + ) + error_message = "experimental.compute_provider.ec2.runner_binaries.s3.versioning must be Disabled, Enabled, or Suspended." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || !anytrue([ + for runner_config in values(local.translated_experimental_base.multi_runner_config) : + try(runner_config.compute_provider.ec2.binaries_syncer.enabled, false) + ]) || contains( + ["DISABLED", "ENABLED", "ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS"], + var.experimental.compute_provider.ec2.runner_binaries.syncer.schedule.state, + ) + error_message = "experimental.compute_provider.ec2.runner_binaries.syncer.schedule.state must be DISABLED, ENABLED, or ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || contains( + ["first", "random", "all"], + var.experimental.orchestration.webhook.queue_selection_strategy, + ) + error_message = "experimental.orchestration.webhook.queue_selection_strategy must be first, random, or all." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || contains( + ["Standard", "Advanced"], + var.experimental.orchestration.webhook.matcher_config_parameter_store_tier, + ) + error_message = "experimental.orchestration.webhook.matcher_config_parameter_store_tier must be Standard or Advanced." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + !( + var.experimental.orchestration.webhook.lambda.artifact.zip != null && + var.experimental.orchestration.webhook.lambda.artifact.s3 != null + ) && ( + var.experimental.orchestration.webhook.lambda.artifact.s3 == null || ( + var.experimental.lambda.artifact.s3.bucket != null && + try(var.experimental.orchestration.webhook.lambda.artifact.s3.key != null, false) + ) + ) + ) + error_message = "experimental.orchestration.webhook.lambda.artifact must set at most one of zip or s3; an s3 wrapper requires experimental.lambda.artifact.s3.bucket and a non-null key." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + !( + var.experimental.orchestration.webhook.lambda.webhook.artifact.zip != null && + var.experimental.orchestration.webhook.lambda.webhook.artifact.s3 != null + ) && ( + var.experimental.orchestration.webhook.lambda.webhook.artifact.s3 == null || ( + var.experimental.lambda.artifact.s3.bucket != null && + try(var.experimental.orchestration.webhook.lambda.webhook.artifact.s3.key != null, false) + ) + ) + ) + error_message = "experimental.orchestration.webhook.lambda.webhook.artifact must set at most one of zip or s3; an s3 wrapper requires experimental.lambda.artifact.s3.bucket and a non-null key." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + !( + var.experimental.ssm.housekeeper.lambda.artifact.zip != null && + var.experimental.ssm.housekeeper.lambda.artifact.s3 != null + ) && alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : !( + runner_config.ssm.housekeeper.lambda.artifact.zip != null && + runner_config.ssm.housekeeper.lambda.artifact.s3 != null + ) + ]) + ) + error_message = "experimental ssm.housekeeper.lambda.artifact must set at most one of zip or s3 at each global or runner-configuration scope." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || alltrue([ + for runner_config in values(local.translated_experimental_base.multi_runner_config) : + runner_config.ssm.housekeeper.lambda.artifact.s3 == null || ( + var.experimental.lambda.artifact.s3.bucket != null && + try(runner_config.ssm.housekeeper.lambda.artifact.s3.key != null, false) + ) + ]) + error_message = "A resolved experimental ssm.housekeeper.lambda.artifact.s3 wrapper requires experimental.lambda.artifact.s3.bucket and a non-null key." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + !( + var.experimental.compute_provider.ec2.instance_termination_watcher.artifact.zip != null && + var.experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3 != null + ) && ( + var.experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3 == null || ( + var.experimental.lambda.artifact.s3.bucket != null && + try(var.experimental.compute_provider.ec2.instance_termination_watcher.artifact.s3.key != null, false) + ) + ) + ) + error_message = "experimental.compute_provider.ec2.instance_termination_watcher.artifact must set at most one of zip or s3; an s3 wrapper requires experimental.lambda.artifact.s3.bucket and a non-null key." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + !( + var.experimental.compute_provider.ec2.ami.housekeeper.artifact.zip != null && + var.experimental.compute_provider.ec2.ami.housekeeper.artifact.s3 != null + ) && ( + var.experimental.compute_provider.ec2.ami.housekeeper.artifact.s3 == null || ( + var.experimental.lambda.artifact.s3.bucket != null && + try(var.experimental.compute_provider.ec2.ami.housekeeper.artifact.s3.key != null, false) + ) + ) + ) + error_message = "experimental.compute_provider.ec2.ami.housekeeper.artifact must set at most one of zip or s3; an s3 wrapper requires experimental.lambda.artifact.s3.bucket and a non-null key." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || !( + var.experimental.compute_provider.ec2.runner_binaries.syncer.artifact.zip != null && + var.experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3 != null + ) + error_message = "experimental.compute_provider.ec2.runner_binaries.syncer.artifact must set at most one of zip or s3." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + var.experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3 == null ? true : ( + var.experimental.lambda.artifact.s3.bucket != null && + var.experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3.key != null + ) + ) + error_message = "experimental.compute_provider.ec2.runner_binaries.syncer.artifact.s3 requires experimental.lambda.artifact.s3.bucket and a non-null key." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || contains( + ["AES256", "aws:kms", "aws:kms:dsse"], + var.experimental.compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm, + ) + error_message = "experimental.compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm must be AES256, aws:kms, or aws:kms:dsse." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + !var.experimental.compute_provider.ec2.runner_binaries.s3.encryption.enabled ? ( + var.experimental.compute_provider.ec2.runner_binaries.s3.encryption.kms_master_key_id == null + ) : ( + var.experimental.compute_provider.ec2.runner_binaries.s3.encryption.kms_master_key_id == null || + contains( + ["aws:kms", "aws:kms:dsse"], + var.experimental.compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm, + ) + ) + ) + error_message = "experimental.compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm must be aws:kms or aws:kms:dsse when kms_master_key_id is set." + } + + precondition { + condition = alltrue([ + for runner_config in values(local.translated_experimental_base.multi_runner_config) : + runner_config.orchestration.webhook == null ? true : ( + !runner_config.orchestration.webhook.queue.redrive_build_queue.enabled || try( + runner_config.orchestration.webhook.queue.redrive_build_queue.maxReceiveCount > 0, + false, + ) + ) + ]) + error_message = "An enabled experimental orchestration.webhook.queue.redrive_build_queue requires maxReceiveCount greater than zero." + } + + precondition { + condition = !local.use_multi_runner_config_v2 || ( + var.experimental.compute_provider.ec2.runner_binaries.s3.logging.prefix == null || + var.experimental.compute_provider.ec2.runner_binaries.s3.logging.bucket != null + ) + error_message = "experimental.compute_provider.ec2.runner_binaries.s3.logging.prefix requires logging.bucket." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + try(coalesce(runner_config.runner.iam.role, var.experimental.runner.iam.role), null) == null || + length( + runner_config.runner.iam.role != null ? ( + runner_config.runner.iam.managed_policy_arns != null ? runner_config.runner.iam.managed_policy_arns : {} + ) : ( + runner_config.runner.iam.managed_policy_arns != null ? runner_config.runner.iam.managed_policy_arns : ( + var.experimental.runner.iam.managed_policy_arns != null ? var.experimental.runner.iam.managed_policy_arns : {} + ) + ) + ) == 0 + ]) + error_message = "runner.iam.managed_policy_arns cannot be set with an external runner.iam.role because external roles are not managed by this module." + } + + precondition { + condition = alltrue([ + for runner_config in values(var.experimental.multi_runner_config) : + try(coalesce(runner_config.runner.iam.role, var.experimental.runner.iam.role), null) == null || + ( + runner_config.runner.iam.role != null ? runner_config.runner.iam.additional_trust_policy_json : + try(coalesce(runner_config.runner.iam.additional_trust_policy_json, var.experimental.runner.iam.additional_trust_policy_json), null) + ) == null + ]) + error_message = "runner.iam.additional_trust_policy_json cannot be set with an external runner.iam.role because external roles are not managed by this module." + } + + } +} diff --git a/modules/multi-runner/variables.experimental.tf b/modules/multi-runner/variables.experimental.tf new file mode 100644 index 0000000000..79445278b9 --- /dev/null +++ b/modules/multi-runner/variables.experimental.tf @@ -0,0 +1,1151 @@ +variable "experimental" { + description = <<-EOT + Opt-in experimental features. Omit this object to retain only the stable `multi_runner_config` behavior. Experimental schemas can change before they become stable. + + Set `experimental.multi_runner_config` to opt into provider-oriented runner configurations. A non-empty experimental map completely replaces the stable top-level `multi_runner_config`; an empty map keeps stable entries on the unchanged `runners` module. + + Sibling blocks provide global v2 defaults. Global and per-configuration values use `configuration override > experimental global v2 default` precedence. Migrated v2 consumers do not inherit a matching flat module input. Singleton shared components consume the global translated values documented below; per-configuration overrides affect only their runner configuration. Component-specific inputs without a nested counterpart continue consuming their existing flat inputs. Tag maps merge from broad to narrow instead of replacing the broader map. + Nullable per-configuration values inherit their experimental global value, so only defaults that apply to every runner configuration should be placed in a global block. When a runner configuration selects an external `runner.iam.role`, inherited managed policies and additional trust policy JSON are intentionally suppressed because this module does not manage that role. + Plan-shaping ownership wrappers remain nullable where their object presence controls Terraform graph shape. `ssm.kms_key_id` is instead an ARN-valued scalar; provider-owned IAM omits null KMS statements while still accepting an ARN whose value is unknown until apply. The unchanged shared webhook retains its legacy policy handling. + + Global experimental fields support the following nested properties. These values apply directly when `experimental.multi_runner_config` is non-empty; in stable mode, flat inputs are translated into the same global shape. + + - `tags`: Base tags for v2 build queues, runner configurations, the shared GitHub App Parameter Store module, webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `{}`. + - `roles.path`: Default IAM path for module-managed v2 runner and Lambda roles and for the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper Lambda roles. The default is null. + - `roles.permissions_boundary`: Default permissions-boundary ARN for module-managed v2 runner and Lambda roles and for the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper Lambda roles. The default is null. + - `runner.os`: Default runner operating system. The default is null; every runner configuration must resolve this field globally or locally. + - `runner.architecture`: Default runner distribution architecture. The default is null; every runner configuration must resolve this field globally or locally. + - `runner.disable_default_labels`: Omits the default self-hosted, operating-system, and architecture labels when true. The default is `false`. + - `runner.extra_labels`: Default additional labels combined with each runner configuration's matcher labels. The default is `[]`. + - `runner.group_name`: Default GitHub runner group. The default is `Default`. + - `runner.name_prefix`: Default prefix added to registered runner names. The default is an empty string. + - `runner.run_as_root`: Runs the runner service as root when supported by the provider. The default is `false`. + - `runner.run_as`: Default operating-system user when `run_as_root` is false. The default is `ec2-user`. + - `runner.auto_update_disabled`: Disables the GitHub runner application's built-in updater. The default is `false`. + - `runner.tags`: Default tags for common runner resources, currently the module-managed runner IAM role. The default is `{}`. + - `runner.hooks.job_started`: Default script content installed as the runner job-started hook. The default is an empty string. + - `runner.hooks.job_completed`: Default script content installed as the runner job-completed hook. The default is an empty string. + - `runner.iam.role`: Optional externally managed runner-role wrapper. The default is null; wrapper presence selects external role ownership during planning. + - `runner.iam.role.arn`: ARN of the externally managed runner role. + - `runner.iam.managed_policy_arns`: Named managed-policy ARNs attached to module-managed runner roles. The default is `{}`. Keep this map empty when the global `runner.iam.role` selects an external role; a runner configuration that explicitly selects its own external role suppresses the inherited map. + - `runner.iam.additional_trust_policy_json`: Optional IAM policy document merged with the provider trust policy for module-managed runner roles. The default is null. Keep it null when the global `runner.iam.role` selects an external role; a runner configuration that explicitly selects its own external role suppresses the inherited value. + - `runner.iam.path`: Runner-role IAM path. The default is null, which falls back to `roles.path`. + - `runner.iam.permissions_boundary`: Runner-role permissions-boundary ARN. The default is null, which falls back to `roles.permissions_boundary`. + - `github.app`: Primary GitHub App credentials persisted or selected by the shared Parameter Store module and used by v2 runner configurations. The default is null, but a non-empty v2 map requires this object. + - `github.app.key_base64`: Base64-encoded GitHub App private key supplied directly. + - `github.app.key_base64_ssm`: Existing Parameter Store private-key parameter wrapper. Set this or `key_base64`. + - `github.app.key_base64_ssm.arn`: ARN of the existing private-key parameter. + - `github.app.key_base64_ssm.name`: Name of the existing private-key parameter. + - `github.app.id`: GitHub App ID supplied directly. + - `github.app.id_ssm`: Existing Parameter Store app-ID parameter wrapper. Set this or `id`. + - `github.app.id_ssm.arn`: ARN of the existing app-ID parameter. + - `github.app.id_ssm.name`: Name of the existing app-ID parameter. + - `github.app.webhook_secret`: GitHub App webhook secret supplied directly. + - `github.app.webhook_secret_ssm`: Existing Parameter Store webhook-secret parameter wrapper. Set this or `webhook_secret`. + - `github.app.webhook_secret_ssm.arn`: ARN of the existing webhook-secret parameter. + - `github.app.webhook_secret_ssm.name`: Name of the existing webhook-secret parameter. + - `github.additional_apps`: Additional GitHub App credentials persisted or selected by the shared Parameter Store module and used for API request distribution. The default is `[]`. + - `github.additional_apps[].key_base64`: Base64-encoded private key supplied directly for an additional app. + - `github.additional_apps[].key_base64_ssm`: Existing Parameter Store private-key parameter wrapper. Set this or `key_base64`. + - `github.additional_apps[].key_base64_ssm.arn`: ARN of the existing additional-app private-key parameter. + - `github.additional_apps[].key_base64_ssm.name`: Name of the existing additional-app private-key parameter. + - `github.additional_apps[].id`: Additional GitHub App ID supplied directly. + - `github.additional_apps[].id_ssm`: Existing Parameter Store app-ID parameter wrapper. Set this or `id`. + - `github.additional_apps[].id_ssm.arn`: ARN of the existing additional-app ID parameter. + - `github.additional_apps[].id_ssm.name`: Name of the existing additional-app ID parameter. + - `github.additional_apps[].installation_id`: Optional installation ID supplied directly for an additional app. + - `github.additional_apps[].installation_id_ssm`: Optional existing Parameter Store installation-ID parameter wrapper. + - `github.additional_apps[].installation_id_ssm.arn`: ARN of the existing installation-ID parameter. + - `github.additional_apps[].installation_id_ssm.name`: Name of the existing installation-ID parameter. + - `github.enterprise_server.url`: GitHub Enterprise Server URL used by v2 runner-config GitHub clients and the shared termination watcher. The default is null. + - `github.enterprise_server.ssl_verify`: Enables TLS certificate verification for v2 runner-config GitHub clients. The default is `true`. + - `github.user_agent`: HTTP User-Agent used by v2 runner-config GitHub clients. The default is `github-aws-runners`. + - `lambda.artifact.s3.bucket`: Optional shared S3 bucket containing Lambda deployment artifacts for v2 runner configurations and their SSM housekeepers, the webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is null. A component selects an object from this bucket only when its own `artifact.s3` wrapper is present. + - `lambda.runtime`: Runtime for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `nodejs24.x`. + - `lambda.architecture`: Architecture for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `arm64`. + - `lambda.principals`: Additional principals allowed to assume v2 runner-config, runner-binary syncer, termination-watcher, and AMI-housekeeper Lambda roles. The default is `[]`; list membership must be known during planning because it creates IAM principal blocks. + - `lambda.principals[].type`: IAM principal type. + - `lambda.principals[].identifiers`: IAM principal identifiers for the type. + - `lambda.subnet_ids`: Subnets for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `[]`. + - `lambda.security_group_ids`: Security groups for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `[]`. + - `lambda.tags`: Default tags for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `{}`. + - `lambda.role.path`: IAM path for module-managed v2 Lambda roles and the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper roles. The default is null, which falls back to `roles.path`. + - `lambda.role.permissions_boundary`: Permissions-boundary ARN for module-managed v2 Lambda roles and the shared webhook, runner-binary syncer, termination-watcher, and AMI-housekeeper roles. The default is null, which falls back to `roles.permissions_boundary`. + - `orchestration.webhook`: Global defaults for the workflow-job webhook control plane. This is a defaults namespace; every runner configuration still selects its demand controller independently under `multi_runner_config[].orchestration`, where exactly one typed provider block must be non-null. + - `orchestration.webhook.queue_selection_strategy`: Queue-selection strategy when multiple runner configurations match a job equally well. The default is `first`, which deterministically selects the first matching queue by priority. `random` spreads jobs across equally matched queues. `all` dispatches to every matching queue, favoring startup speed at the cost of multiple runner launches and registrations for one job. + - `orchestration.webhook.eventbridge.enable`: Routes accepted webhook events through EventBridge when true. The default is `true`, and the value must be known during planning because it selects the webhook implementation. + - `orchestration.webhook.eventbridge.accept_events`: EventBridge event types accepted by the shared webhook. The default is `[]`, which accepts all supported events. + - `orchestration.webhook.matcher_config_parameter_store_tier`: Parameter Store tier for the shared matcher configuration. The default is `Standard`; valid values are `Standard` and `Advanced`. The value must be known during planning because it determines the matcher-parameter chunks. + - `orchestration.webhook.github.repository_white_list`: Repository full names allowed to use the shared webhook. The default is `[]`, which disables repository filtering. + - `orchestration.webhook.runner.boot_time_in_minutes`: Default expected runner boot duration used by webhook scale-down and pool controls. The default is `5`. + - `orchestration.webhook.runner.ephemeral`: Registers webhook-orchestrated runners in ephemeral mode by default. The default is `false`. + - `orchestration.webhook.runner.jit_config_enabled`: Explicit default for just-in-time runner configuration. The default is null, which follows the resolved `ephemeral` mode. + - `orchestration.webhook.runner.maximum_count`: Default maximum number of runners managed by the webhook orchestration provider per runner configuration. The default is null; every webhook runner configuration must resolve this field globally or locally. + - `orchestration.webhook.lambda.artifact`: Shared runner-control-plane artifact used by webhook scale, pool, and job-retry components. Set at most one of `zip` or `s3`; when both are null, the packaged runner archive is used. + - `orchestration.webhook.lambda.artifact.zip`: Optional local path to the shared runner-control-plane Lambda archive. The default is null. + - `orchestration.webhook.lambda.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for runner-control-plane Lambdas, must be known during planning, and requires a non-null shared bucket and key. + - `orchestration.webhook.lambda.artifact.s3.key`: Object key of the shared runner-control-plane Lambda archive. + - `orchestration.webhook.lambda.artifact.s3.object_version`: Optional object version of the shared runner-control-plane Lambda archive. The default is null. + - `orchestration.webhook.lambda.scale.up.memory_size`: Scale-up Lambda memory in MB. The default is `512`. + - `orchestration.webhook.lambda.scale.up.timeout`: Scale-up Lambda timeout in seconds. The default is `30`. + - `orchestration.webhook.lambda.scale.up.reserved_concurrent_executions`: Reserved concurrency for scale-up. The default is `1`; use `-1` for unreserved concurrency. + - `orchestration.webhook.lambda.scale.up.job_queued_check_enabled`: Enables queued-job verification before scaling. The default is null, which follows the resolved runner mode. + - `orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size`: Maximum build-queue records delivered per scale-up invocation. The default is `10`. + - `orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds`: Maximum build-queue batching window. The default is `0`. + - `orchestration.webhook.lambda.scale.up.tags`: Default tags for scale-up resources. The default is `{}`. + - `orchestration.webhook.lambda.scale.down.memory_size`: Scale-down Lambda memory in MB. The default is `512`. + - `orchestration.webhook.lambda.scale.down.timeout`: Scale-down Lambda timeout in seconds. The default is `60`. + - `orchestration.webhook.lambda.scale.down.schedule_expression`: EventBridge schedule for scale-down. The default is `cron(*/5 * * * ? *)`. + - `orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes`: Minimum runner age before scale-down may terminate it. The default is null, which selects the operating-system default. + - `orchestration.webhook.lambda.scale.down.idle_config`: Default time-based desired idle-runner configurations. The default is `[]`. + - `orchestration.webhook.lambda.scale.down.idle_config[].cron`: Cron expression identifying when the idle configuration applies. + - `orchestration.webhook.lambda.scale.down.idle_config[].timeZone`: IANA time zone used to evaluate the cron expression. + - `orchestration.webhook.lambda.scale.down.idle_config[].idleCount`: Number of idle runners retained during the matching period. + - `orchestration.webhook.lambda.scale.down.idle_config[].evictionStrategy`: Selection strategy used when excess idle runners are removed. The default is `oldest_first`. + - `orchestration.webhook.lambda.scale.down.tags`: Default tags for scale-down resources. The default is `{}`. + - `orchestration.webhook.lambda.webhook.artifact`: Shared-webhook artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used. + - `orchestration.webhook.lambda.webhook.artifact.zip`: Optional local path to the shared-webhook Lambda archive. The default is null. + - `orchestration.webhook.lambda.webhook.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for the webhook and requires a non-null shared bucket and key. + - `orchestration.webhook.lambda.webhook.artifact.s3.key`: Object key of the shared-webhook Lambda archive. + - `orchestration.webhook.lambda.webhook.artifact.s3.object_version`: Optional object version of the shared-webhook Lambda archive. The default is null. + - `orchestration.webhook.lambda.webhook.api_gateway_access_log_settings`: Optional API Gateway access-log destination and format for the shared webhook. The default is null, and wrapper presence must be known during planning because it controls the access-log block. + - `orchestration.webhook.lambda.webhook.api_gateway_access_log_settings.destination_arn`: CloudWatch Logs destination ARN for API Gateway access logs. + - `orchestration.webhook.lambda.webhook.api_gateway_access_log_settings.format`: API Gateway access-log format. + - `orchestration.webhook.lambda.webhook.memory_size`: Shared-webhook Lambda memory in MB. The default is `256`. + - `orchestration.webhook.lambda.webhook.timeout`: Shared-webhook Lambda timeout in seconds. The default is `10`. + - `orchestration.webhook.lambda.webhook.tags`: Additional tags for the shared webhook Lambda, merged after `lambda.tags`. The default is `{}`. + - `orchestration.webhook.lambda.pool.memory_size`: Pool Lambda memory in MB. The default is `512`. + - `orchestration.webhook.lambda.pool.timeout`: Pool Lambda timeout in seconds. The default is `60`. + - `orchestration.webhook.lambda.pool.reserved_concurrent_executions`: Reserved concurrency for the pool Lambda. The default is `1`; use `-1` for unreserved concurrency. + - `orchestration.webhook.lambda.pool.config`: Default scheduled target pool sizes. The default is `[]`, which disables the pool component. + - `orchestration.webhook.lambda.pool.config[].schedule_expression`: Scheduler expression that activates the target size. + - `orchestration.webhook.lambda.pool.config[].schedule_expression_timezone`: Optional IANA time zone used to evaluate the schedule. + - `orchestration.webhook.lambda.pool.config[].size`: Desired runner-pool size for the schedule. + - `orchestration.webhook.lambda.pool.include_busy_runners`: Includes busy runners when reconciling scheduled pool capacity. The default is `false`. + - `orchestration.webhook.lambda.pool.runner_owner`: Optional GitHub organization or repository owner used for pooled runners. The default is null. + - `orchestration.webhook.lambda.pool.tags`: Default tags for pool resources. The default is `{}`. + - `orchestration.webhook.queue.delay_webhook_event`: Default delay in seconds applied to accepted webhook jobs. The default is `30`. + - `orchestration.webhook.queue.job_queue_retention_in_seconds`: Default build-queue message retention period in seconds. The default is `86400`. + - `orchestration.webhook.queue.visibility_timeout_seconds`: Default build-queue visibility timeout. The default is `180`; set it to at least six times every resolved `orchestration.webhook.lambda.scale.up.timeout` that inherits it. + - `orchestration.webhook.queue.redrive_build_queue.enabled`: Creates and attaches a dead-letter queue to every v2 build queue by default. The default is `false`. + - `orchestration.webhook.queue.redrive_build_queue.maxReceiveCount`: Default number of receives before a message moves to the dead-letter queue. The default is null while redrive is disabled and must resolve to a value greater than zero when redrive is enabled. + - `orchestration.webhook.queue.tags`: Default tags for v2 build queues and dead-letter queues. The default is `{}`. + - `orchestration.webhook.queue.encryption`: Global at-rest encryption configuration for the multi-runner build queues and their dead-letter queues. It does not configure runner-config job-retry queues. Omitting the whole block selects SQS-managed encryption and defaults the two KMS attributes to null. When supplying the block explicitly, provide all three leaf attributes and use null for the inactive mode. + - `orchestration.webhook.queue.encryption.kms_data_key_reuse_period_seconds`: KMS data-key reuse period in seconds. This key is required syntactically in an explicit `queue.encryption` object but may be null; it is used only with `kms_master_key_id`. + - `orchestration.webhook.queue.encryption.kms_master_key_id`: KMS key ARN used for queue encryption. This AWS-facing field name is retained for compatibility, but non-null values must be key ARNs because runner-config IAM policies cannot use key IDs or aliases as resources. The field is required syntactically in an explicit `queue.encryption` object but may be null, and a computed ARN may remain unknown until apply. It is independent from `ssm.kms_key_id` and is forwarded separately to each webhook runner configuration so runner-config scale-up and job-retry roles receive only the build-queue KMS permissions they require. + - `orchestration.webhook.queue.encryption.sqs_managed_sse_enabled`: Selects the non-KMS mode: `true` enables SQS-managed encryption and `false` explicitly disables queue encryption. This key is required syntactically in an explicit `queue.encryption` object and must be null when `kms_master_key_id` is set. Omitting the whole encryption block defaults it to `true`. + - `ssm.paths.root`: Base Parameter Store path for shared GitHub App and webhook parameters and for all v2 runner configurations. The schema default is null, which derives `/github-action-runners/`; normalization appends the configuration key only for configuration-owned paths. + - `ssm.paths.app`: Shared GitHub App credential path segment below `ssm.paths.root`. The default is `app`. + - `ssm.paths.webhook`: Shared webhook matcher-configuration path segment below `ssm.paths.root`. The default is `webhook`. + - `ssm.paths.tokens`: Runner registration-token and JIT-configuration path segment below each runner-configuration root. The default is `runners/tokens`. + - `ssm.paths.config`: Persistent runner-configuration path segment below each runner-configuration root. The default is `runners/config`. + - `ssm.kms_key_id`: Optional global KMS key ARN that encrypts shared GitHub App parameters, configures the webhook and termination watcher, and adds matching decrypt permissions to every v2 runner configuration. The default is null and its value may be unknown until apply. It does not select encryption for runtime-created runner-configuration parameters. + - `ssm.tags`: Default tags for the shared GitHub App Parameter Store module and runner-configuration-owned SSM resources. The default is `{}`. + - `ssm.parameters.tags`: Default tags for Terraform-managed and runtime-created runner-configuration parameters. The default is `{}`. + - `ssm.housekeeper.schedule_expression`: Default EventBridge schedule for each runner-configuration SSM housekeeper. The default is `rate(1 day)`. + - `ssm.housekeeper.state`: Default EventBridge rule state for each runner-configuration SSM housekeeper. The default is `ENABLED`. + - `ssm.housekeeper.tags`: Default tags for SSM housekeeper resources. The default is `{}`. + - `ssm.housekeeper.lambda.artifact`: Default SSM-housekeeper artifact selection. Set at most one of `zip` or `s3`; when both are null, runner-config uses its packaged runner control-plane archive. + - `ssm.housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive. The default is null. + - `ssm.housekeeper.lambda.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for the SSM housekeeper, must be known during planning, and requires a non-null shared bucket and key. + - `ssm.housekeeper.lambda.artifact.s3.key`: Object key of the SSM-housekeeper Lambda archive. + - `ssm.housekeeper.lambda.artifact.s3.object_version`: Optional object version of the SSM-housekeeper Lambda archive. The default is null. + - `ssm.housekeeper.lambda.memory_size`: Default SSM housekeeper Lambda memory in MB. The default is `512`. + - `ssm.housekeeper.lambda.timeout`: Default SSM housekeeper Lambda timeout in seconds. The default is `60`. + - `ssm.housekeeper.config.tokenPath`: Optional cleanup path shared by every runner configuration. The default is null; omit it so each runner configuration derives its isolated token path. + - `ssm.housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed. The default is `1`. + - `ssm.housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true. The default is `false`. + - `observability.logs.level`: Application log level for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `info`. + - `observability.logs.retention_in_days`: CloudWatch Logs retention for v2 runner-config resources and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `180`. + - `observability.logs.kms_key_id`: Optional KMS key ID or ARN for v2 runner-config log groups and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is null. + - `observability.logs.class`: CloudWatch log-group class for v2 runner-config resources and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is `STANDARD`. + - `observability.logs.tags`: Default tags for v2 runner-config log groups. The default is `{}`; shared singleton functions receive `tags` and `lambda.tags` instead. + - `observability.tracing.mode`: Optional Lambda tracing mode for v2 runner-config functions and the shared webhook, runner-binary syncer, termination watcher, and AMI housekeeper. The default is null; its nullness must be known during planning because it controls X-Ray IAM and tracing blocks. + - `observability.tracing.capture_http_requests`: Enables HTTP request capture in the tracing helper for v2 runner-config functions and translated shared consumers. The default is `false`. + - `observability.tracing.capture_error`: Enables error capture in the tracing helper for v2 runner-config functions and translated shared consumers. The default is `false`. + - `observability.metrics.enable`: Enables module-emitted metrics for v2 runner configurations and the shared termination watcher. The default is `false`. + - `observability.metrics.namespace`: CloudWatch namespace for v2 runner-config and termination-watcher metrics. The default is `GitHub Runners`. + - `observability.metrics.metric.enable_github_app_rate_limit`: Emits GitHub App rate-limit metrics when metrics are enabled. The default is `true`. + - `observability.metrics.metric.enable_job_retry`: Emits job-retry metrics when metrics are enabled. The default is `true`. + - `observability.metrics.metric.enable_spot_termination`: Emits Spot termination metrics from the shared termination watcher when metrics are enabled. The default is `true`. + - `observability.metrics.metric.enable_spot_termination_warning`: Emits Spot termination-warning metrics from the shared termination watcher when metrics are enabled. The default is `true`. + - `compute_provider.ec2.vpc_id`: Shared VPC default for v2 EC2 runner configurations. The default is null; every EC2 runner configuration must resolve this field globally or locally. + - `compute_provider.ec2.subnet_ids`: Shared subnet default for v2 EC2 runner configurations. The default is null; every EC2 runner configuration must resolve this field globally or locally. + - `compute_provider.ec2.managed_security_group_enabled`: Creates the module-managed runner security group by default. The default is `true`. + - `compute_provider.ec2.egress_rules`: Shared runner security-group egress rules. The default is one IPv4/IPv6 allow-all rule; v2 does not inherit flat `runner_egress_rules`. + - `compute_provider.ec2.egress_rules[].cidr_blocks`: IPv4 CIDR destinations for an egress rule. + - `compute_provider.ec2.egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations for an egress rule. + - `compute_provider.ec2.egress_rules[].prefix_list_ids`: Prefix-list destinations for an egress rule. + - `compute_provider.ec2.egress_rules[].from_port`: Start of the egress rule port range. + - `compute_provider.ec2.egress_rules[].protocol`: Egress rule protocol; `-1` allows every protocol. + - `compute_provider.ec2.egress_rules[].security_groups`: Destination security-group IDs for an egress rule. + - `compute_provider.ec2.egress_rules[].self`: Allows traffic to the managed security group itself when true. + - `compute_provider.ec2.egress_rules[].to_port`: End of the egress rule port range. + - `compute_provider.ec2.egress_rules[].description`: Optional egress rule description. + - `compute_provider.ec2.additional_security_group_ids`: Existing security groups attached to every v2 EC2 runner configuration unless overridden. The default is `[]`. + - `compute_provider.ec2.cloudwatch_agent.config`: Optional complete CloudWatch agent configuration inherited by v2 EC2 runner configurations. The default is null; enablement remains configuration-owned. + - `compute_provider.ec2.instance_profile_path`: IAM path for module-managed EC2 instance profiles. The default is null. + - `compute_provider.ec2.key_name`: Optional EC2 key-pair name inherited by v2 EC2 runner configurations. The default is null. + - `compute_provider.ec2.associate_public_ipv4_address`: Associates public IPv4 addresses with v2 EC2 runners unless overridden. The default is `false`. + - `compute_provider.ec2.tags`: Default tags for runtime EC2 resources. The default is `{}` and runner-configuration EC2 tags take precedence. + - `compute_provider.ec2.ami.housekeeper`: Global configuration for the shared AMI-housekeeper Lambda. + - `compute_provider.ec2.ami.housekeeper.enabled`: Creates the shared AMI housekeeper when true. The default is `false`, and the value must be known during planning because it controls the module instance. + - `compute_provider.ec2.ami.housekeeper.cleanup_config`: AMI cleanup selection and safety settings. The default is `{}`, which resolves the leaf defaults described below in the AMI-housekeeper module. + - `compute_provider.ec2.ami.housekeeper.cleanup_config.maxItems`: Optional maximum number of AMIs queried for cleanup. The default is null, which applies no maximum. + - `compute_provider.ec2.ami.housekeeper.cleanup_config.minimumDaysOld`: Minimum AMI age in days before cleanup. The effective default is `30`. + - `compute_provider.ec2.ami.housekeeper.cleanup_config.amiFilters`: AMI filters, each containing `Name` and `Values`. The effective default selects images with `state = available` and `image-type = machine`. + - `compute_provider.ec2.ami.housekeeper.cleanup_config.launchTemplateNames`: Optional launch-template names whose referenced AMIs are retained. The default is null, which selects no launch templates. + - `compute_provider.ec2.ami.housekeeper.cleanup_config.ssmParameterNames`: Optional Parameter Store names whose referenced AMIs are retained. The default is null, which selects no parameters. + - `compute_provider.ec2.ami.housekeeper.cleanup_config.dryRun`: Reports eligible AMIs without deregistering them when true. The effective default is `false`. + - `compute_provider.ec2.ami.housekeeper.artifact`: AMI-housekeeper artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used. + - `compute_provider.ec2.ami.housekeeper.artifact.zip`: Optional local path to the AMI-housekeeper Lambda archive. The default is null. + - `compute_provider.ec2.ami.housekeeper.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 and requires a non-null shared bucket and key. + - `compute_provider.ec2.ami.housekeeper.artifact.s3.key`: Object key of the AMI-housekeeper Lambda archive. + - `compute_provider.ec2.ami.housekeeper.artifact.s3.object_version`: Optional object version of the AMI-housekeeper Lambda archive. The default is null. + - `compute_provider.ec2.ami.housekeeper.lambda.memory_size`: AMI-housekeeper Lambda memory in MB. The default is `256`. + - `compute_provider.ec2.ami.housekeeper.lambda.timeout`: AMI-housekeeper Lambda timeout in seconds. The default is `300`. + - `compute_provider.ec2.ami.housekeeper.schedule.expression`: AMI-housekeeper EventBridge schedule expression. The default is `cron(11 7 * * ? *)`. + - `compute_provider.ec2.instance_termination_watcher`: Global configuration for the shared EC2 instance-termination watcher. + - `compute_provider.ec2.instance_termination_watcher.enabled`: Creates the shared EC2 termination watcher when true. The default is `false`, and the value must be known during planning because it controls the module instance. + - `compute_provider.ec2.instance_termination_watcher.features.enable_spot_termination_handler`: Enables the Spot termination-event handler. The default is `true`, and the value must be known during planning because it controls child resources. + - `compute_provider.ec2.instance_termination_watcher.features.enable_spot_termination_notification_watcher`: Enables the Spot interruption-warning watcher. The default is `true`, and the value must be known during planning because it controls child resources. + - `compute_provider.ec2.instance_termination_watcher.enable_runner_deregistration`: Deregisters terminated runners from GitHub when true. The default is `true`, and the value must be known during planning because it controls deregistration resources. + - `compute_provider.ec2.instance_termination_watcher.environment_variables`: Additional termination-watcher Lambda environment variables. The default is `{}`. + - `compute_provider.ec2.instance_termination_watcher.artifact`: Termination-watcher artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used. + - `compute_provider.ec2.instance_termination_watcher.artifact.zip`: Optional local path to the termination-watcher Lambda archive. The default is null. + - `compute_provider.ec2.instance_termination_watcher.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 and requires a non-null shared bucket and key. + - `compute_provider.ec2.instance_termination_watcher.artifact.s3.key`: Object key of the termination-watcher Lambda archive. + - `compute_provider.ec2.instance_termination_watcher.artifact.s3.object_version`: Optional object version of the termination-watcher Lambda archive. The default is null. + - `compute_provider.ec2.instance_termination_watcher.lambda.memory_size`: Optional watcher Lambda memory in MB. The default is null, which delegates to the termination-watcher module. + - `compute_provider.ec2.instance_termination_watcher.lambda.timeout`: Optional watcher Lambda timeout in seconds. The default is null, which delegates to the termination-watcher module. + - `compute_provider.ec2.runner_binaries`: Global configuration for the shared runner-distribution buckets and syncers, created once per unique enabled runner operating-system and architecture pair. + - `compute_provider.ec2.runner_binaries.enabled`: Default for whether EC2 runner configurations use the synchronized runner distribution. The default is `true`; a runner configuration may override it through `compute_provider.ec2.binaries_syncer.enabled`. Every resolved enable value must be known during planning because it determines the syncer module instances. + - `compute_provider.ec2.runner_binaries.s3`: Settings for each shared runner-distribution bucket. + - `compute_provider.ec2.runner_binaries.s3.encryption`: Server-side encryption settings for each distribution bucket. + - `compute_provider.ec2.runner_binaries.s3.encryption.enabled`: Creates an explicit distribution-bucket encryption configuration when true. The default is `true`, and the value must be known during planning because it controls resource shape. Keep `kms_master_key_id` null when this is false. + - `compute_provider.ec2.runner_binaries.s3.encryption.bucket_key_enabled`: Optional S3 Bucket Key setting. The default is null. + - `compute_provider.ec2.runner_binaries.s3.encryption.sse_algorithm`: Server-side encryption algorithm. The default is `AES256`; valid values are `AES256`, `aws:kms`, and `aws:kms:dsse`. When `kms_master_key_id` is set, use one of the KMS algorithms. + - `compute_provider.ec2.runner_binaries.s3.encryption.kms_master_key_id`: Optional KMS key identifier for the distribution bucket. The default is null, and its nullness must be known during planning because it controls the syncer KMS policy. The syncer receives KMS access, but runner roles do not derive `kms:Decrypt` from this field; grant runner roles decrypt access separately when using a CMK. + - `compute_provider.ec2.runner_binaries.s3.tags`: Additional tags for each distribution bucket. The default is `{}`; these merge after global `tags`. + - `compute_provider.ec2.runner_binaries.s3.versioning`: Distribution-bucket versioning state. The default is `Disabled`; valid values are `Disabled`, `Enabled`, and `Suspended`. After enabling versioning, Terraform cannot return the bucket to `Disabled`; use `Suspended` instead. + - `compute_provider.ec2.runner_binaries.s3.logging`: Optional access-logging settings for each distribution bucket. + - `compute_provider.ec2.runner_binaries.s3.logging.bucket`: Existing target bucket for access logs. The default is null, and its nullness must be known during planning because it controls the logging resource. + - `compute_provider.ec2.runner_binaries.s3.logging.prefix`: Optional access-log prefix. The default is null, which uses the distribution-bucket name when logging is enabled. A non-null prefix requires `logging.bucket`. + - `compute_provider.ec2.runner_binaries.syncer`: Component-specific settings for the shared runner-binary syncer Lambda. + - `compute_provider.ec2.runner_binaries.syncer.artifact`: Syncer Lambda artifact selection. Set at most one of `zip` or `s3`; when both are null, the packaged archive is used. + - `compute_provider.ec2.runner_binaries.syncer.artifact.zip`: Optional local path to the syncer Lambda archive. The default is null. + - `compute_provider.ec2.runner_binaries.syncer.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 and requires a non-null shared bucket and key. + - `compute_provider.ec2.runner_binaries.syncer.artifact.s3.key`: Object key of the syncer Lambda archive. Required when the `s3` wrapper is present. + - `compute_provider.ec2.runner_binaries.syncer.artifact.s3.object_version`: Optional object version of the syncer Lambda archive. The default is null. + - `compute_provider.ec2.runner_binaries.syncer.lambda`: Syncer Lambda sizing settings. Runtime, architecture, networking, role, tags, logging, and tracing come from their global experimental blocks. + - `compute_provider.ec2.runner_binaries.syncer.lambda.memory_size`: Memory allocated to the syncer Lambda in MB. The default is `256`. + - `compute_provider.ec2.runner_binaries.syncer.lambda.timeout`: Syncer Lambda timeout in seconds. The default is `300`. + - `compute_provider.ec2.runner_binaries.syncer.schedule`: EventBridge schedule settings for the syncer Lambda. + - `compute_provider.ec2.runner_binaries.syncer.schedule.expression`: EventBridge schedule expression. The default is `cron(27 * * * ? *)`. + - `compute_provider.ec2.runner_binaries.syncer.schedule.state`: EventBridge rule state. The default is `ENABLED`; valid values are `DISABLED`, `ENABLED`, and `ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS`. + + Each `experimental.multi_runner_config` entry supports the following nested fields: + + - `multi_runner_config[].tags`: Configuration-wide tags. These override global `experimental.tags`; narrower component and compute-provider tag maps take precedence for their resources. Flat `tags` are not merged into v2 queues or runner configurations. + - `multi_runner_config[].runner.os`: Runner operating system. + - `multi_runner_config[].runner.architecture`: Runner distribution architecture. + - `multi_runner_config[].runner.disable_default_labels`: Prevents GitHub default labels from being registered. + - `multi_runner_config[].runner.extra_labels`: Additional labels combined with `orchestration.webhook.matcherConfig.labelMatchers` for webhook runner configurations. Default self-hosted, operating-system, and architecture labels are also included unless `runner.disable_default_labels` is true. + - `multi_runner_config[].runner.group_name`: GitHub runner group used during registration. + - `multi_runner_config[].runner.name_prefix`: Prefix added to registered runner names. + - `multi_runner_config[].runner.run_as_root`: Runs the runner service as root when supported by the compute provider. + - `multi_runner_config[].runner.run_as`: Operating-system user used when `run_as_root` is false. + - `multi_runner_config[].runner.auto_update_disabled`: Disables the GitHub runner application's built-in updater. + - `multi_runner_config[].runner.tags`: Tags for common runner resources, currently the managed runner IAM role. These override entry-level `tags`. + - `multi_runner_config[].runner.hooks.job_started`: Script content installed as the runner job-started hook. + - `multi_runner_config[].runner.hooks.job_completed`: Script content installed as the runner job-completed hook. + - `multi_runner_config[].runner.iam.role`: Optional externally managed runner-role wrapper. When set, inherited managed policies and trust additions are suppressed. + - `multi_runner_config[].runner.iam.role.arn`: ARN of an externally managed runner role. When set, `runner-config` does not create or modify that role. + - `multi_runner_config[].runner.iam.managed_policy_arns`: Named managed-policy ARNs attached to the module-managed runner role. Keep this empty or null when the runner configuration selects an external `runner.iam.role`. + - `multi_runner_config[].runner.iam.additional_trust_policy_json`: Optional IAM policy document merged with the selected compute provider's default runner-role trust policy. Keep it null when the runner configuration selects an external `runner.iam.role`. + - `multi_runner_config[].runner.iam.path`: IAM path for the module-managed runner role. + - `multi_runner_config[].runner.iam.permissions_boundary`: Permissions-boundary ARN for the module-managed runner role. + - `multi_runner_config[].lambda`: Lambda runtime, architecture, networking, tags, and role substrate shared by orchestration and the runner-configuration SSM housekeeper. Scale function settings belong under `orchestration.webhook.lambda`. + - `multi_runner_config[].lambda.runtime`: Per-configuration runtime override for runner-config Lambda functions. + - `multi_runner_config[].lambda.architecture`: Per-configuration architecture override for runner-config Lambda functions. + - `multi_runner_config[].lambda.subnet_ids`: Per-configuration subnet override for runner-config Lambda functions. + - `multi_runner_config[].lambda.security_group_ids`: Per-configuration security-group override for runner-config Lambda functions. + - `multi_runner_config[].lambda.tags`: Per-configuration tags for control-plane Lambda functions. Component tags override this map. + - `multi_runner_config[].lambda.role.path`: Per-configuration IAM path for module-managed Lambda roles. Null inherits `experimental.lambda.role.path`, then `experimental.roles.path`. + - `multi_runner_config[].lambda.role.permissions_boundary`: Per-configuration permissions-boundary ARN for module-managed Lambda roles. Null inherits `experimental.lambda.role.permissions_boundary`, then `experimental.roles.permissions_boundary`. + - `multi_runner_config[].orchestration`: Demand-controller selection. Exactly one typed provider block must be non-null. Only `webhook` is supported today; additional providers can be added without moving the webhook contract. + - `multi_runner_config[].orchestration.webhook`: Selects the workflow-job webhook control plane, including its SQS build queue, scale-up, scheduled scale-down/pool, and optional job-retry resources. + - `multi_runner_config[].orchestration.webhook.runner.boot_time_in_minutes`: Expected runner boot duration used by webhook scale-down and pool controls. Null inherits `experimental.orchestration.webhook.runner.boot_time_in_minutes`. + - `multi_runner_config[].orchestration.webhook.runner.ephemeral`: Registers webhook-orchestrated runners in ephemeral mode. Null inherits `experimental.orchestration.webhook.runner.ephemeral`. + - `multi_runner_config[].orchestration.webhook.runner.jit_config_enabled`: Explicitly enables or disables just-in-time configuration. Null inherits the global webhook value; if both are null, behavior follows the resolved webhook `ephemeral` mode. + - `multi_runner_config[].orchestration.webhook.runner.maximum_count`: Maximum number of runners managed by the webhook orchestration provider for this configuration. Null inherits `experimental.orchestration.webhook.runner.maximum_count`. + - `multi_runner_config[].orchestration.webhook.github.organization_runners`: Registers runners at organization scope when true; otherwise repository-scoped registration is used. + - `multi_runner_config[].orchestration.webhook.matcherConfig.labelMatchers`: Groups of labels used to match webhook jobs to this configuration. + - `multi_runner_config[].orchestration.webhook.matcherConfig.exactMatch`: Deprecated one-way match. When true, every workflow-job label must appear in a configured label group, but that group may contain additional labels. + - `multi_runner_config[].orchestration.webhook.matcherConfig.bidirectionalLabelMatch`: Requires an exact two-way set match between workflow-job labels and a configured label group, with no extra or missing labels. + - `multi_runner_config[].orchestration.webhook.matcherConfig.priority`: Ordering used when multiple configurations match the same job. + - `multi_runner_config[].orchestration.webhook.matcherConfig.enableDynamicLabels`: Enables runtime interpretation of supported dynamic AWS labels. + - `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy`: Optional policy restricting values accepted from dynamic AWS labels. + - `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.blocked_keys`: Dynamic-label keys rejected for this runner configuration. The default is `[]`. + - `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys`: Per-key allow, deny, and maximum-value restrictions. The default is `{}`. + - `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys..allowed`: Values explicitly allowed for the dynamic-label key. The default is `[]`. + - `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys..denied`: Values explicitly denied for the dynamic-label key. The default is `[]`. + - `multi_runner_config[].orchestration.webhook.matcherConfig.awsDynamicLabelsPolicy.restricted_keys..max`: Optional maximum accepted value for the dynamic-label key. The default is null. + - `multi_runner_config[].orchestration.webhook.queue.delay_webhook_event`: Delay in seconds applied to webhook job messages. Null inherits the global queue default. + - `multi_runner_config[].orchestration.webhook.queue.job_queue_retention_in_seconds`: Build-queue message retention period in seconds. Null inherits the global queue default. + - `multi_runner_config[].orchestration.webhook.queue.visibility_timeout_seconds`: Build-queue visibility timeout. Null inherits the global queue default; the resolved value must be at least six times the resolved `orchestration.webhook.lambda.scale.up.timeout` so Lambda has enough time to retry throttled invocations. + - `multi_runner_config[].orchestration.webhook.queue.redrive_build_queue.enabled`: Creates and attaches a dead-letter queue for the build queue. A null wrapper or null leaf inherits the corresponding global value. + - `multi_runner_config[].orchestration.webhook.queue.redrive_build_queue.maxReceiveCount`: Number of receives before a build message moves to the dead-letter queue. A null wrapper or null leaf inherits the corresponding global value, and the resolved value must be greater than zero when redrive is enabled. + - `multi_runner_config[].orchestration.webhook.queue.tags`: Tags for configuration-owned queue resources. These merge after global queue tags and entry-level `tags`; component tags override this map. + - `multi_runner_config[].orchestration.webhook.lambda.scale.up.memory_size`: Memory allocated to the scale-up Lambda in MB. + - `multi_runner_config[].orchestration.webhook.lambda.scale.up.timeout`: Scale-up Lambda timeout in seconds. + - `multi_runner_config[].orchestration.webhook.lambda.scale.up.reserved_concurrent_executions`: Reserved concurrency for the scale-up Lambda. Use `-1` for unreserved concurrency. + - `multi_runner_config[].orchestration.webhook.lambda.scale.up.job_queued_check_enabled`: Enables the queued-job verification before scaling. Null inherits the global value; if both are null, behavior follows the resolved runner mode. + - `multi_runner_config[].orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size`: Maximum build-queue records delivered to one scale-up Lambda invocation. + - `multi_runner_config[].orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds`: Maximum batching window for build-queue records. + - `multi_runner_config[].orchestration.webhook.lambda.scale.up.tags`: Tags for scale-up resources. These override entry-level and shared Lambda, queue, and log-group tags within their resource scopes. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.memory_size`: Memory allocated to the scale-down Lambda in MB. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.timeout`: Scale-down Lambda timeout in seconds. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.schedule_expression`: EventBridge schedule expression that invokes scale-down. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.minimum_running_time_in_minutes`: Minimum runner age before scale-down may terminate it. Null inherits the global value; if both are null, the operating-system default is selected. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config`: Time-based desired idle-runner configurations. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].cron`: Cron expression identifying when the idle configuration applies. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].timeZone`: IANA time zone used to evaluate `cron`. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].idleCount`: Number of idle runners to retain during the matching period. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.idle_config[].evictionStrategy`: Selection strategy used when excess idle runners are removed. + - `multi_runner_config[].orchestration.webhook.lambda.scale.down.tags`: Tags for scale-down resources. These override entry-level and shared Lambda and log-group tags within their resource scopes. + - `multi_runner_config[].orchestration.webhook.lambda.pool.memory_size`: Memory allocated to the pool Lambda in MB. + - `multi_runner_config[].orchestration.webhook.lambda.pool.timeout`: Pool Lambda timeout in seconds. + - `multi_runner_config[].orchestration.webhook.lambda.pool.reserved_concurrent_executions`: Reserved concurrency for the pool Lambda. Use `-1` for unreserved concurrency. + - `multi_runner_config[].orchestration.webhook.lambda.pool.config`: Scheduled target pool sizes. An empty list disables the pool component. + - `multi_runner_config[].orchestration.webhook.lambda.pool.config[].schedule_expression`: Scheduler expression that activates the target size. + - `multi_runner_config[].orchestration.webhook.lambda.pool.config[].schedule_expression_timezone`: Optional IANA time zone used to evaluate the schedule. + - `multi_runner_config[].orchestration.webhook.lambda.pool.config[].size`: Desired number of runners for the schedule. + - `multi_runner_config[].orchestration.webhook.lambda.pool.include_busy_runners`: Includes busy runners when reconciling scheduled pool capacity. + - `multi_runner_config[].orchestration.webhook.lambda.pool.runner_owner`: Optional GitHub organization or repository owner used when creating pooled runners. + - `multi_runner_config[].orchestration.webhook.lambda.pool.tags`: Tags for pool resources. These override entry-level and shared Lambda and log-group tags within their resource scopes. + - `multi_runner_config[].orchestration.webhook.job_retry.enabled`: Creates the retry queue, Lambda function, event-source mapping, and related IAM resources. + - `multi_runner_config[].orchestration.webhook.job_retry.delay_in_seconds`: Initial delay before a queued-job retry check. + - `multi_runner_config[].orchestration.webhook.job_retry.delay_backoff`: Multiplier applied to the delay after each unsuccessful check. + - `multi_runner_config[].orchestration.webhook.job_retry.max_attempts`: Maximum retry-check attempts before the message is no longer republished. + - `multi_runner_config[].orchestration.webhook.job_retry.tags`: Tags for job-retry resources. These override entry-level and shared Lambda, queue, and log-group tags within their resource scopes. + - `multi_runner_config[].orchestration.webhook.job_retry.lambda.memory_size`: Memory allocated to the job-retry Lambda in MB. + - `multi_runner_config[].orchestration.webhook.job_retry.lambda.reserved_concurrent_executions`: Reserved concurrency for the job-retry Lambda. Use `-1` for unreserved concurrency. + - `multi_runner_config[].orchestration.webhook.job_retry.lambda.timeout`: Job-retry Lambda timeout in seconds and visibility timeout for its retry queue. + - `multi_runner_config[].ssm.paths.root`: Base Parameter Store root for this runner configuration. The configuration key is always appended to preserve configuration isolation. The omitted global root derives `/github-action-runners/`. + - `multi_runner_config[].ssm.paths.tokens`: Path segment below the runner-configuration root used for runner registration tokens and just-in-time configuration. + - `multi_runner_config[].ssm.paths.config`: Path segment below the runner-configuration root used for persistent runner configuration. + - `multi_runner_config[].ssm.tags`: Shared tags for runner-configuration-owned SSM resources. These override entry-level `tags`. + - `multi_runner_config[].ssm.parameters.tags`: Tags for Terraform-managed and runtime-created runner configuration parameters. These override `ssm.tags`. + - `multi_runner_config[].ssm.housekeeper.schedule_expression`: EventBridge schedule expression that invokes the runner-configuration SSM housekeeper. + - `multi_runner_config[].ssm.housekeeper.state`: EventBridge rule state for the runner-configuration SSM housekeeper. Valid values are `DISABLED`, `ENABLED`, and `ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS`. + - `multi_runner_config[].ssm.housekeeper.tags`: Tags for SSM housekeeper resources. These override entry-level, shared Lambda, shared log, and `ssm.tags` values. + - `multi_runner_config[].ssm.housekeeper.lambda.artifact`: Per-configuration SSM-housekeeper artifact selection. A selected `zip` or `s3` source overrides the global `ssm.housekeeper.lambda.artifact`; when neither level selects a source, runner-config uses its packaged runner control-plane archive. + - `multi_runner_config[].ssm.housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive. + - `multi_runner_config[].ssm.housekeeper.lambda.artifact.s3`: Optional key and object version in the shared `lambda.artifact.s3.bucket`. Wrapper presence selects S3 for this SSM housekeeper, must be known during planning, and requires a non-null shared bucket and key. + - `multi_runner_config[].ssm.housekeeper.lambda.artifact.s3.key`: Object key of this runner configuration's SSM-housekeeper Lambda archive. + - `multi_runner_config[].ssm.housekeeper.lambda.artifact.s3.object_version`: Optional object version of this runner configuration's SSM-housekeeper Lambda archive. + - `multi_runner_config[].ssm.housekeeper.lambda.memory_size`: Memory allocated to the SSM housekeeper Lambda in MB. + - `multi_runner_config[].ssm.housekeeper.lambda.timeout`: SSM housekeeper Lambda timeout in seconds. + - `multi_runner_config[].ssm.housekeeper.config.tokenPath`: Optional cleanup path. A global value is shared by every runner configuration, so omit it to derive each configuration's isolated token path. + - `multi_runner_config[].ssm.housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed. + - `multi_runner_config[].ssm.housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true. + - `multi_runner_config[].observability.logs.level`: Application log level for runner-configuration control-plane functions. + - `multi_runner_config[].observability.logs.retention_in_days`: CloudWatch Logs retention period for runner-configuration resources. + - `multi_runner_config[].observability.logs.kms_key_id`: Optional KMS key ID or ARN used to encrypt runner-configuration CloudWatch log groups. + - `multi_runner_config[].observability.logs.class`: CloudWatch log-group class for runner-configuration resources. + - `multi_runner_config[].observability.logs.tags`: Shared tags for runner-configuration CloudWatch log groups. Component tags override this map. + - `multi_runner_config[].observability.tracing.mode`: Optional Lambda tracing mode. Its nullness must be known during planning because it controls X-Ray IAM and tracing blocks. + - `multi_runner_config[].observability.tracing.capture_http_requests`: Enables HTTP request capture in the tracing helper. + - `multi_runner_config[].observability.tracing.capture_error`: Enables error capture in the tracing helper. + - `multi_runner_config[].observability.metrics.enable`: Enables module-emitted metrics. + - `multi_runner_config[].observability.metrics.namespace`: CloudWatch namespace used for emitted metrics. + - `multi_runner_config[].observability.metrics.metric.enable_github_app_rate_limit`: Emits GitHub App rate-limit metrics. + - `multi_runner_config[].observability.metrics.metric.enable_job_retry`: Emits job-retry metrics. + - `multi_runner_config[].compute_provider`: Typed compute-provider blocks. Exactly one block must be non-null, and the populated block selects the provider. Its presence must be known during planning; values inside it may remain unknown until apply. + - `multi_runner_config[].compute_provider.ec2`: EC2-specific configuration. + - `multi_runner_config[].compute_provider.ec2.metadata_options.instance_metadata_tags`: Exposes instance tags through Instance Metadata Service when enabled. + - `multi_runner_config[].compute_provider.ec2.metadata_options.http_endpoint`: Enables or disables the Instance Metadata Service endpoint. + - `multi_runner_config[].compute_provider.ec2.metadata_options.http_tokens`: Controls whether IMDSv2 session tokens are optional or required. + - `multi_runner_config[].compute_provider.ec2.metadata_options.http_put_response_hop_limit`: Network hop limit for Instance Metadata Service token responses. + - `multi_runner_config[].compute_provider.ec2.ami.filter`: EC2 AMI filters combined with the default AMI-name filter. + - `multi_runner_config[].compute_provider.ec2.ami.owners`: AWS account IDs or aliases allowed to own the selected AMI. + - `multi_runner_config[].compute_provider.ec2.ami.id_ssm_parameter`: Optional externally managed SSM parameter containing the AMI ID. The wrapper's presence selects external ownership at plan time. + - `multi_runner_config[].compute_provider.ec2.ami.id_ssm_parameter.arn`: ARN of the externally managed SSM parameter. The ARN may be unknown until apply. + - `multi_runner_config[].compute_provider.ec2.ami.kms_key`: Optional KMS key required to launch encrypted AMIs or snapshots. The wrapper's presence selects the KMS policy at plan time. + - `multi_runner_config[].compute_provider.ec2.ami.kms_key.arn`: ARN of the KMS key. The ARN may be unknown until apply. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings`: EBS mappings added to the runner launch template. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].delete_on_termination`: Deletes the volume when its runner instance terminates. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].device_name`: Device name exposed to the runner instance. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].encrypted`: Enables EBS encryption. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].iops`: Provisioned IOPS for supported volume types. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].kms_key_id`: KMS key ID or ARN used to encrypt the volume. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].snapshot_id`: Snapshot used to initialize the volume. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].throughput`: Provisioned throughput for supported volume types. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].volume_initialization_rate`: Fixed initialization rate in MiB/s for supported snapshot-backed volumes. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].volume_size`: Volume size in GiB. + - `multi_runner_config[].compute_provider.ec2.block_device_mappings[].volume_type`: EBS volume type. + - `multi_runner_config[].compute_provider.ec2.create_service_linked_role_spot`: Allows scale-up to create the EC2 Spot service-linked role. + - `multi_runner_config[].compute_provider.ec2.credit_specification`: CPU credit mode for burstable instance types. + - `multi_runner_config[].compute_provider.ec2.ebs_optimized`: Requests EBS-optimized runner instances. + - `multi_runner_config[].compute_provider.ec2.cloudwatch_agent.enabled`: Installs and configures the CloudWatch agent through the default bootstrap flow. + - `multi_runner_config[].compute_provider.ec2.cloudwatch_agent.config`: Optional complete CloudWatch agent configuration. + - `multi_runner_config[].compute_provider.ec2.binaries_syncer.enabled`: Enables use of the shared synchronized runner distribution from S3. Null inherits `experimental.compute_provider.ec2.runner_binaries.enabled`. + - `multi_runner_config[].compute_provider.ec2.detailed_monitoring_enabled`: Enables detailed EC2 monitoring for runner instances. + - `multi_runner_config[].compute_provider.ec2.ssm_enabled`: Attaches runner permissions and policies required for AWS Systems Manager access. + - `multi_runner_config[].compute_provider.ec2.user_data.enabled`: Enables launch-template user data. + - `multi_runner_config[].compute_provider.ec2.user_data.template`: Optional path to a custom user-data template. + - `multi_runner_config[].compute_provider.ec2.user_data.content`: Optional complete user-data content used instead of rendering a template. + - `multi_runner_config[].compute_provider.ec2.user_data.pre_install`: Script content inserted before runner installation in the default template. + - `multi_runner_config[].compute_provider.ec2.user_data.post_install`: Script content inserted after runner installation in the default template. + - `multi_runner_config[].compute_provider.ec2.user_data.debug_logging_enabled`: Enables verbose user-data tracing, which can expose secrets in logs. + - `multi_runner_config[].compute_provider.ec2.instance_allocation_strategy`: EC2 Fleet allocation strategy used to select capacity. + - `multi_runner_config[].compute_provider.ec2.instance_max_spot_price`: Optional maximum hourly Spot price. + - `multi_runner_config[].compute_provider.ec2.instance_target_capacity_type`: Primary capacity type, either `spot` or `on-demand`. + - `multi_runner_config[].compute_provider.ec2.instance_type_priorities`: Optional numeric priorities keyed by instance type. + - `multi_runner_config[].compute_provider.ec2.instance_types`: EC2 instance types available to the scale-up and pool functions. + - `multi_runner_config[].compute_provider.ec2.additional_security_group_ids`: Existing security groups attached to runner instances. + - `multi_runner_config[].compute_provider.ec2.managed_security_group_enabled`: Creates the module-managed runner security group when true. + - `multi_runner_config[].compute_provider.ec2.egress_rules`: Runner security-group egress rules. Null inherits `experimental.compute_provider.ec2.egress_rules`, whose default is the built-in IPv4/IPv6 allow-all rule. Flat `runner_egress_rules` is not inherited by v2. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].cidr_blocks`: IPv4 CIDR destinations for the runner-configuration egress rule. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations for the runner-configuration egress rule. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].prefix_list_ids`: Prefix-list destinations for the runner-configuration egress rule. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].from_port`: Start of the runner-configuration egress rule port range. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].protocol`: Runner-configuration egress rule protocol; `-1` allows every protocol. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].security_groups`: Destination security-group IDs for the runner-configuration egress rule. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].self`: Allows traffic to the managed security group itself when true. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].to_port`: End of the runner-configuration egress rule port range. + - `multi_runner_config[].compute_provider.ec2.egress_rules[].description`: Optional runner-configuration egress rule description. + - `multi_runner_config[].compute_provider.ec2.instance_profile_path`: IAM path for the module-managed EC2 instance profile. + - `multi_runner_config[].compute_provider.ec2.key_name`: Optional EC2 key-pair name for runner instances. + - `multi_runner_config[].compute_provider.ec2.associate_public_ipv4_address`: Associates a public IPv4 address with runner instances. + - `multi_runner_config[].compute_provider.ec2.instance_profile.name`: Name of an externally managed instance profile. Setting it also requires `runner.iam.role`. + - `multi_runner_config[].compute_provider.ec2.enable_on_demand_failover_for_errors`: EC2 error codes that trigger an on-demand fallback after a Spot launch failure. + - `multi_runner_config[].compute_provider.ec2.scale_errors`: EC2 error codes treated as retryable scale-up failures. + - `multi_runner_config[].compute_provider.ec2.subnet_ids`: Subnets from which scale-up may launch runners. A null configuration value inherits the experimental global value. + - `multi_runner_config[].compute_provider.ec2.vpc_id`: VPC in which runner networking resources are created. A null configuration value inherits the experimental global value. + - `multi_runner_config[].compute_provider.ec2.cpu_options.core_count`: Number of CPU cores exposed to the runner instance. + - `multi_runner_config[].compute_provider.ec2.cpu_options.threads_per_core`: Number of hardware threads exposed per CPU core. + - `multi_runner_config[].compute_provider.ec2.cpu_options.amd_sev_snp`: Enables or disables AMD SEV-SNP on supported instance types. + - `multi_runner_config[].compute_provider.ec2.cpu_options.nested_virtualization`: Enables or disables nested virtualization on supported instance types. + - `multi_runner_config[].compute_provider.ec2.placement.affinity`: Host affinity setting. + - `multi_runner_config[].compute_provider.ec2.placement.availability_zone`: Availability Zone in which the instance is placed. + - `multi_runner_config[].compute_provider.ec2.placement.group_id`: Placement-group ID. + - `multi_runner_config[].compute_provider.ec2.placement.group_name`: Placement-group name. + - `multi_runner_config[].compute_provider.ec2.placement.host_id`: Dedicated Host ID. + - `multi_runner_config[].compute_provider.ec2.placement.host_resource_group_arn`: ARN of the host resource group used for placement. + - `multi_runner_config[].compute_provider.ec2.placement.spread_domain`: Spread-domain placement value. + - `multi_runner_config[].compute_provider.ec2.placement.tenancy`: Instance tenancy. + - `multi_runner_config[].compute_provider.ec2.placement.partition_number`: Placement-group partition number. + - `multi_runner_config[].compute_provider.ec2.license_specifications[].license_configuration_arn`: ARN of a License Manager license configuration. + - `multi_runner_config[].compute_provider.ec2.use_dedicated_host`: Enables the dedicated-host launch path required for macOS runners. + - `multi_runner_config[].compute_provider.ec2.log_files`: Optional log files collected by the CloudWatch agent. + - `multi_runner_config[].compute_provider.ec2.log_files[].log_group_name`: CloudWatch log-group name before optional prefixing. + - `multi_runner_config[].compute_provider.ec2.log_files[].prefix_log_group`: Prefixes the log-group name with the runner configuration path when true. + - `multi_runner_config[].compute_provider.ec2.log_files[].file_path`: File or glob read by the CloudWatch agent. + - `multi_runner_config[].compute_provider.ec2.log_files[].log_stream_name`: CloudWatch log-stream name template. + - `multi_runner_config[].compute_provider.ec2.log_files[].log_class`: CloudWatch log-group class for the collected file. + - `multi_runner_config[].compute_provider.ec2.tags`: Tags for runtime EC2 instances, volumes, network interfaces, and eligible Spot requests. These override entry-level tags and the generated runner `Name`; provider-required bootstrap tags take final precedence. + EOT + + type = object({ + tags = optional(map(string), {}) + + roles = optional(object({ + path = optional(string, null) + permissions_boundary = optional(string, null) + }), {}) + + runner = optional(object({ + os = optional(string, null) + architecture = optional(string, null) + disable_default_labels = optional(bool, false) + extra_labels = optional(list(string), []) + group_name = optional(string, "Default") + name_prefix = optional(string, "") + run_as_root = optional(bool, false) + run_as = optional(string, "ec2-user") + auto_update_disabled = optional(bool, false) + tags = optional(map(string), {}) + hooks = optional(object({ + job_started = optional(string, "") + job_completed = optional(string, "") + }), {}) + iam = optional(object({ + role = optional(object({ + arn = string + }), null) + managed_policy_arns = optional(map(string), {}) + additional_trust_policy_json = optional(string, null) + path = optional(string, null) + permissions_boundary = optional(string, null) + }), {}) + }), {}) + + github = optional(object({ + app = optional(object({ + key_base64 = optional(string) + key_base64_ssm = optional(object({ + arn = string + name = string + })) + id = optional(string) + id_ssm = optional(object({ + arn = string + name = string + })) + webhook_secret = optional(string) + webhook_secret_ssm = optional(object({ + arn = string + name = string + })) + }), null) + additional_apps = optional(list(object({ + key_base64 = optional(string) + key_base64_ssm = optional(object({ arn = string, name = string })) + id = optional(string) + id_ssm = optional(object({ arn = string, name = string })) + installation_id = optional(string) + installation_id_ssm = optional(object({ arn = string, name = string })) + })), []) + enterprise_server = optional(object({ + url = optional(string, null) + ssl_verify = optional(bool, true) + }), {}) + user_agent = optional(string, "github-aws-runners") + }), {}) + + lambda = optional(object({ + artifact = optional(object({ + s3 = optional(object({ + bucket = optional(string, null) + }), {}) + }), {}) + runtime = optional(string, "nodejs24.x") + architecture = optional(string, "arm64") + principals = optional(list(object({ + type = string + identifiers = list(string) + })), []) + subnet_ids = optional(list(string), []) + security_group_ids = optional(list(string), []) + tags = optional(map(string), {}) + role = optional(object({ + path = optional(string, null) + permissions_boundary = optional(string, null) + }), {}) + }), {}) + + orchestration = optional(object({ + webhook = optional(object({ + queue_selection_strategy = optional(string, "first") + eventbridge = optional(object({ + enable = optional(bool, true) + accept_events = optional(list(string), []) + }), {}) + matcher_config_parameter_store_tier = optional(string, "Standard") + runner = optional(object({ + boot_time_in_minutes = optional(number, 5) + ephemeral = optional(bool, false) + jit_config_enabled = optional(bool, null) + maximum_count = optional(number, null) + }), {}) + + github = optional(object({ + repository_white_list = optional(list(string), []) + }), {}) + + lambda = optional(object({ + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + scale = optional(object({ + up = optional(object({ + memory_size = optional(number, 512) + timeout = optional(number, 30) + reserved_concurrent_executions = optional(number, 1) + job_queued_check_enabled = optional(bool, null) + event_source_mapping = optional(object({ + batch_size = optional(number, 10) + maximum_batching_window_in_seconds = optional(number, 0) + }), {}) + tags = optional(map(string), {}) + }), {}) + down = optional(object({ + memory_size = optional(number, 512) + timeout = optional(number, 60) + schedule_expression = optional(string, "cron(*/5 * * * ? *)") + minimum_running_time_in_minutes = optional(number, null) + idle_config = optional(list(object({ + cron = string + timeZone = string + idleCount = number + evictionStrategy = optional(string, "oldest_first") + })), []) + tags = optional(map(string), {}) + }), {}) + }), {}) + webhook = optional(object({ + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + api_gateway_access_log_settings = optional(object({ + destination_arn = string + format = string + }), null) + memory_size = optional(number, 256) + timeout = optional(number, 10) + tags = optional(map(string), {}) + }), {}) + pool = optional(object({ + memory_size = optional(number, 512) + timeout = optional(number, 60) + reserved_concurrent_executions = optional(number, 1) + config = optional(list(object({ + schedule_expression = string + schedule_expression_timezone = optional(string) + size = number + })), []) + include_busy_runners = optional(bool, false) + runner_owner = optional(string, null) + tags = optional(map(string), {}) + }), {}) + }), {}) + + queue = optional(object({ + delay_webhook_event = optional(number, 30) + job_queue_retention_in_seconds = optional(number, 86400) + visibility_timeout_seconds = optional(number, 180) + redrive_build_queue = optional(object({ + enabled = optional(bool, false) + maxReceiveCount = optional(number, null) + }), { + enabled = false + maxReceiveCount = null + }) + tags = optional(map(string), {}) + encryption = optional(object({ + kms_data_key_reuse_period_seconds = number + kms_master_key_id = string + sqs_managed_sse_enabled = bool + }), { + kms_data_key_reuse_period_seconds = null + kms_master_key_id = null + sqs_managed_sse_enabled = true + }) + }), {}) + }), {}) + }), {}) + + ssm = optional(object({ + paths = optional(object({ + root = optional(string, null) + app = optional(string, "app") + webhook = optional(string, "webhook") + tokens = optional(string, "runners/tokens") + config = optional(string, "runners/config") + }), {}) + kms_key_id = optional(string, null) + tags = optional(map(string), {}) + parameters = optional(object({ + tags = optional(map(string), {}) + }), {}) + housekeeper = optional(object({ + schedule_expression = optional(string, "rate(1 day)") + state = optional(string, "ENABLED") + tags = optional(map(string), {}) + lambda = optional(object({ + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + memory_size = optional(number, 512) + timeout = optional(number, 60) + }), {}) + config = optional(object({ + tokenPath = optional(string, null) + minimumDaysOld = optional(number, 1) + dryRun = optional(bool, false) + }), {}) + }), {}) + }), {}) + + observability = optional(object({ + logs = optional(object({ + level = optional(string, "info") + retention_in_days = optional(number, 180) + kms_key_id = optional(string, null) + class = optional(string, "STANDARD") + tags = optional(map(string), {}) + }), {}) + tracing = optional(object({ + mode = optional(string, null) + capture_http_requests = optional(bool, false) + capture_error = optional(bool, false) + }), {}) + metrics = optional(object({ + enable = optional(bool, false) + namespace = optional(string, "GitHub Runners") + metric = optional(object({ + enable_github_app_rate_limit = optional(bool, true) + enable_job_retry = optional(bool, true) + enable_spot_termination = optional(bool, true) + enable_spot_termination_warning = optional(bool, true) + }), {}) + }), {}) + }), {}) + + compute_provider = optional(object({ + ec2 = optional(object({ + vpc_id = optional(string, null) + subnet_ids = optional(list(string), null) + managed_security_group_enabled = optional(bool, true) + egress_rules = optional(list(object({ + cidr_blocks = list(string) + ipv6_cidr_blocks = list(string) + prefix_list_ids = list(string) + from_port = number + protocol = string + security_groups = list(string) + self = bool + to_port = number + description = string + })), [{ + cidr_blocks = ["0.0.0.0/0"] + ipv6_cidr_blocks = ["::/0"] + prefix_list_ids = null + from_port = 0 + protocol = "-1" + security_groups = null + self = null + to_port = 0 + description = null + }]) + additional_security_group_ids = optional(list(string), []) + cloudwatch_agent = optional(object({ + config = optional(string, null) + }), {}) + instance_profile_path = optional(string, null) + key_name = optional(string, null) + associate_public_ipv4_address = optional(bool, false) + tags = optional(map(string), {}) + ami = optional(object({ + housekeeper = optional(object({ + enabled = optional(bool, false) + cleanup_config = optional(object({ + maxItems = optional(number) + minimumDaysOld = optional(number) + amiFilters = optional(list(object({ + Name = string + Values = list(string) + }))) + launchTemplateNames = optional(list(string)) + ssmParameterNames = optional(list(string)) + dryRun = optional(bool) + }), {}) + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + lambda = optional(object({ + memory_size = optional(number, 256) + timeout = optional(number, 300) + }), {}) + schedule = optional(object({ + expression = optional(string, "cron(11 7 * * ? *)") + }), {}) + }), {}) + }), {}) + instance_termination_watcher = optional(object({ + enabled = optional(bool, false) + features = optional(object({ + enable_spot_termination_handler = optional(bool, true) + enable_spot_termination_notification_watcher = optional(bool, true) + }), {}) + enable_runner_deregistration = optional(bool, true) + environment_variables = optional(map(string), {}) + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + lambda = optional(object({ + memory_size = optional(number, null) + timeout = optional(number, null) + }), {}) + }), {}) + runner_binaries = optional(object({ + enabled = optional(bool, true) + s3 = optional(object({ + encryption = optional(object({ + enabled = optional(bool, true) + bucket_key_enabled = optional(bool, null) + sse_algorithm = optional(string, "AES256") + kms_master_key_id = optional(string, null) + }), {}) + tags = optional(map(string), {}) + versioning = optional(string, "Disabled") + logging = optional(object({ + bucket = optional(string, null) + prefix = optional(string, null) + }), {}) + }), {}) + syncer = optional(object({ + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + lambda = optional(object({ + memory_size = optional(number, 256) + timeout = optional(number, 300) + }), {}) + schedule = optional(object({ + expression = optional(string, "cron(27 * * * ? *)") + state = optional(string, "ENABLED") + }), {}) + }), {}) + }), {}) + }), {}) + }), {}) + + multi_runner_config = optional(map(object({ + tags = optional(map(string), {}) + + runner = optional(object({ + os = optional(string, null) + architecture = optional(string, null) + disable_default_labels = optional(bool, null) + extra_labels = optional(list(string), null) + group_name = optional(string, null) + name_prefix = optional(string, null) + run_as_root = optional(bool, null) + run_as = optional(string, null) + auto_update_disabled = optional(bool, null) + tags = optional(map(string), {}) + hooks = optional(object({ + job_started = optional(string, null) + job_completed = optional(string, null) + }), {}) + iam = optional(object({ + role = optional(object({ + arn = string + }), null) + managed_policy_arns = optional(map(string), null) + additional_trust_policy_json = optional(string, null) + path = optional(string, null) + permissions_boundary = optional(string, null) + }), {}) + }), {}) + + lambda = optional(object({ + runtime = optional(string, null) + architecture = optional(string, null) + subnet_ids = optional(list(string), null) + security_group_ids = optional(list(string), null) + tags = optional(map(string), {}) + role = optional(object({ + path = optional(string, null) + permissions_boundary = optional(string, null) + }), {}) + }), {}) + + orchestration = object({ + webhook = optional(object({ + runner = optional(object({ + boot_time_in_minutes = optional(number, null) + ephemeral = optional(bool, null) + jit_config_enabled = optional(bool, null) + maximum_count = optional(number, null) + }), {}) + + github = optional(object({ + organization_runners = optional(bool, false) + }), {}) + + matcherConfig = object({ + labelMatchers = list(list(string)) + exactMatch = optional(bool, false) + bidirectionalLabelMatch = optional(bool, false) + priority = optional(number, 999) + enableDynamicLabels = optional(bool, false) + awsDynamicLabelsPolicy = optional(object({ + blocked_keys = optional(list(string), []) + restricted_keys = optional(map(object({ + allowed = optional(list(string), []) + denied = optional(list(string), []) + max = optional(string, null) + })), {}) + }), null) + }) + + queue = optional(object({ + delay_webhook_event = optional(number, null) + job_queue_retention_in_seconds = optional(number, null) + visibility_timeout_seconds = optional(number, null) + redrive_build_queue = optional(object({ + enabled = optional(bool, null) + maxReceiveCount = optional(number, null) + }), null) + tags = optional(map(string), {}) + }), {}) + + lambda = optional(object({ + scale = optional(object({ + up = optional(object({ + memory_size = optional(number, null) + timeout = optional(number, null) + reserved_concurrent_executions = optional(number, null) + job_queued_check_enabled = optional(bool, null) + event_source_mapping = optional(object({ + batch_size = optional(number, null) + maximum_batching_window_in_seconds = optional(number, null) + }), {}) + tags = optional(map(string), {}) + }), {}) + down = optional(object({ + memory_size = optional(number, null) + timeout = optional(number, null) + schedule_expression = optional(string, null) + minimum_running_time_in_minutes = optional(number, null) + idle_config = optional(list(object({ + cron = string + timeZone = string + idleCount = number + evictionStrategy = optional(string, "oldest_first") + })), null) + tags = optional(map(string), {}) + }), {}) + }), {}) + pool = optional(object({ + memory_size = optional(number, null) + timeout = optional(number, null) + reserved_concurrent_executions = optional(number, null) + config = optional(list(object({ + schedule_expression = string + schedule_expression_timezone = optional(string) + size = number + })), null) + include_busy_runners = optional(bool, null) + runner_owner = optional(string, null) + tags = optional(map(string), {}) + }), {}) + }), {}) + + job_retry = optional(object({ + enabled = optional(bool, false) + delay_in_seconds = optional(number, 300) + delay_backoff = optional(number, 2) + max_attempts = optional(number, 1) + tags = optional(map(string), {}) + lambda = optional(object({ + memory_size = optional(number, 256) + reserved_concurrent_executions = optional(number, 1) + timeout = optional(number, 30) + }), {}) + }), {}) + + }), null) + + }) + + ssm = optional(object({ + paths = optional(object({ + root = optional(string, null) + tokens = optional(string, null) + config = optional(string, null) + }), {}) + tags = optional(map(string), {}) + parameters = optional(object({ + tags = optional(map(string), {}) + }), {}) + housekeeper = optional(object({ + schedule_expression = optional(string, null) + state = optional(string, null) + tags = optional(map(string), {}) + lambda = optional(object({ + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + memory_size = optional(number, null) + timeout = optional(number, null) + }), {}) + config = optional(object({ + tokenPath = optional(string, null) + minimumDaysOld = optional(number, null) + dryRun = optional(bool, null) + }), {}) + }), {}) + }), {}) + + observability = optional(object({ + logs = optional(object({ + level = optional(string, null) + retention_in_days = optional(number, null) + kms_key_id = optional(string, null) + class = optional(string, null) + tags = optional(map(string), {}) + }), {}) + tracing = optional(object({ + mode = optional(string, null) + capture_http_requests = optional(bool, null) + capture_error = optional(bool, null) + }), {}) + metrics = optional(object({ + enable = optional(bool, null) + namespace = optional(string, null) + metric = optional(object({ + enable_github_app_rate_limit = optional(bool, null) + enable_job_retry = optional(bool, null) + }), {}) + }), {}) + }), {}) + + compute_provider = object({ + ec2 = optional(object({ + metadata_options = optional(object({ + instance_metadata_tags = optional(string, "enabled") + http_endpoint = optional(string, "enabled") + http_tokens = optional(string, "required") + http_put_response_hop_limit = optional(number, 1) + }), {}) + ami = optional(object({ + filter = optional(map(list(string)), { state = ["available"] }) + owners = optional(list(string), ["amazon"]) + id_ssm_parameter = optional(object({ + arn = string + }), null) + kms_key = optional(object({ + arn = string + }), null) + }), null) + block_device_mappings = optional(list(object({ + delete_on_termination = optional(bool, true) + device_name = optional(string, "/dev/xvda") + encrypted = optional(bool, true) + iops = optional(number) + kms_key_id = optional(string) + snapshot_id = optional(string) + throughput = optional(number) + volume_initialization_rate = optional(number) + volume_size = number + volume_type = optional(string, "gp3") + })), [{ + volume_size = 30 + }]) + create_service_linked_role_spot = optional(bool, false) + credit_specification = optional(string, null) + ebs_optimized = optional(bool, false) + cloudwatch_agent = optional(object({ + enabled = optional(bool, true) + config = optional(string, null) + }), {}) + binaries_syncer = optional(object({ + enabled = optional(bool, null) + }), {}) + detailed_monitoring_enabled = optional(bool, false) + ssm_enabled = optional(bool, false) + user_data = optional(object({ + enabled = optional(bool, true) + template = optional(string, null) + content = optional(string, null) + pre_install = optional(string, "") + post_install = optional(string, "") + debug_logging_enabled = optional(bool, false) + }), {}) + instance_allocation_strategy = optional(string, "lowest-price") + instance_max_spot_price = optional(string, null) + instance_target_capacity_type = optional(string, "spot") + instance_type_priorities = optional(map(number), null) + instance_types = list(string) + additional_security_group_ids = optional(list(string), null) + managed_security_group_enabled = optional(bool, null) + egress_rules = optional(list(object({ + cidr_blocks = list(string) + ipv6_cidr_blocks = list(string) + prefix_list_ids = list(string) + from_port = number + protocol = string + security_groups = list(string) + self = bool + to_port = number + description = string + })), null) + instance_profile_path = optional(string, null) + key_name = optional(string, null) + associate_public_ipv4_address = optional(bool, null) + instance_profile = optional(object({ + name = string + }), null) + enable_on_demand_failover_for_errors = optional(list(string), []) + scale_errors = optional(list(string), [ + "UnfulfillableCapacity", + "MaxSpotInstanceCountExceeded", + "TargetCapacityLimitExceededException", + "RequestLimitExceeded", + "ResourceLimitExceeded", + "MaxSpotInstanceCountExceeded", + "MaxSpotFleetRequestCountExceeded", + "InsufficientInstanceCapacity", + "InsufficientCapacityOnHost", + ]) + subnet_ids = optional(list(string), null) + vpc_id = optional(string, null) + cpu_options = optional(object({ + core_count = optional(number) + threads_per_core = optional(number) + amd_sev_snp = optional(string) + nested_virtualization = optional(string) + }), null) + placement = optional(object({ + affinity = optional(string) + availability_zone = optional(string) + group_id = optional(string) + group_name = optional(string) + host_id = optional(string) + host_resource_group_arn = optional(string) + spread_domain = optional(string) + tenancy = optional(string) + partition_number = optional(number) + }), null) + license_specifications = optional(list(object({ + license_configuration_arn = string + })), []) + use_dedicated_host = optional(bool, false) + log_files = optional(list(object({ + log_group_name = string + prefix_log_group = bool + file_path = string + log_stream_name = string + log_class = optional(string, "STANDARD") + })), null) + tags = optional(map(string), {}) + }), null) + }) + + })), {}) + }) + default = {} +} diff --git a/modules/multi-runner/variables.tf b/modules/multi-runner/variables.tf index a47cd2a83c..09855ed736 100644 --- a/modules/multi-runner/variables.tf +++ b/modules/multi-runner/variables.tf @@ -23,19 +23,9 @@ variable "github_app" { name = string })) }) - - validation { - condition = (var.github_app.key_base64 != null || var.github_app.key_base64_ssm != null) && (var.github_app.id != null || var.github_app.id_ssm != null) && (var.github_app.webhook_secret != null || var.github_app.webhook_secret_ssm != null) - error_message = < v + if v.orchestration.webhook != null + } + + runner_matcher_config = { + for k, v in local.webhook_runner_config : k => { + id = aws_sqs_queue.queued_builds[k].id + arn = aws_sqs_queue.queued_builds[k].arn + computeProvider = local.compute_provider_types[k] + matcherConfig = v.orchestration.webhook.matcherConfig + } + } +} + module "webhook" { source = "../webhook" prefix = var.prefix - tags = local.tags - kms_key_arn = var.kms_key_arn - eventbridge = var.eventbridge - runner_matcher_config = local.runner_config - matcher_config_parameter_store_tier = var.matcher_config_parameter_store_tier + tags = merge(local.translated_experimental.tags, { "ghr:environment" = var.prefix }) + kms_key_arn = local.translated_experimental.ssm.kms_key_id + eventbridge = local.translated_experimental.orchestration.webhook.eventbridge + runner_matcher_config = local.runner_matcher_config + matcher_config_parameter_store_tier = local.translated_experimental.orchestration.webhook.matcher_config_parameter_store_tier ssm_paths = { - root = local.ssm_root_path - webhook = var.ssm_paths.webhook + root = trimsuffix(coalesce(local.translated_experimental.ssm.paths.root, "/github-action-runners/${var.prefix}"), "/") + webhook = local.translated_experimental.ssm.paths.webhook } github_app_parameters = { webhook_secret = local.github_app_parameters.webhook_secret } - lambda_s3_bucket = var.lambda_s3_bucket - webhook_lambda_s3_key = var.webhook_lambda_s3_key - webhook_lambda_s3_object_version = var.webhook_lambda_s3_object_version - webhook_lambda_apigateway_access_log_settings = var.webhook_lambda_apigateway_access_log_settings - lambda_runtime = var.lambda_runtime - lambda_architecture = var.lambda_architecture - lambda_zip = var.webhook_lambda_zip - lambda_timeout = var.webhook_lambda_timeout - lambda_memory_size = var.webhook_lambda_memory_size - lambda_tags = var.lambda_tags - tracing_config = var.tracing_config - logging_retention_in_days = var.logging_retention_in_days - logging_kms_key_id = var.logging_kms_key_id - log_class = var.log_class - - role_path = var.role_path - role_permissions_boundary = var.role_permissions_boundary - repository_white_list = var.repository_white_list - queue_selection_strategy = var.queue_selection_strategy - - lambda_subnet_ids = var.lambda_subnet_ids - lambda_security_group_ids = var.lambda_security_group_ids + lambda_s3_bucket = local.translated_experimental.orchestration.webhook.lambda.webhook.artifact.s3 == null ? null : local.translated_experimental.lambda.artifact.s3.bucket + webhook_lambda_s3_key = try(local.translated_experimental.orchestration.webhook.lambda.webhook.artifact.s3.key, null) + webhook_lambda_s3_object_version = try(local.translated_experimental.orchestration.webhook.lambda.webhook.artifact.s3.object_version, null) + webhook_lambda_apigateway_access_log_settings = local.translated_experimental.orchestration.webhook.lambda.webhook.api_gateway_access_log_settings + lambda_runtime = local.translated_experimental.lambda.runtime + lambda_architecture = local.translated_experimental.lambda.architecture + lambda_zip = local.translated_experimental.orchestration.webhook.lambda.webhook.artifact.zip + lambda_timeout = local.translated_experimental.orchestration.webhook.lambda.webhook.timeout + lambda_memory_size = local.translated_experimental.orchestration.webhook.lambda.webhook.memory_size + lambda_tags = merge(local.translated_experimental.lambda.tags, local.translated_experimental.orchestration.webhook.lambda.webhook.tags) + tracing_config = local.translated_experimental.observability.tracing + logging_retention_in_days = local.translated_experimental.observability.logs.retention_in_days + logging_kms_key_id = local.translated_experimental.observability.logs.kms_key_id + log_class = local.translated_experimental.observability.logs.class + + role_path = try(coalesce(local.translated_experimental.lambda.role.path, local.translated_experimental.roles.path), null) + role_permissions_boundary = try(coalesce(local.translated_experimental.lambda.role.permissions_boundary, local.translated_experimental.roles.permissions_boundary), null) + repository_white_list = local.translated_experimental.orchestration.webhook.github.repository_white_list + queue_selection_strategy = local.translated_experimental.orchestration.webhook.queue_selection_strategy + + lambda_subnet_ids = local.translated_experimental.lambda.subnet_ids + lambda_security_group_ids = local.translated_experimental.lambda.security_group_ids aws_partition = var.aws_partition - log_level = var.log_level + log_level = local.translated_experimental.observability.logs.level } diff --git a/modules/orchestration-providers/webhook/README.md b/modules/orchestration-providers/webhook/README.md new file mode 100644 index 0000000000..c6c25f2afd --- /dev/null +++ b/modules/orchestration-providers/webhook/README.md @@ -0,0 +1,57 @@ +# Webhook orchestration provider + +This internal module owns the event-driven runner demand controls used by `runner-config`: scale-up, scale-down, scheduled pool reconciliation, and optional queued-job retry. It receives the common GitHub, Lambda, runner-registration, SSM, observability, and selected compute-provider contracts from the parent configuration module, then resolves webhook-specific defaults and tag precedence before invoking its leaf modules. Lifecycle, boot time, and capacity are provider-owned under `config.runner`; the provider resolves the lifecycle contract for runner bootstrap, forwards capacity to scale-up and pool, and forwards boot time to scale-down and pool. It also combines the shared Lambda artifact bucket with its own `config.lambda.artifact` zip or S3 key/version shared by scale, pool, and job-retry; provider-specific artifact fields do not leak into the common Lambda contract. + +`runner-config` selects this provider when `orchestration.webhook` is the one populated orchestration block. The parent continues to own common runner resources, shared SSM configuration, and compute-provider selection. A future orchestration provider should be implemented as a sibling module with the same parent-facing resource boundary; it should not add its stateful resources to this webhook module. + +The scale-down lifecycle is documented in the [scale-down state diagram](./scale-down-state-diagram.md). + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 6.33 | + +## Providers + +No providers. + +## Modules + +| Name | Source | Version | +|------|--------|---------| +| [job\_retry](#module\_job\_retry) | ./job-retry | n/a | +| [pool](#module\_pool) | ./pool | n/a | +| [scale\_runners](#module\_scale\_runners) | ./scale-runners | n/a | + +## Resources + +No resources. + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [aws\_partition](#input\_aws\_partition) | AWS partition used to construct ARNs. | `string` | `"aws"` | no | +| [config](#input\_config) | Resolved provider-owned values from orchestration.webhook, including runner lifecycle, boot timeout, and capacity limits used by scaling and pool controls. |
object({
runner = object({
boot_time_in_minutes = number
ephemeral = bool
jit_config_enabled = optional(bool, null)
maximum_count = number
})
github = object({
organization_runners = bool
})
queue = object({
build = object({
arn = string
url = string
})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
})
lambda = object({
artifact = object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
})
scale = object({
up = object({
memory_size = number
timeout = number
reserved_concurrent_executions = number
job_queued_check_enabled = optional(bool, null)
event_source_mapping = object({
batch_size = number
maximum_batching_window_in_seconds = number
})
tags = optional(map(string), {})
})
down = object({
memory_size = number
timeout = number
schedule_expression = string
minimum_running_time_in_minutes = optional(number, null)
idle_config = list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = string
}))
tags = optional(map(string), {})
})
})
pool = object({
memory_size = number
timeout = number
reserved_concurrent_executions = number
config = list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
}))
include_busy_runners = bool
runner_owner = optional(string, null)
tags = optional(map(string), {})
})
})
job_retry = object({
enabled = bool
delay_in_seconds = number
delay_backoff = number
max_attempts = number
tags = optional(map(string), {})
lambda = object({
memory_size = number
reserved_concurrent_executions = number
timeout = number
})
})
})
| n/a | yes | +| [github](#input\_github) | Common GitHub API client and GitHub App Parameter Store references. |
object({
app_parameters = object({
key_base64 = list(map(string))
id = list(map(string))
installation_id = list(object({ name = string, arn = string }))
})
enterprise_server = object({
url = optional(string, null)
ssl_verify = bool
})
user_agent = optional(string, null)
})
| n/a | yes | +| [lambda](#input\_lambda) | Common Lambda substrate. Only the shared artifact bucket crosses this boundary; the webhook provider owns its archive key, version, and local zip selection. |
object({
artifact = object({
s3 = object({
bucket = optional(string, null)
})
})
runtime = string
architecture = string
subnet_ids = list(string)
security_group_ids = list(string)
tags = optional(map(string), {})
role = object({
path = string
permissions_boundary = optional(string, null)
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
})
})
| n/a | yes | +| [observability](#input\_observability) | Common logging, tracing, and metrics configuration consumed by webhook controls. |
object({
logs = object({
level = string
retention_in_days = number
kms_key_id = optional(string, null)
class = string
tags = optional(map(string), {})
})
tracing = object({
mode = optional(string, null)
capture_http_requests = bool
capture_error = bool
})
metrics = object({
enable = bool
namespace = string
metric = object({
enable_github_app_rate_limit = bool
enable_job_retry = bool
})
})
})
| n/a | yes | +| [prefix](#input\_prefix) | Prefix used to identify resources created for this webhook orchestration provider. | `string` | n/a | yes | +| [runner](#input\_runner) | Common runner registration values consumed by webhook demand controls. Lifecycle, boot timeout, and capacity remain provider-owned under config.runner. |
object({
os = string
auto_update_disabled = bool
labels = list(string)
group_name = string
name_prefix = string
})
| n/a | yes | +| [runner\_provider](#input\_runner\_provider) | Selected compute-provider capabilities consumed by webhook scaling, pool, and retry controls. |
object({
type = string
scale_up = object({
environment_variables = map(string)
iam_policy_json = string
additional_iam_policy_json = optional(string, null)
managed_policy = optional(object({
arn = string
}), null)
})
scale_down = object({
environment_variables = map(string)
iam_policy_json = string
})
pool = object({
environment_variables = map(string)
iam_policy_json = string
managed_policy_enabled = bool
managed_policy_arn = optional(string, null)
})
})
| n/a | yes | +| [ssm](#input\_ssm) | Resolved Parameter Store paths, optional decrypt key, and runtime parameter tags. |
object({
token_path = string
token_path_arn = string
config_path = string
config_path_arn = string
kms_key_id = optional(string, null)
parameter_store_tags = string
})
| n/a | yes | +| [tags](#input\_tags) | Base tags available to webhook-provider resources. Component-specific tags override this map within their documented scopes. | `map(string)` | `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [job\_retry](#output\_job\_retry) | Job-retry resources. Null when job retry is disabled. | +| [pool](#output\_pool) | Scheduled pool resources. Null when no pool schedule is configured. | +| [runner\_lifecycle](#output\_runner\_lifecycle) | Effective webhook-owned runner lifecycle consumed by runner-config bootstrap parameters. | +| [scale\_down](#output\_scale\_down) | Scale-down control-plane resources. | +| [scale\_up](#output\_scale\_up) | Scale-up control-plane resources. | + diff --git a/modules/orchestration-providers/webhook/job-retry.tf b/modules/orchestration-providers/webhook/job-retry.tf new file mode 100644 index 0000000000..651e12c9ea --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry.tf @@ -0,0 +1,48 @@ +module "job_retry" { + source = "./job-retry" + count = local.job_retry_enabled ? 1 : 0 + + config = { + prefix = local.resolved_config.prefix + aws_partition = var.aws_partition + lambda = { + artifact = local.resolved_config.lambda.artifact + runtime = local.resolved_config.lambda.runtime + architecture = local.resolved_config.lambda.architecture + memory_size = local.resolved_config.job_retry.lambda.memory_size + timeout = local.resolved_config.job_retry.lambda.timeout + reserved_concurrent_executions = local.resolved_config.job_retry.lambda.reserved_concurrent_executions + environment_variables = {} + vpc = { + subnet_ids = local.resolved_config.lambda.subnet_ids + security_group_ids = local.resolved_config.lambda.security_group_ids + } + role = local.resolved_config.lambda.role + } + runner = { + name_prefix = local.resolved_config.runner.name_prefix + } + github = local.resolved_config.github + queue = { + build = local.resolved_config.queue.build + kms_key_id = local.resolved_config.queue.kms_key_id + event_source_mapping = local.resolved_config.queue.event_source_mapping + encryption = { + sqs_managed_sse_enabled = true + kms_master_key_id = null + kms_data_key_reuse_period_seconds = null + } + } + ssm = { + kms_key_id = local.resolved_config.ssm.kms_key_id + } + observability = local.resolved_config.observability + tags = { + resources = local.job_retry_tags + lambda = local.job_retry_lambda_tags + log_group = local.job_retry_log_tags + queue = local.job_retry_queue_tags + event_source_mapping = local.job_retry_queue_tags + } + } +} diff --git a/modules/orchestration-providers/webhook/job-retry/README.md b/modules/orchestration-providers/webhook/job-retry/README.md new file mode 100644 index 0000000000..f73c1053d1 --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry/README.md @@ -0,0 +1,61 @@ +# Module - Job Retry + +This module is listening to a SQS queue where the scale-up lambda publishes messages for jobs that needs to trigger a retry if still queued. The job retry module lambda function is handling the messages, checking if the job is queued. Next for queued jobs a message is published to the build queue for the scale-up lambda. The scale-up lambda will handle the message as any other workflow job event. + +## Usages + +The module is an inner module used by the webhook orchestration provider when the opt-in feature for job retry is enabled. The module is not intended to be used standalone. + + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 6.21 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.21 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_log_group.job_retry](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_iam_role.job_retry](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy.job_retry](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.job_retry_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.job_retry_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy_attachment.job_retry_vpc_execution_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_lambda_event_source_mapping.job_retry](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_event_source_mapping) | resource | +| [aws_lambda_function.job_retry](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | +| [aws_lambda_permission.job_retry](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource | +| [aws_sqs_queue.job_retry_check_queue](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sqs_queue) | resource | +| [aws_sqs_queue_policy.job_retry_check_queue_policy](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sqs_queue_policy) | resource | +| [aws_iam_policy_document.deny_insecure_transport](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.job_retry](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.job_retry_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.lambda_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.lambda_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [config](#input\_config) | Provider-neutral job-retry configuration assembled by runner-config.

- `prefix`: Prefix used to name job-retry resources.
- `aws_partition`: AWS partition used to construct the Lambda VPC managed-policy ARN.
- `lambda.artifact.zip`: Resolved local control-plane archive.
- `lambda.artifact.s3.bucket`: Optional S3 bucket containing the Lambda archive.
- `lambda.artifact.s3.key`: Object key of the Lambda archive.
- `lambda.artifact.s3.object_version`: Optional object version of the Lambda archive.
- `lambda.runtime`: Runtime used by the job-retry Lambda.
- `lambda.architecture`: Instruction-set architecture used by the job-retry Lambda.
- `lambda.memory_size`: Memory allocated to the job-retry Lambda.
- `lambda.timeout`: Lambda timeout and retry-queue visibility timeout in seconds.
- `lambda.reserved_concurrent_executions`: Reserved concurrency for the Lambda. Use `-1` for unreserved concurrency.
- `lambda.environment_variables`: Additional Lambda environment variables. Required job-retry variables override matching keys.
- `lambda.vpc.subnet_ids`: Subnets used for Lambda VPC configuration.
- `lambda.vpc.security_group_ids`: Security groups used for Lambda VPC configuration.
- `lambda.role.path`: IAM path used for the job-retry Lambda role.
- `lambda.role.permissions_boundary`: Optional permissions boundary for the Lambda role.
- `lambda.role.principals`: Extra principals allowed to assume the Lambda role, for example during local testing.
- `runner.name_prefix`: Prefix used to identify runners belonging to this runner configuration.
- `github.organization_runners`: Enables organization runners.
- `github.enterprise_server.url`: Optional GitHub Enterprise Server URL.
- `github.enterprise_server.ssl_verify`: Enables TLS certificate verification for GitHub Enterprise Server requests.
- `github.user_agent`: Optional User-Agent sent to GitHub.
- `github.app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys.
- `github.app_parameters.id`: Ordered Parameter Store references for GitHub App IDs.
- `github.app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs.
- `queue.build`: URL and ARN of the build queue to which retry messages are published.
- `queue.kms_key_id`: Optional KMS key ARN used to encrypt the build queue. This is distinct from the Parameter Store key.
- `queue.event_source_mapping.batch_size`: Maximum records delivered per job-retry invocation.
- `queue.event_source_mapping.maximum_batching_window_in_seconds`: Maximum event batching window.
- `queue.encryption`: Server-side encryption configuration for the retry queue.
- `ssm.kms_key_id`: Optional KMS key ARN used by the job-retry IAM policy. Its value may be unknown until apply.
- `observability.logs`: Logging level, retention, encryption, and log-class configuration.
- `observability.tracing`: Lambda X-Ray and tracing-helper configuration.
- `observability.metrics`: Metrics enablement, namespace, and job-retry metric configuration.
- `tags.resources`: Tags for the job-retry Lambda role and component resources.
- `tags.lambda`: Tags for the job-retry Lambda function.
- `tags.log_group`: Tags for the job-retry log group.
- `tags.queue`: Tags for the retry queue.
- `tags.event_source_mapping`: Tags for the retry-queue event-source mapping. |
object({
prefix = string
aws_partition = string
lambda = object({
artifact = object({
zip = string
s3 = object({
bucket = optional(string, null)
key = optional(string, null)
object_version = optional(string, null)
})
})
runtime = string
architecture = string
memory_size = number
timeout = number
reserved_concurrent_executions = number
environment_variables = map(string)
vpc = object({
subnet_ids = list(string)
security_group_ids = list(string)
})
role = object({
path = string
permissions_boundary = optional(string, null)
principals = list(object({
type = string
identifiers = list(string)
}))
})
})
runner = object({
name_prefix = string
})
github = object({
organization_runners = bool
enterprise_server = object({
url = optional(string, null)
ssl_verify = optional(bool, true)
})
user_agent = optional(string, null)
app_parameters = object({
key_base64 = list(map(string))
id = list(map(string))
installation_id = list(object({ name = string, arn = string }))
})
})
queue = object({
build = object({
url = string
arn = string
})
kms_key_id = optional(string, null)
event_source_mapping = object({
batch_size = number
maximum_batching_window_in_seconds = number
})
encryption = object({
sqs_managed_sse_enabled = bool
kms_master_key_id = optional(string, null)
kms_data_key_reuse_period_seconds = optional(number, null)
})
})
ssm = object({
kms_key_id = optional(string, null)
})
observability = object({
logs = object({
level = string
retention_in_days = number
kms_key_id = optional(string, null)
class = string
})
tracing = object({
mode = optional(string, null)
capture_http_requests = bool
capture_error = bool
})
metrics = object({
enable = bool
namespace = string
metric = object({
enable_github_app_rate_limit = bool
enable_job_retry = bool
})
})
})
tags = object({
resources = map(string)
lambda = map(string)
log_group = map(string)
queue = map(string)
event_source_mapping = map(string)
})
})
| n/a | yes | + +## Outputs + +| Name | Description | +|------|-------------| +| [job\_retry\_check\_queue](#output\_job\_retry\_check\_queue) | Queue consumed by the job-retry Lambda. | +| [lambda](#output\_lambda) | Job-retry Lambda resources. | + diff --git a/modules/orchestration-providers/webhook/job-retry/iam-policies.tf b/modules/orchestration-providers/webhook/job-retry/iam-policies.tf new file mode 100644 index 0000000000..0e79e8a265 --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry/iam-policies.tf @@ -0,0 +1,122 @@ +# IAM policies attached to the job-retry Lambda role. +data "aws_iam_policy_document" "lambda_assume_role" { + statement { + sid = "WebhookJobRetryAssumeRole" + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + + dynamic "principals" { + for_each = var.config.lambda.role.principals + + content { + type = principals.value.type + identifiers = principals.value.identifiers + } + } + } +} + +data "aws_iam_policy_document" "job_retry_logging" { + statement { + sid = "WebhookJobRetryWriteLogs" + effect = "Allow" + + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + ] + + resources = ["${aws_cloudwatch_log_group.job_retry.arn}*"] + } +} + +data "aws_iam_policy_document" "lambda_xray" { + count = var.config.observability.tracing.mode != null ? 1 : 0 + + # AWS X-Ray write/read trace APIs do not support resource-level permissions. + statement { + sid = "AllowXRay" + effect = "Allow" + actions = [ + "xray:BatchGetTraces", + "xray:GetTraceSummaries", + "xray:PutTelemetryRecords", + "xray:PutTraceSegments", + ] + resources = ["*"] + } +} + +data "aws_iam_policy_document" "job_retry" { + statement { + sid = "WebhookJobRetryReadGitHubAppParameters" + effect = "Allow" + + actions = [ + "ssm:GetParameter", + "ssm:GetParameters", + ] + + resources = concat( + [for p in var.config.github.app_parameters.id : p.arn], + [for p in var.config.github.app_parameters.key_base64 : p.arn], + [for p in var.config.github.app_parameters.installation_id : p.arn if p != null], + ) + } + + statement { + sid = "WebhookJobRetryConsumeRetryQueue" + effect = "Allow" + + actions = [ + "sqs:ReceiveMessage", + "sqs:GetQueueAttributes", + "sqs:DeleteMessage", + ] + + resources = [aws_sqs_queue.job_retry_check_queue.arn] + } + + statement { + sid = "WebhookJobRetryPublishBuildQueue" + effect = "Allow" + + actions = [ + "sqs:SendMessage", + "sqs:GetQueueAttributes", + ] + + resources = [var.config.queue.build.arn] + } + + dynamic "statement" { + for_each = var.config.ssm.kms_key_id == null ? [] : [var.config.ssm.kms_key_id] + iterator = kms_key + + content { + sid = "WebhookJobRetryDecryptParameterStore" + effect = "Allow" + actions = ["kms:Decrypt"] + resources = [kms_key.value] + } + } + + dynamic "statement" { + for_each = var.config.queue.kms_key_id == null ? [] : [var.config.queue.kms_key_id] + iterator = kms_key + + content { + sid = "WebhookJobRetryEncryptBuildQueueMessage" + effect = "Allow" + actions = [ + "kms:Decrypt", + "kms:GenerateDataKey", + ] + resources = [kms_key.value] + } + } +} diff --git a/modules/orchestration-providers/webhook/job-retry/job-retry.tf b/modules/orchestration-providers/webhook/job-retry/job-retry.tf new file mode 100644 index 0000000000..7d819786aa --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry/job-retry.tf @@ -0,0 +1,179 @@ +# Provider-neutral job-retry queue and Lambda resources. +locals { + name = "job-retry" + vpc_enabled = ( + length(var.config.lambda.vpc.subnet_ids) > 0 && + length(var.config.lambda.vpc.security_group_ids) > 0 + ) + + lambda_environment_variables = { + ENVIRONMENT = var.config.prefix + LOG_LEVEL = var.config.observability.logs.level + PREFIX = var.config.prefix + POWERTOOLS_LOGGER_LOG_EVENT = var.config.observability.logs.level == "debug" ? "true" : "false" + POWERTOOLS_SERVICE_NAME = local.name + POWERTOOLS_TRACE_ENABLED = var.config.observability.tracing.mode != null + POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS = var.config.observability.tracing.capture_http_requests + POWERTOOLS_TRACER_CAPTURE_ERROR = var.config.observability.tracing.capture_error + POWERTOOLS_METRICS_NAMESPACE = var.config.observability.metrics.namespace + } + + job_retry_environment_variables = { + ENABLE_ORGANIZATION_RUNNERS = var.config.github.organization_runners + ENABLE_METRIC_JOB_RETRY = var.config.observability.metrics.enable && var.config.observability.metrics.metric.enable_job_retry + ENABLE_METRIC_GITHUB_APP_RATE_LIMIT = var.config.observability.metrics.enable && var.config.observability.metrics.metric.enable_github_app_rate_limit + GHES_URL = var.config.github.enterprise_server.url + NODE_TLS_REJECT_UNAUTHORIZED = var.config.github.enterprise_server.url != null && !var.config.github.enterprise_server.ssl_verify ? 0 : 1 + USER_AGENT = var.config.github.user_agent + JOB_QUEUE_SCALE_UP_URL = var.config.queue.build.url + PARAMETER_GITHUB_APP_ID_NAME = join(":", [for p in var.config.github.app_parameters.id : p.name]) + PARAMETER_GITHUB_APP_KEY_BASE64_NAME = join(":", [for p in var.config.github.app_parameters.key_base64 : p.name]) + PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = join(":", [for p in var.config.github.app_parameters.installation_id : p != null ? p.name : ""]) + RUNNER_NAME_PREFIX = var.config.runner.name_prefix + } + + environment_variables = merge( + local.lambda_environment_variables, + var.config.lambda.environment_variables, + local.job_retry_environment_variables, + ) +} + +resource "aws_sqs_queue_policy" "job_retry_check_queue_policy" { + queue_url = aws_sqs_queue.job_retry_check_queue.id + policy = data.aws_iam_policy_document.deny_insecure_transport.json +} + +resource "aws_sqs_queue" "job_retry_check_queue" { + name = "${var.config.prefix}-job-retry" + visibility_timeout_seconds = var.config.lambda.timeout + + sqs_managed_sse_enabled = var.config.queue.encryption.sqs_managed_sse_enabled + kms_master_key_id = var.config.queue.encryption.kms_master_key_id + kms_data_key_reuse_period_seconds = var.config.queue.encryption.kms_data_key_reuse_period_seconds + + tags = var.config.tags.queue +} + +resource "aws_lambda_function" "job_retry" { + s3_bucket = var.config.lambda.artifact.s3.bucket + s3_key = var.config.lambda.artifact.s3.key + s3_object_version = var.config.lambda.artifact.s3.object_version + filename = var.config.lambda.artifact.s3.bucket == null ? var.config.lambda.artifact.zip : null + source_code_hash = var.config.lambda.artifact.s3.bucket == null ? filebase64sha256(var.config.lambda.artifact.zip) : null + function_name = "${var.config.prefix}-${local.name}" + role = aws_iam_role.job_retry.arn + handler = "index.jobRetryCheck" + runtime = var.config.lambda.runtime + timeout = var.config.lambda.timeout + memory_size = var.config.lambda.memory_size + reserved_concurrent_executions = var.config.lambda.reserved_concurrent_executions + architectures = [var.config.lambda.architecture] + + environment { + variables = local.environment_variables + } + + dynamic "vpc_config" { + for_each = local.vpc_enabled ? [true] : [] + + content { + security_group_ids = var.config.lambda.vpc.security_group_ids + subnet_ids = var.config.lambda.vpc.subnet_ids + } + } + + dynamic "tracing_config" { + for_each = var.config.observability.tracing.mode != null ? [true] : [] + + content { + mode = var.config.observability.tracing.mode + } + } + + tags = var.config.tags.lambda +} + +resource "aws_cloudwatch_log_group" "job_retry" { + name = "/aws/lambda/${aws_lambda_function.job_retry.function_name}" + retention_in_days = var.config.observability.logs.retention_in_days + kms_key_id = var.config.observability.logs.kms_key_id + log_group_class = var.config.observability.logs.class + tags = var.config.tags.log_group +} + +resource "aws_iam_role" "job_retry" { + name = "${substr("${var.config.prefix}-${local.name}", 0, 54)}-${substr(md5("${var.config.prefix}-${local.name}"), 0, 8)}" + assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json + path = var.config.lambda.role.path + permissions_boundary = var.config.lambda.role.permissions_boundary + tags = var.config.tags.resources +} + +resource "aws_iam_role_policy" "job_retry_logging" { + name = "logging-policy" + role = aws_iam_role.job_retry.name + policy = data.aws_iam_policy_document.job_retry_logging.json +} + +resource "aws_iam_role_policy_attachment" "job_retry_vpc_execution_role" { + count = local.vpc_enabled ? 1 : 0 + role = aws_iam_role.job_retry.name + policy_arn = "arn:${var.config.aws_partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" +} + +resource "aws_iam_role_policy" "job_retry_xray" { + count = var.config.observability.tracing.mode != null ? 1 : 0 + name = "xray-policy" + policy = data.aws_iam_policy_document.lambda_xray[0].json + role = aws_iam_role.job_retry.name +} + +resource "aws_lambda_event_source_mapping" "job_retry" { + event_source_arn = aws_sqs_queue.job_retry_check_queue.arn + function_name = aws_lambda_function.job_retry.arn + batch_size = var.config.queue.event_source_mapping.batch_size + maximum_batching_window_in_seconds = var.config.queue.event_source_mapping.maximum_batching_window_in_seconds + tags = var.config.tags.event_source_mapping +} + +resource "aws_lambda_permission" "job_retry" { + statement_id = "AllowExecutionFromSQS" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.job_retry.function_name + principal = "sqs.amazonaws.com" + source_arn = aws_sqs_queue.job_retry_check_queue.arn +} + +resource "aws_iam_role_policy" "job_retry" { + name = "job_retry-policy" + role = aws_iam_role.job_retry.name + policy = data.aws_iam_policy_document.job_retry.json +} + +data "aws_iam_policy_document" "deny_insecure_transport" { + statement { + sid = "DenyInsecureTransport" + + effect = "Deny" + + principals { + type = "AWS" + identifiers = ["*"] + } + + actions = [ + "sqs:*" + ] + + resources = [ + aws_sqs_queue.job_retry_check_queue.arn + ] + + condition { + test = "Bool" + variable = "aws:SecureTransport" + values = ["false"] + } + } +} diff --git a/modules/orchestration-providers/webhook/job-retry/outputs.tf b/modules/orchestration-providers/webhook/job-retry/outputs.tf new file mode 100644 index 0000000000..4f08cc4498 --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry/outputs.tf @@ -0,0 +1,13 @@ +output "lambda" { + description = "Job-retry Lambda resources." + value = { + function = aws_lambda_function.job_retry + log_group = aws_cloudwatch_log_group.job_retry + role = aws_iam_role.job_retry + } +} + +output "job_retry_check_queue" { + description = "Queue consumed by the job-retry Lambda." + value = aws_sqs_queue.job_retry_check_queue +} diff --git a/modules/orchestration-providers/webhook/job-retry/tests/job-retry.tftest.hcl b/modules/orchestration-providers/webhook/job-retry/tests/job-retry.tftest.hcl new file mode 100644 index 0000000000..f99570354e --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry/tests/job-retry.tftest.hcl @@ -0,0 +1,332 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } + + mock_resource "aws_iam_role" { + defaults = { + arn = "arn:aws:iam::123456789012:role/job-retry-test" + } + } + +} + +variables { + config = { + prefix = "job-retry-test" + aws_partition = "aws" + lambda = { + artifact = { + zip = "unused.zip" + s3 = { + bucket = "lambda-artifacts" + key = "job-retry.zip" + } + } + architecture = "arm64" + runtime = "nodejs24.x" + memory_size = 256 + timeout = 30 + reserved_concurrent_executions = 1 + environment_variables = { + CUSTOM_ENV = "preserved" + RUNNER_NAME_PREFIX = "caller-prefix-" + } + vpc = { + security_group_ids = ["sg-12345678"] + subnet_ids = ["subnet-12345678"] + } + role = { + path = "/job-retry-test/" + principals = [{ + type = "AWS" + identifiers = ["arn:aws:iam::123456789012:root"] + }] + } + } + runner = { + name_prefix = "required-prefix-" + } + github = { + organization_runners = false + enterprise_server = { + url = "https://experimental-job-retry.example.com" + ssl_verify = false + } + user_agent = "experimental-job-retry-user-agent" + app_parameters = { + key_base64 = [ + { + name = "/github-runner/key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" + }, + { + name = "/github-runner/key-base64-2" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64-2" + }, + ] + id = [ + { + name = "/github-runner/app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" + }, + { + name = "/github-runner/app-id-2" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id-2" + }, + ] + installation_id = [ + null, + { + name = "/github-runner/installation-id-2" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/installation-id-2" + }, + ] + } + } + queue = { + build = { + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/build-queue" + arn = "arn:aws:sqs:eu-west-1:123456789012:build-queue" + } + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/build-queue-test" + event_source_mapping = { + batch_size = 10 + maximum_batching_window_in_seconds = 0 + } + encryption = { + sqs_managed_sse_enabled = true + } + } + ssm = { + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/job-retry-test" + } + observability = { + logs = { + level = "trace" + class = "INFREQUENT_ACCESS" + retention_in_days = 180 + } + tracing = { + mode = "Active" + capture_http_requests = false + capture_error = false + } + metrics = { + enable = false + namespace = "JobRetryTest" + metric = { + enable_github_app_rate_limit = true + enable_job_retry = true + } + } + } + tags = { + resources = { scope = "resources" } + lambda = { scope = "lambda" } + log_group = { scope = "log-group" } + queue = { scope = "queue" } + event_source_mapping = { scope = "event-source-mapping" } + } + } +} + +run "preserves_nested_job_retry_configuration" { + command = plan + + assert { + condition = output.lambda.function.environment[0].variables["CUSTOM_ENV"] == "preserved" + error_message = "Caller-provided job-retry environment variables must be preserved." + } + + assert { + condition = output.lambda.function.environment[0].variables["RUNNER_NAME_PREFIX"] == "required-prefix-" + error_message = "Required job-retry environment variables must override caller-provided values." + } + + assert { + condition = ( + output.lambda.function.environment[0].variables["GHES_URL"] == "https://experimental-job-retry.example.com" + && output.lambda.function.environment[0].variables["NODE_TLS_REJECT_UNAUTHORIZED"] == "0" + && output.lambda.function.environment[0].variables["USER_AGENT"] == "experimental-job-retry-user-agent" + && output.lambda.function.environment[0].variables["PARAMETER_GITHUB_APP_ID_NAME"] == "/github-runner/app-id:/github-runner/app-id-2" + && output.lambda.function.environment[0].variables["PARAMETER_GITHUB_APP_KEY_BASE64_NAME"] == "/github-runner/key-base64:/github-runner/key-base64-2" + && output.lambda.function.environment[0].variables["PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME"] == ":/github-runner/installation-id-2" + && contains(data.aws_iam_policy_document.job_retry.statement[0].resources, "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id-2") + && contains(data.aws_iam_policy_document.job_retry.statement[0].resources, "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64-2") + && contains(data.aws_iam_policy_document.job_retry.statement[0].resources, "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/installation-id-2") + ) + error_message = "Job retry must receive the nested GitHub connection settings, pass every app parameter, and grant access to every corresponding SSM ARN." + } + + assert { + condition = ( + toset(keys(output.lambda)) == toset(["function", "log_group", "role"]) + && output.lambda.function.s3_bucket == "lambda-artifacts" + && output.lambda.function.s3_key == "job-retry.zip" + && output.lambda.function.reserved_concurrent_executions == 1 + ) + error_message = "The nested Lambda configuration and direct resource output contract must be preserved." + } + + assert { + condition = ( + output.lambda.function.tags == tomap({ scope = "lambda" }) + && output.lambda.log_group.tags == tomap({ scope = "log-group" }) + && output.lambda.role.tags == tomap({ scope = "resources" }) + && output.job_retry_check_queue.tags == tomap({ scope = "queue" }) + && aws_lambda_event_source_mapping.job_retry.tags == tomap({ scope = "event-source-mapping" }) + ) + error_message = "Resolved nested tag maps must be applied to their owned resources." + } + + assert { + condition = ( + output.lambda.log_group.log_group_class == "INFREQUENT_ACCESS" + && length(data.aws_iam_policy_document.job_retry.statement) == 5 + && one([ + for statement in data.aws_iam_policy_document.job_retry.statement : statement + if statement.sid == "WebhookJobRetryDecryptParameterStore" + ]).resources == toset(["arn:aws:kms:eu-west-1:123456789012:key/job-retry-test"]) + && one([ + for statement in data.aws_iam_policy_document.job_retry.statement : statement + if statement.sid == "WebhookJobRetryDecryptParameterStore" + ]).actions == toset(["kms:Decrypt"]) + && one([ + for statement in data.aws_iam_policy_document.job_retry.statement : statement + if statement.sid == "WebhookJobRetryEncryptBuildQueueMessage" + ]).resources == toset(["arn:aws:kms:eu-west-1:123456789012:key/build-queue-test"]) + && one([ + for statement in data.aws_iam_policy_document.job_retry.statement : statement + if statement.sid == "WebhookJobRetryEncryptBuildQueueMessage" + ]).actions == toset(["kms:Decrypt", "kms:GenerateDataKey"]) + && length(aws_lambda_function.job_retry.vpc_config) == 1 + && length(aws_iam_role_policy_attachment.job_retry_vpc_execution_role) == 1 + && length(aws_iam_role_policy.job_retry_xray) == 1 + && length(data.aws_iam_policy_document.lambda_assume_role.statement[0].principals) == 2 + ) + error_message = "Logging, distinct Parameter Store/build-queue KMS grants, complete VPC, tracing, and extra role-principal configuration must be preserved." + } + + assert { + condition = ( + data.aws_iam_policy_document.lambda_xray[0].statement[0].sid == "AllowXRay" + && data.aws_iam_policy_document.lambda_xray[0].statement[0].resources == toset(["*"]) + && toset(data.aws_iam_policy_document.lambda_xray[0].statement[0].actions) == toset([ + "xray:BatchGetTraces", + "xray:GetTraceSummaries", + "xray:PutTelemetryRecords", + "xray:PutTraceSegments", + ]) + ) + error_message = "Only the resource-agnostic X-Ray APIs may retain a wildcard resource in the job-retry policies." + } + +} + +run "does_not_enable_partial_vpc_configuration" { + command = plan + + variables { + config = { + prefix = "job-retry-test" + aws_partition = "aws" + lambda = { + artifact = { + zip = "unused.zip" + s3 = { + bucket = "lambda-artifacts" + key = "job-retry.zip" + } + } + architecture = "arm64" + runtime = "nodejs24.x" + memory_size = 256 + timeout = 30 + reserved_concurrent_executions = 1 + environment_variables = {} + vpc = { + security_group_ids = [] + subnet_ids = ["subnet-12345678"] + } + role = { + path = "/job-retry-test/" + principals = [] + } + } + runner = { + name_prefix = "" + } + github = { + organization_runners = false + enterprise_server = {} + app_parameters = { + key_base64 = [{ + name = "/github-runner/key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" + }] + id = [{ + name = "/github-runner/app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" + }] + installation_id = [null] + } + } + queue = { + build = { + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/build-queue" + arn = "arn:aws:sqs:eu-west-1:123456789012:build-queue" + } + event_source_mapping = { + batch_size = 10 + maximum_batching_window_in_seconds = 0 + } + encryption = { + sqs_managed_sse_enabled = true + } + } + ssm = {} + observability = { + logs = { + level = "info" + class = "STANDARD" + retention_in_days = 180 + } + tracing = { + capture_http_requests = false + capture_error = false + } + metrics = { + enable = false + namespace = "GitHub Runners" + metric = { + enable_github_app_rate_limit = true + enable_job_retry = true + } + } + } + tags = { + resources = {} + lambda = {} + log_group = {} + queue = {} + event_source_mapping = {} + } + } + } + + assert { + condition = ( + length(aws_lambda_function.job_retry.vpc_config) == 0 + && length(aws_iam_role_policy_attachment.job_retry_vpc_execution_role) == 0 + && length(data.aws_iam_policy_document.job_retry.statement) == 3 + && length([ + for statement in data.aws_iam_policy_document.job_retry.statement : statement + if contains(statement.actions, "kms:Decrypt") + ]) == 0 + ) + error_message = "Partial VPC inputs must stay disabled and a null KMS key must omit the KMS statement entirely." + } +} diff --git a/modules/orchestration-providers/webhook/job-retry/variables.tf b/modules/orchestration-providers/webhook/job-retry/variables.tf new file mode 100644 index 0000000000..d6645c3bb6 --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry/variables.tf @@ -0,0 +1,166 @@ +variable "config" { + description = <<-EOT + Provider-neutral job-retry configuration assembled by runner-config. + + - `prefix`: Prefix used to name job-retry resources. + - `aws_partition`: AWS partition used to construct the Lambda VPC managed-policy ARN. + - `lambda.artifact.zip`: Resolved local control-plane archive. + - `lambda.artifact.s3.bucket`: Optional S3 bucket containing the Lambda archive. + - `lambda.artifact.s3.key`: Object key of the Lambda archive. + - `lambda.artifact.s3.object_version`: Optional object version of the Lambda archive. + - `lambda.runtime`: Runtime used by the job-retry Lambda. + - `lambda.architecture`: Instruction-set architecture used by the job-retry Lambda. + - `lambda.memory_size`: Memory allocated to the job-retry Lambda. + - `lambda.timeout`: Lambda timeout and retry-queue visibility timeout in seconds. + - `lambda.reserved_concurrent_executions`: Reserved concurrency for the Lambda. Use `-1` for unreserved concurrency. + - `lambda.environment_variables`: Additional Lambda environment variables. Required job-retry variables override matching keys. + - `lambda.vpc.subnet_ids`: Subnets used for Lambda VPC configuration. + - `lambda.vpc.security_group_ids`: Security groups used for Lambda VPC configuration. + - `lambda.role.path`: IAM path used for the job-retry Lambda role. + - `lambda.role.permissions_boundary`: Optional permissions boundary for the Lambda role. + - `lambda.role.principals`: Extra principals allowed to assume the Lambda role, for example during local testing. + - `runner.name_prefix`: Prefix used to identify runners belonging to this runner configuration. + - `github.organization_runners`: Enables organization runners. + - `github.enterprise_server.url`: Optional GitHub Enterprise Server URL. + - `github.enterprise_server.ssl_verify`: Enables TLS certificate verification for GitHub Enterprise Server requests. + - `github.user_agent`: Optional User-Agent sent to GitHub. + - `github.app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys. + - `github.app_parameters.id`: Ordered Parameter Store references for GitHub App IDs. + - `github.app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs. + - `queue.build`: URL and ARN of the build queue to which retry messages are published. + - `queue.kms_key_id`: Optional KMS key ARN used to encrypt the build queue. This is distinct from the Parameter Store key. + - `queue.event_source_mapping.batch_size`: Maximum records delivered per job-retry invocation. + - `queue.event_source_mapping.maximum_batching_window_in_seconds`: Maximum event batching window. + - `queue.encryption`: Server-side encryption configuration for the retry queue. + - `ssm.kms_key_id`: Optional KMS key ARN used by the job-retry IAM policy. Its value may be unknown until apply. + - `observability.logs`: Logging level, retention, encryption, and log-class configuration. + - `observability.tracing`: Lambda X-Ray and tracing-helper configuration. + - `observability.metrics`: Metrics enablement, namespace, and job-retry metric configuration. + - `tags.resources`: Tags for the job-retry Lambda role and component resources. + - `tags.lambda`: Tags for the job-retry Lambda function. + - `tags.log_group`: Tags for the job-retry log group. + - `tags.queue`: Tags for the retry queue. + - `tags.event_source_mapping`: Tags for the retry-queue event-source mapping. + EOT + + type = object({ + prefix = string + aws_partition = string + lambda = object({ + artifact = object({ + zip = string + s3 = object({ + bucket = optional(string, null) + key = optional(string, null) + object_version = optional(string, null) + }) + }) + runtime = string + architecture = string + memory_size = number + timeout = number + reserved_concurrent_executions = number + environment_variables = map(string) + vpc = object({ + subnet_ids = list(string) + security_group_ids = list(string) + }) + role = object({ + path = string + permissions_boundary = optional(string, null) + principals = list(object({ + type = string + identifiers = list(string) + })) + }) + }) + runner = object({ + name_prefix = string + }) + github = object({ + organization_runners = bool + enterprise_server = object({ + url = optional(string, null) + ssl_verify = optional(bool, true) + }) + user_agent = optional(string, null) + app_parameters = object({ + key_base64 = list(map(string)) + id = list(map(string)) + installation_id = list(object({ name = string, arn = string })) + }) + }) + queue = object({ + build = object({ + url = string + arn = string + }) + kms_key_id = optional(string, null) + event_source_mapping = object({ + batch_size = number + maximum_batching_window_in_seconds = number + }) + encryption = object({ + sqs_managed_sse_enabled = bool + kms_master_key_id = optional(string, null) + kms_data_key_reuse_period_seconds = optional(number, null) + }) + }) + ssm = object({ + kms_key_id = optional(string, null) + }) + observability = object({ + logs = object({ + level = string + retention_in_days = number + kms_key_id = optional(string, null) + class = string + }) + tracing = object({ + mode = optional(string, null) + capture_http_requests = bool + capture_error = bool + }) + metrics = object({ + enable = bool + namespace = string + metric = object({ + enable_github_app_rate_limit = bool + enable_job_retry = bool + }) + }) + }) + tags = object({ + resources = map(string) + lambda = map(string) + log_group = map(string) + queue = map(string) + event_source_mapping = map(string) + }) + }) + + nullable = false + + validation { + condition = contains(["arm64", "x86_64"], var.config.lambda.architecture) + error_message = "config.lambda.architecture must be arm64 or x86_64." + } + + validation { + condition = contains([ + "silly", + "trace", + "debug", + "info", + "warn", + "error", + "fatal", + ], var.config.observability.logs.level) + error_message = "config.observability.logs.level must be one of silly, trace, debug, info, warn, error, or fatal." + } + + validation { + condition = length(var.config.prefix) + length("job-retry") <= 63 + error_message = "The length of config.prefix plus job-retry must be less than or equal to 63." + } +} diff --git a/modules/orchestration-providers/webhook/job-retry/versions.tf b/modules/orchestration-providers/webhook/job-retry/versions.tf new file mode 100644 index 0000000000..42a40b33fd --- /dev/null +++ b/modules/orchestration-providers/webhook/job-retry/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.21" + } + } +} diff --git a/modules/orchestration-providers/webhook/main.tf b/modules/orchestration-providers/webhook/main.tf new file mode 100644 index 0000000000..d9b1722d98 --- /dev/null +++ b/modules/orchestration-providers/webhook/main.tf @@ -0,0 +1,66 @@ +locals { + packaged_runners_lambda_zip = "${path.module}/../../../lambdas/functions/control-plane/runners.zip" + runner_control_artifact_s3_selected = var.config.lambda.artifact.s3 != null + runner_control_artifact = { + zip = local.runner_control_artifact_s3_selected ? null : coalesce( + var.config.lambda.artifact.zip, + local.packaged_runners_lambda_zip, + ) + s3 = { + bucket = local.runner_control_artifact_s3_selected ? var.lambda.artifact.s3.bucket : null + key = try(var.config.lambda.artifact.s3.key, null) + object_version = try(var.config.lambda.artifact.s3.object_version, null) + } + } + + resolved_config = { + prefix = var.prefix + tags = var.tags + runner = merge(var.runner, var.config.runner, { + jit_config_enabled = ( + var.config.runner.jit_config_enabled == null + ? var.config.runner.ephemeral + : var.config.runner.jit_config_enabled + ) + }) + github = merge(var.github, var.config.github) + lambda = merge(var.lambda, { + artifact = local.runner_control_artifact + }) + queue = merge(var.config.queue, { + event_source_mapping = var.config.lambda.scale.up.event_source_mapping + }) + scale_up = var.config.lambda.scale.up + scale_down = var.config.lambda.scale.down + pool = var.config.lambda.pool + job_retry = var.config.job_retry + ssm = var.ssm + observability = var.observability + } + + common_tags = local.resolved_config.tags + lambda_tags = merge(local.common_tags, local.resolved_config.lambda.tags) + queue_tags = merge(local.common_tags, local.resolved_config.queue.tags) + observability_log_tags = merge(local.common_tags, local.resolved_config.observability.logs.tags) + + scale_up_tags = merge(local.common_tags, local.resolved_config.scale_up.tags) + scale_up_lambda_tags = merge(local.lambda_tags, local.resolved_config.scale_up.tags) + scale_up_log_tags = merge(local.observability_log_tags, local.resolved_config.scale_up.tags) + scale_up_queue_tags = merge(local.queue_tags, local.resolved_config.scale_up.tags) + + scale_down_tags = merge(local.common_tags, local.resolved_config.scale_down.tags) + scale_down_lambda_tags = merge(local.lambda_tags, local.resolved_config.scale_down.tags) + scale_down_log_tags = merge(local.observability_log_tags, local.resolved_config.scale_down.tags) + + pool_tags = merge(local.common_tags, local.resolved_config.pool.tags) + pool_lambda_tags = merge(local.lambda_tags, local.resolved_config.pool.tags) + pool_log_tags = merge(local.observability_log_tags, local.resolved_config.pool.tags) + + job_retry_enabled = local.resolved_config.job_retry.enabled + job_retry_tags = merge(local.common_tags, local.resolved_config.job_retry.tags) + job_retry_lambda_tags = merge(local.lambda_tags, local.resolved_config.job_retry.tags) + job_retry_log_tags = merge(local.observability_log_tags, local.resolved_config.job_retry.tags) + job_retry_queue_tags = merge(local.queue_tags, local.resolved_config.job_retry.tags) + + enable_job_queued_check = local.resolved_config.scale_up.job_queued_check_enabled == null ? !local.resolved_config.runner.ephemeral : local.resolved_config.scale_up.job_queued_check_enabled +} diff --git a/modules/orchestration-providers/webhook/outputs.tf b/modules/orchestration-providers/webhook/outputs.tf new file mode 100644 index 0000000000..0fb477ba7d --- /dev/null +++ b/modules/orchestration-providers/webhook/outputs.tf @@ -0,0 +1,30 @@ +output "scale_up" { + description = "Scale-up control-plane resources." + value = module.scale_runners.scale_up +} + +output "scale_down" { + description = "Scale-down control-plane resources." + value = module.scale_runners.scale_down +} + +output "pool" { + description = "Scheduled pool resources. Null when no pool schedule is configured." + value = one(module.pool[*].pool) +} + +output "job_retry" { + description = "Job-retry resources. Null when job retry is disabled." + value = local.job_retry_enabled ? { + lambda = one(module.job_retry[*].lambda) + queue = one(module.job_retry[*].job_retry_check_queue) + } : null +} + +output "runner_lifecycle" { + description = "Effective webhook-owned runner lifecycle consumed by runner-config bootstrap parameters." + value = { + ephemeral = local.resolved_config.runner.ephemeral + jit_config_enabled = local.resolved_config.runner.jit_config_enabled + } +} diff --git a/modules/orchestration-providers/webhook/pool.tf b/modules/orchestration-providers/webhook/pool.tf new file mode 100644 index 0000000000..6fb9ad3d34 --- /dev/null +++ b/modules/orchestration-providers/webhook/pool.tf @@ -0,0 +1,66 @@ +module "pool" { + count = length(local.resolved_config.pool.config) > 0 ? 1 : 0 + source = "./pool" + + config = { + prefix = local.resolved_config.prefix + ghes = { + ssl_verify = local.resolved_config.github.enterprise_server.ssl_verify + url = local.resolved_config.github.enterprise_server.url + } + user_agent = local.resolved_config.github.user_agent + github_app_parameters = local.resolved_config.github.app_parameters + runners_maximum_count = local.resolved_config.runner.maximum_count + kms_key_id = local.resolved_config.ssm.kms_key_id + lambda = { + log_level = local.resolved_config.observability.logs.level + logging_retention_in_days = local.resolved_config.observability.logs.retention_in_days + logging_kms_key_id = local.resolved_config.observability.logs.kms_key_id + log_class = local.resolved_config.observability.logs.class + reserved_concurrent_executions = local.resolved_config.pool.reserved_concurrent_executions + s3_bucket = local.resolved_config.lambda.artifact.s3.bucket + s3_key = local.resolved_config.lambda.artifact.s3.key + s3_object_version = local.resolved_config.lambda.artifact.s3.object_version + security_group_ids = local.resolved_config.lambda.security_group_ids + subnet_ids = local.resolved_config.lambda.subnet_ids + architecture = local.resolved_config.lambda.architecture + memory_size = local.resolved_config.pool.memory_size + runtime = local.resolved_config.lambda.runtime + timeout = local.resolved_config.pool.timeout + zip = local.resolved_config.lambda.artifact.zip + parameter_store_tags = local.resolved_config.ssm.parameter_store_tags + principals = local.resolved_config.lambda.role.principals + } + pool = local.resolved_config.pool.config + include_busy_runners = local.resolved_config.pool.include_busy_runners + role_path = local.resolved_config.lambda.role.path + role_permissions_boundary = local.resolved_config.lambda.role.permissions_boundary + runner = { + disable_runner_autoupdate = local.resolved_config.runner.auto_update_disabled + ephemeral = local.resolved_config.runner.ephemeral + enable_jit_config = local.resolved_config.runner.jit_config_enabled + labels = local.resolved_config.runner.labels + group_name = local.resolved_config.runner.group_name + name_prefix = local.resolved_config.runner.name_prefix + pool_owner = local.resolved_config.pool.runner_owner + boot_time_in_minutes = local.resolved_config.runner.boot_time_in_minutes + } + ssm_token_path = local.resolved_config.ssm.token_path + ssm_token_path_arn = local.resolved_config.ssm.token_path_arn + ssm_config_path = local.resolved_config.ssm.config_path + tags = local.pool_tags + lambda_tags = local.pool_lambda_tags + log_group_tags = local.pool_log_tags + arn_ssm_parameters_path_config = local.resolved_config.ssm.config_path_arn + } + + aws_partition = var.aws_partition + tracing_config = local.resolved_config.observability.tracing + runner_provider = { + type = var.runner_provider.type + environment_variables = var.runner_provider.pool.environment_variables + iam_policy_json = var.runner_provider.pool.iam_policy_json + managed_policy_enabled = var.runner_provider.pool.managed_policy_enabled + managed_policy_arn = var.runner_provider.pool.managed_policy_arn + } +} diff --git a/modules/orchestration-providers/webhook/pool/README.md b/modules/orchestration-providers/webhook/pool/README.md new file mode 100644 index 0000000000..1cf4a1a545 --- /dev/null +++ b/modules/orchestration-providers/webhook/pool/README.md @@ -0,0 +1,64 @@ +# Pool module + +This module creates the AWS resources required to maintain a pool of runners. However terraform modules are always exposed and theoretically can be used anywhere. This module is seen as a strict inner module. + +## Why a submodule for the pool + +The pool is an opt-in feature. To be able to use the count on a module level to avoid counts per resources a module is created. All inputs of the module are already defined on a higher level. See the mapping of the variables in [`pool.tf`](../pool.tf) + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 6.21 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.21 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_log_group.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_iam_role.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role.scheduler](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.pool_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.pool_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.scheduler](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy_attachment.pool_vpc_execution_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_iam_role_policy_attachment.provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_lambda_function.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | +| [aws_scheduler_schedule.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/scheduler_schedule) | resource | +| [aws_scheduler_schedule_group.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/scheduler_schedule_group) | resource | +| [aws_iam_policy_document.lambda_assume_role_policy](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.lambda_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.pool](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.pool_common](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.pool_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scheduler](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scheduler_assume](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [aws\_partition](#input\_aws\_partition) | (optional) partition for the arn if not 'aws' | `string` | `"aws"` | no | +| [config](#input\_config) | Configuration passed from the webhook orchestration provider to the pool Lambda and scheduler.

- `lambda`: Pool Lambda runtime and deployment configuration.
- `lambda.log_level`: Logging level used by the pool Lambda.
- `lambda.logging_retention_in_days`: Number of days to retain events in the pool Lambda log group.
- `lambda.logging_kms_key_id`: KMS key ID used to encrypt the pool Lambda log group.
- `lambda.log_class`: CloudWatch Logs class for the pool Lambda log group.
- `lambda.reserved_concurrent_executions`: Reserved concurrency for the pool Lambda. Use -1 for no reservation.
- `lambda.s3_bucket`: S3 bucket containing the pool Lambda deployment package.
- `lambda.s3_key`: S3 key of the pool Lambda deployment package.
- `lambda.s3_object_version`: S3 object version of the pool Lambda deployment package.
- `lambda.security_group_ids`: Security group IDs associated with the pool Lambda.
- `lambda.runtime`: AWS Lambda runtime used by the pool Lambda.
- `lambda.architecture`: AWS Lambda architecture used by the pool Lambda.
- `lambda.memory_size`: Memory allocated to the pool Lambda in MB.
- `lambda.timeout`: Pool Lambda timeout in seconds.
- `lambda.zip`: Local path to the pool Lambda deployment package when S3 is not used.
- `lambda.subnet_ids`: Subnet IDs in which the pool Lambda runs.
- `lambda.parameter_store_tags`: JSON-encoded tags supplied to the pool Lambda for SSM parameters it creates.
- `lambda.principals`: Additional principals allowed to assume the pool Lambda role.
- `tags`: Common tags added to pool resources.
- `ghes`: GitHub Enterprise Server connection configuration.
- `ghes.url`: GitHub Enterprise Server URL; null when using public GitHub.
- `ghes.ssl_verify`: Whether the pool Lambda verifies the GitHub Enterprise Server TLS certificate.
- `github_app_parameters`: Ordered SSM parameter metadata for GitHub App credentials.
- `github_app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys.
- `github_app_parameters.id`: Ordered Parameter Store references for GitHub App IDs.
- `github_app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs.
- `runner`: Runner registration configuration used by the pool Lambda.
- `runner.disable_runner_autoupdate`: Whether GitHub runner automatic updates are disabled.
- `runner.ephemeral`: Whether runners register as ephemeral runners.
- `runner.enable_jit_config`: Whether runners use just-in-time registration configuration.
- `runner.labels`: Labels assigned to runners created by the pool Lambda.
- `runner.group_name`: GitHub runner group assigned to runners created by the pool Lambda.
- `runner.name_prefix`: Prefix used for runner names.
- `runner.pool_owner`: GitHub organization or repository that owns the runner pool.
- `runner.boot_time_in_minutes`: Webhook-provider runner boot timeout used by pool reconciliation.
- `runners_maximum_count`: Webhook-provider runner capacity limit enforced by the pool Lambda.
- `prefix`: Prefix used to name pool resources.
- `pool`: Scheduled pool targets.
- `pool[*].schedule_expression`: EventBridge Scheduler expression for a pool target.
- `pool[*].schedule_expression_timezone`: Time zone used to evaluate the schedule expression.
- `pool[*].size`: Desired runner count for the scheduled pool target.
- `include_busy_runners`: Whether busy runners count toward the desired pool size.
- `role_permissions_boundary`: Permissions boundary applied to IAM roles created for the pool.
- `kms_key_id`: Optional customer-managed KMS key ARN that the pool Lambda may use to decrypt encrypted parameters.
- `role_path`: IAM path applied to roles created for the pool.
- `ssm_token_path`: SSM path under which runner registration tokens are stored.
- `ssm_token_path_arn`: ARN matching the runner registration-token SSM path.
- `ssm_config_path`: SSM path under which runner configuration is stored.
- `arn_ssm_parameters_path_config`: ARN matching the runner configuration SSM path.
- `lambda_tags`: Tags added specifically to the pool Lambda function, overriding common tags with the same key.
- `log_group_tags`: Tags added specifically to the pool Lambda log group, overriding common tags with the same key.
- `user_agent`: User-Agent header used for GitHub API requests. |
object({
lambda = object({
log_level = string
logging_retention_in_days = number
logging_kms_key_id = string
log_class = string
reserved_concurrent_executions = number
s3_bucket = string
s3_key = string
s3_object_version = string
security_group_ids = list(string)
runtime = string
architecture = string
memory_size = number
timeout = number
zip = string
subnet_ids = list(string)
parameter_store_tags = string
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
})
tags = map(string)
ghes = object({
url = string
ssl_verify = string
})
github_app_parameters = object({
key_base64 = list(map(string))
id = list(map(string))
installation_id = list(object({ name = string, arn = string }))
})
runner = object({
disable_runner_autoupdate = bool
ephemeral = bool
enable_jit_config = bool
labels = list(string)
group_name = string
name_prefix = string
pool_owner = string
boot_time_in_minutes = number
})
runners_maximum_count = number
prefix = string
pool = list(object({
schedule_expression = string
schedule_expression_timezone = string
size = number
}))
include_busy_runners = bool
role_permissions_boundary = string
kms_key_id = optional(string, null)
role_path = string
ssm_token_path = string
ssm_token_path_arn = string
ssm_config_path = string
arn_ssm_parameters_path_config = string
lambda_tags = map(string)
log_group_tags = optional(map(string), {})
user_agent = string
})
| n/a | yes | +| [runner\_provider](#input\_runner\_provider) | Compute provider integration used by the pool Lambda.

- `type`: Compute provider type passed to scheduled pool invocations.
- `environment_variables`: Provider-specific environment variables added to the pool Lambda.
- `iam_policy_json`: Provider-specific IAM policy document merged into the pool Lambda policy.
- `managed_policy_enabled`: Whether to attach a provider-specific managed IAM policy to the pool Lambda role.
- `managed_policy_arn`: ARN of the provider-specific managed IAM policy to attach when enabled. |
object({
type = string
environment_variables = map(string)
iam_policy_json = string
managed_policy_enabled = bool
managed_policy_arn = optional(string, null)
})
| n/a | yes | +| [tracing\_config](#input\_tracing\_config) | Tracing configuration for the pool Lambda.

- `mode`: AWS X-Ray tracing mode. A null value disables tracing.
- `capture_http_requests`: Whether Powertools tracing captures outgoing HTTP requests.
- `capture_error`: Whether Powertools tracing captures errors as tracing metadata. |
object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
})
| `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [pool](#output\_pool) | Scheduled pool Lambda resources. | + diff --git a/modules/orchestration-providers/webhook/pool/iam-policies.tf b/modules/orchestration-providers/webhook/pool/iam-policies.tf new file mode 100644 index 0000000000..f5a9285bce --- /dev/null +++ b/modules/orchestration-providers/webhook/pool/iam-policies.tf @@ -0,0 +1,77 @@ +# IAM policies attached to the pool Lambda role. +data "aws_iam_policy_document" "pool_common" { + statement { + sid = "WebhookPoolWriteRuntimeParameters" + effect = "Allow" + + actions = [ + "ssm:AddTagsToResource", + "ssm:PutParameter", + ] + + resources = [ + var.config.ssm_token_path_arn, + "${var.config.ssm_token_path_arn}/*", + var.config.arn_ssm_parameters_path_config, + "${var.config.arn_ssm_parameters_path_config}/*", + ] + } + + statement { + sid = "WebhookPoolReadRunnerConfigParameters" + effect = "Allow" + + actions = [ + "ssm:GetParameter", + "ssm:GetParameters", + "ssm:GetParametersByPath", + ] + + resources = [ + var.config.arn_ssm_parameters_path_config, + "${var.config.arn_ssm_parameters_path_config}/*", + ] + } + + statement { + sid = "WebhookPoolReadGitHubAppParameters" + effect = "Allow" + + actions = [ + "ssm:GetParameter", + "ssm:GetParameters", + ] + + resources = concat( + [for p in var.config.github_app_parameters.id : p.arn], + [for p in var.config.github_app_parameters.key_base64 : p.arn], + [for p in var.config.github_app_parameters.installation_id : p.arn if p != null], + ) + } + + dynamic "statement" { + for_each = var.config.kms_key_id == null ? [] : [var.config.kms_key_id] + iterator = kms_key + + content { + sid = "WebhookPoolDecryptParameterStore" + effect = "Allow" + actions = ["kms:Decrypt"] + resources = [kms_key.value] + } + } +} + +data "aws_iam_policy_document" "pool_logging" { + statement { + sid = "WebhookPoolWriteLogs" + effect = "Allow" + + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + ] + + resources = ["${aws_cloudwatch_log_group.pool.arn}*"] + } +} diff --git a/modules/orchestration-providers/webhook/pool/outputs.tf b/modules/orchestration-providers/webhook/pool/outputs.tf new file mode 100644 index 0000000000..cfc429ecce --- /dev/null +++ b/modules/orchestration-providers/webhook/pool/outputs.tf @@ -0,0 +1,8 @@ +output "pool" { + description = "Scheduled pool Lambda resources." + value = { + lambda = aws_lambda_function.pool + log_group = aws_cloudwatch_log_group.pool + role = aws_iam_role.pool + } +} diff --git a/modules/orchestration-providers/webhook/pool/pool.tf b/modules/orchestration-providers/webhook/pool/pool.tf new file mode 100644 index 0000000000..cff2776e90 --- /dev/null +++ b/modules/orchestration-providers/webhook/pool/pool.tf @@ -0,0 +1,236 @@ +# Provider-neutral pool Lambda and scheduler wiring. +locals { + pool_name_prefix = ( + length("${var.config.prefix}-pool") <= 38 + ? "${var.config.prefix}-pool" + : "${substr("${var.config.prefix}-pool", 0, 29)}-${substr(md5("${var.config.prefix}-pool"), 0, 8)}" + ) + + common_environment_variables = { + DISABLE_RUNNER_AUTOUPDATE = var.config.runner.disable_runner_autoupdate + ENABLE_EPHEMERAL_RUNNERS = var.config.runner.ephemeral + ENABLE_JIT_CONFIG = var.config.runner.enable_jit_config + ENVIRONMENT = var.config.prefix + GHES_URL = var.config.ghes.url + USER_AGENT = var.config.user_agent + LOG_LEVEL = upper(var.config.lambda.log_level) + NODE_TLS_REJECT_UNAUTHORIZED = var.config.ghes.url != null && !var.config.ghes.ssl_verify ? 0 : 1 + PARAMETER_GITHUB_APP_ID_NAME = join(":", [for p in var.config.github_app_parameters.id : p.name]) + PARAMETER_GITHUB_APP_KEY_BASE64_NAME = join(":", [for p in var.config.github_app_parameters.key_base64 : p.name]) + PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = join(":", [for p in var.config.github_app_parameters.installation_id : p != null ? p.name : ""]) + POWERTOOLS_LOGGER_LOG_EVENT = var.config.lambda.log_level == "debug" ? "true" : "false" + RUNNER_LABELS = lower(join(",", var.config.runner.labels)) + RUNNER_GROUP_NAME = var.config.runner.group_name + RUNNER_NAME_PREFIX = var.config.runner.name_prefix + RUNNER_OWNER = var.config.runner.pool_owner + RUNNER_BOOT_TIME_IN_MINUTES = var.config.runner.boot_time_in_minutes + RUNNERS_MAXIMUM_COUNT = var.config.runners_maximum_count + SSM_TOKEN_PATH = var.config.ssm_token_path + SSM_CONFIG_PATH = var.config.ssm_config_path + POWERTOOLS_SERVICE_NAME = "${var.config.prefix}-pool" + POWERTOOLS_TRACE_ENABLED = var.tracing_config.mode != null ? true : false + POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS = var.tracing_config.capture_http_requests + POWERTOOLS_TRACER_CAPTURE_ERROR = var.tracing_config.capture_error + SSM_PARAMETER_STORE_TAGS = var.config.lambda.parameter_store_tags + INCLUDE_BUSY_RUNNERS = var.config.include_busy_runners + } +} + +resource "aws_lambda_function" "pool" { + + s3_bucket = var.config.lambda.s3_bucket != null ? var.config.lambda.s3_bucket : null + s3_key = var.config.lambda.s3_key != null ? var.config.lambda.s3_key : null + s3_object_version = var.config.lambda.s3_object_version != null ? var.config.lambda.s3_object_version : null + filename = var.config.lambda.s3_bucket == null ? var.config.lambda.zip : null + source_code_hash = var.config.lambda.s3_bucket == null ? filebase64sha256(var.config.lambda.zip) : null + function_name = "${var.config.prefix}-pool" + role = aws_iam_role.pool.arn + handler = "index.adjustPool" + architectures = [var.config.lambda.architecture] + runtime = var.config.lambda.runtime + timeout = var.config.lambda.timeout + reserved_concurrent_executions = var.config.lambda.reserved_concurrent_executions + memory_size = var.config.lambda.memory_size + tags = merge(var.config.tags, var.config.lambda_tags) + + environment { + variables = merge(var.runner_provider.environment_variables, local.common_environment_variables) + } + + dynamic "vpc_config" { + for_each = var.config.lambda.subnet_ids != null && var.config.lambda.security_group_ids != null ? [true] : [] + content { + security_group_ids = var.config.lambda.security_group_ids + subnet_ids = var.config.lambda.subnet_ids + } + } + + dynamic "tracing_config" { + for_each = var.tracing_config.mode != null ? [true] : [] + content { + mode = var.tracing_config.mode + } + } +} + +resource "aws_cloudwatch_log_group" "pool" { + name = "/aws/lambda/${aws_lambda_function.pool.function_name}" + retention_in_days = var.config.lambda.logging_retention_in_days + kms_key_id = var.config.lambda.logging_kms_key_id + log_group_class = var.config.lambda.log_class + tags = merge(var.config.tags, var.config.log_group_tags) +} + +resource "aws_iam_role" "pool" { + name = "${substr("${var.config.prefix}-pool-lambda", 0, 54)}-${substr(md5("${var.config.prefix}-pool-lambda"), 0, 8)}" + assume_role_policy = data.aws_iam_policy_document.lambda_assume_role_policy.json + path = var.config.role_path + permissions_boundary = var.config.role_permissions_boundary + tags = var.config.tags +} + +resource "aws_iam_role_policy" "pool" { + name = "pool-policy" + role = aws_iam_role.pool.name + policy = data.aws_iam_policy_document.pool.json +} + +data "aws_iam_policy_document" "pool" { + source_policy_documents = [ + data.aws_iam_policy_document.pool_common.json, + var.runner_provider.iam_policy_json, + ] +} + +resource "aws_iam_role_policy" "pool_logging" { + name = "logging-policy" + role = aws_iam_role.pool.name + policy = data.aws_iam_policy_document.pool_logging.json +} + +resource "aws_iam_role_policy_attachment" "pool_vpc_execution_role" { + count = length(var.config.lambda.subnet_ids) > 0 ? 1 : 0 + role = aws_iam_role.pool.name + policy_arn = "arn:${var.aws_partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" +} + +data "aws_iam_policy_document" "lambda_assume_role_policy" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + + dynamic "principals" { + for_each = var.config.lambda.principals + + content { + type = principals.value.type + identifiers = principals.value.identifiers + } + } + } +} + +resource "aws_iam_role_policy_attachment" "provider" { + count = var.runner_provider.managed_policy_enabled ? 1 : 0 + role = aws_iam_role.pool.name + policy_arn = var.runner_provider.managed_policy_arn +} + +# AWS X-Ray write/read trace APIs do not support resource-level permissions. +data "aws_iam_policy_document" "lambda_xray" { + count = var.tracing_config.mode != null ? 1 : 0 + statement { + actions = [ + "xray:BatchGetTraces", + "xray:GetTraceSummaries", + "xray:PutTelemetryRecords", + "xray:PutTraceSegments" + ] + effect = "Allow" + resources = [ + "*" + ] + sid = "AllowXRay" + } +} + +resource "aws_iam_role_policy" "pool_xray" { + count = var.tracing_config.mode != null ? 1 : 0 + name = "xray-policy" + policy = data.aws_iam_policy_document.lambda_xray[0].json + role = aws_iam_role.pool.name +} + +resource "aws_scheduler_schedule_group" "pool" { + name_prefix = local.pool_name_prefix + + tags = var.config.tags +} + +data "aws_iam_policy_document" "scheduler_assume" { + statement { + sid = "ScheduleGroupAssumeRole" + actions = ["sts:AssumeRole"] + principals { + type = "Service" + identifiers = ["scheduler.amazonaws.com"] + } + + condition { + test = "StringEquals" + variable = "aws:SourceArn" + values = [aws_scheduler_schedule_group.pool.arn] + } + } +} + +data "aws_iam_policy_document" "scheduler" { + statement { + sid = "InvokePoolLambda" + actions = ["lambda:InvokeFunction"] + resources = [aws_lambda_function.pool.arn] + } +} + +resource "aws_iam_role" "scheduler" { + name_prefix = local.pool_name_prefix + + path = var.config.role_path + permissions_boundary = var.config.role_permissions_boundary + + assume_role_policy = data.aws_iam_policy_document.scheduler_assume.json + tags = var.config.tags +} + +resource "aws_iam_role_policy" "scheduler" { + name = "terraform" + role = aws_iam_role.scheduler.name + policy = data.aws_iam_policy_document.scheduler.json +} + +resource "aws_scheduler_schedule" "pool" { + for_each = { for i, v in var.config.pool : i => v } + + name = "${var.config.prefix}-pool-${each.key}-rule" + group_name = aws_scheduler_schedule_group.pool.name + + flexible_time_window { + mode = "OFF" + } + + schedule_expression = each.value.schedule_expression + schedule_expression_timezone = each.value.schedule_expression_timezone + + target { + arn = aws_lambda_function.pool.arn + role_arn = aws_iam_role.scheduler.arn + input = jsonencode({ + poolSize = each.value.size + type = var.runner_provider.type + }) + } +} diff --git a/modules/orchestration-providers/webhook/pool/tests/provider.tftest.hcl b/modules/orchestration-providers/webhook/pool/tests/provider.tftest.hcl new file mode 100644 index 0000000000..d65ca41b82 --- /dev/null +++ b/modules/orchestration-providers/webhook/pool/tests/provider.tftest.hcl @@ -0,0 +1,248 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"logs:CreateLogStream\",\"Resource\":\"*\"}]}" + } + } +} + +variables { + config = { + lambda = { + log_level = "info" + logging_retention_in_days = 14 + logging_kms_key_id = null + log_class = "STANDARD" + reserved_concurrent_executions = 1 + s3_bucket = "lambda-artifacts" + s3_key = "runners.zip" + s3_object_version = null + security_group_ids = [] + runtime = "nodejs24.x" + architecture = "arm64" + memory_size = 256 + timeout = 60 + zip = "runners.zip" + subnet_ids = [] + parameter_store_tags = "{}" + principals = [{ + type = "AWS" + identifiers = ["arn:aws:iam::123456789012:role/local-testing"] + }] + } + tags = { + Environment = "pool-test" + } + ghes = { + url = null + ssl_verify = true + } + github_app_parameters = { + key_base64 = [ + { + name = "/github-runner/key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" + }, + { + name = "/github-runner/key-base64-2" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64-2" + }, + ] + id = [ + { + name = "/github-runner/app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" + }, + { + name = "/github-runner/app-id-2" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id-2" + }, + ] + installation_id = [ + null, + { + name = "/github-runner/installation-id-2" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/installation-id-2" + }, + ] + } + runner = { + disable_runner_autoupdate = false + ephemeral = true + enable_jit_config = true + labels = ["self-hosted", "microvm"] + group_name = "default" + name_prefix = "microvm" + pool_owner = "example" + boot_time_in_minutes = 13 + } + runners_maximum_count = 10 + prefix = "pool-test" + pool = [{ + schedule_expression = "cron(0 8 * * ? *)" + schedule_expression_timezone = "UTC" + size = 2 + }] + include_busy_runners = false + role_permissions_boundary = null + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/pool-test" + role_path = "/" + ssm_token_path = "/github-runner/tokens" + ssm_token_path_arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/tokens" + ssm_config_path = "/github-runner/config" + arn_ssm_parameters_path_config = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/config" + lambda_tags = {} + user_agent = "terraform-aws-github-runner" + } + + runner_provider = { + type = "microvm" + environment_variables = { + MICROVM_CLUSTER = "runner-cluster" + } + iam_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Action = ["microvm:CreateRunner"] + Resource = ["*"] + }] + }) + managed_policy_enabled = true + managed_policy_arn = "arn:aws:iam::123456789012:policy/microvm-pool" + } + + tracing_config = { + mode = "Active" + capture_http_requests = true + capture_error = true + } +} + +run "provider_supplies_only_compute_specific_pool_configuration" { + command = plan + + assert { + condition = ( + length(data.aws_iam_policy_document.lambda_assume_role_policy.statement[0].principals) == 2 && + contains(data.aws_iam_policy_document.lambda_assume_role_policy.statement[0].principals[*].type, "AWS") + ) + error_message = "The pool Lambda trust policy must include configured additional principals." + } + + assert { + condition = toset(keys(output.pool)) == toset(["lambda", "log_group", "role"]) + error_message = "The pool module must expose its resources through one nested output." + } + + assert { + condition = ( + aws_lambda_function.pool.environment[0].variables["RUNNER_OWNER"] == "example" + && aws_lambda_function.pool.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "10" + && aws_lambda_function.pool.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "13" + ) + error_message = "The pool module must assemble common runner registration values and webhook-provider capacity and boot-time settings." + } + + assert { + condition = ( + aws_lambda_function.pool.environment[0].variables["PARAMETER_GITHUB_APP_ID_NAME"] == "/github-runner/app-id:/github-runner/app-id-2" + && aws_lambda_function.pool.environment[0].variables["PARAMETER_GITHUB_APP_KEY_BASE64_NAME"] == "/github-runner/key-base64:/github-runner/key-base64-2" + && aws_lambda_function.pool.environment[0].variables["PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME"] == ":/github-runner/installation-id-2" + && contains(data.aws_iam_policy_document.pool_common.statement[2].resources, "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id-2") + && contains(data.aws_iam_policy_document.pool_common.statement[2].resources, "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64-2") + && contains(data.aws_iam_policy_document.pool_common.statement[2].resources, "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/installation-id-2") + ) + error_message = "Pool must pass every GitHub App parameter and grant access to every corresponding SSM ARN." + } + + assert { + condition = aws_lambda_function.pool.environment[0].variables["MICROVM_CLUSTER"] == "runner-cluster" + error_message = "The pool module must merge compute-provider environment variables into the Lambda environment." + } + + assert { + condition = !contains(keys(aws_lambda_function.pool.environment[0].variables), "AMI_ID_SSM_PARAMETER_NAME") + error_message = "The common pool module must not add EC2-specific environment variables." + } + + assert { + condition = jsondecode(aws_scheduler_schedule.pool["0"].target[0].input).type == "microvm" + error_message = "The pool scheduler payload must select the configured compute provider." + } + + assert { + condition = length(data.aws_iam_policy_document.pool.source_policy_documents) == 2 + error_message = "The pool role policy must merge the common and compute-provider policy documents." + } + + assert { + condition = ( + length(data.aws_iam_policy_document.pool_common.statement) == 4 + && one([ + for statement in data.aws_iam_policy_document.pool_common.statement : statement + if statement.sid == "WebhookPoolDecryptParameterStore" + ]).resources == toset(["arn:aws:kms:eu-west-1:123456789012:key/pool-test"]) + ) + error_message = "The pool KMS policy statement must consume the scalar key ARN." + } + + assert { + condition = ( + one([ + for statement in data.aws_iam_policy_document.pool_common.statement : statement + if statement.sid == "WebhookPoolWriteRuntimeParameters" + ]).resources == toset([ + "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/tokens", + "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/tokens/*", + "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/config", + "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/config/*", + ]) + && !contains(one([ + for statement in data.aws_iam_policy_document.pool_common.statement : statement + if statement.sid == "WebhookPoolWriteRuntimeParameters" + ]).resources, "*") + ) + error_message = "The pool Lambda must scope runtime SSM writes to the token and runner-config parameter paths." + } + + assert { + condition = ( + data.aws_iam_policy_document.lambda_xray[0].statement[0].sid == "AllowXRay" + && data.aws_iam_policy_document.lambda_xray[0].statement[0].resources == toset(["*"]) + && toset(data.aws_iam_policy_document.lambda_xray[0].statement[0].actions) == toset([ + "xray:BatchGetTraces", + "xray:GetTraceSummaries", + "xray:PutTelemetryRecords", + "xray:PutTraceSegments", + ]) + ) + error_message = "Only the resource-agnostic X-Ray APIs may retain a wildcard resource in the pool policies." + } + + assert { + condition = length(aws_iam_role_policy_attachment.provider) == 1 + error_message = "The optional compute-provider managed policy must be attached to the pool role." + } +} + +run "omits_optional_kms_statement" { + command = plan + + variables { + config = merge(var.config, { + kms_key_id = null + }) + } + + assert { + condition = ( + length(data.aws_iam_policy_document.pool_common.statement) == 3 + && length([ + for statement in data.aws_iam_policy_document.pool_common.statement : statement + if anytrue([for action in statement.actions : startswith(action, "kms:")]) + ]) == 0 + ) + error_message = "A null Parameter Store key must omit the optional pool KMS statement." + } +} diff --git a/modules/orchestration-providers/webhook/pool/variables.tf b/modules/orchestration-providers/webhook/pool/variables.tf new file mode 100644 index 0000000000..6337b0ea5f --- /dev/null +++ b/modules/orchestration-providers/webhook/pool/variables.tf @@ -0,0 +1,176 @@ +variable "config" { + description = <<-EOF + Configuration passed from the webhook orchestration provider to the pool Lambda and scheduler. + + - `lambda`: Pool Lambda runtime and deployment configuration. + - `lambda.log_level`: Logging level used by the pool Lambda. + - `lambda.logging_retention_in_days`: Number of days to retain events in the pool Lambda log group. + - `lambda.logging_kms_key_id`: KMS key ID used to encrypt the pool Lambda log group. + - `lambda.log_class`: CloudWatch Logs class for the pool Lambda log group. + - `lambda.reserved_concurrent_executions`: Reserved concurrency for the pool Lambda. Use -1 for no reservation. + - `lambda.s3_bucket`: S3 bucket containing the pool Lambda deployment package. + - `lambda.s3_key`: S3 key of the pool Lambda deployment package. + - `lambda.s3_object_version`: S3 object version of the pool Lambda deployment package. + - `lambda.security_group_ids`: Security group IDs associated with the pool Lambda. + - `lambda.runtime`: AWS Lambda runtime used by the pool Lambda. + - `lambda.architecture`: AWS Lambda architecture used by the pool Lambda. + - `lambda.memory_size`: Memory allocated to the pool Lambda in MB. + - `lambda.timeout`: Pool Lambda timeout in seconds. + - `lambda.zip`: Local path to the pool Lambda deployment package when S3 is not used. + - `lambda.subnet_ids`: Subnet IDs in which the pool Lambda runs. + - `lambda.parameter_store_tags`: JSON-encoded tags supplied to the pool Lambda for SSM parameters it creates. + - `lambda.principals`: Additional principals allowed to assume the pool Lambda role. + - `tags`: Common tags added to pool resources. + - `ghes`: GitHub Enterprise Server connection configuration. + - `ghes.url`: GitHub Enterprise Server URL; null when using public GitHub. + - `ghes.ssl_verify`: Whether the pool Lambda verifies the GitHub Enterprise Server TLS certificate. + - `github_app_parameters`: Ordered SSM parameter metadata for GitHub App credentials. + - `github_app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys. + - `github_app_parameters.id`: Ordered Parameter Store references for GitHub App IDs. + - `github_app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs. + - `runner`: Runner registration configuration used by the pool Lambda. + - `runner.disable_runner_autoupdate`: Whether GitHub runner automatic updates are disabled. + - `runner.ephemeral`: Whether runners register as ephemeral runners. + - `runner.enable_jit_config`: Whether runners use just-in-time registration configuration. + - `runner.labels`: Labels assigned to runners created by the pool Lambda. + - `runner.group_name`: GitHub runner group assigned to runners created by the pool Lambda. + - `runner.name_prefix`: Prefix used for runner names. + - `runner.pool_owner`: GitHub organization or repository that owns the runner pool. + - `runner.boot_time_in_minutes`: Webhook-provider runner boot timeout used by pool reconciliation. + - `runners_maximum_count`: Webhook-provider runner capacity limit enforced by the pool Lambda. + - `prefix`: Prefix used to name pool resources. + - `pool`: Scheduled pool targets. + - `pool[*].schedule_expression`: EventBridge Scheduler expression for a pool target. + - `pool[*].schedule_expression_timezone`: Time zone used to evaluate the schedule expression. + - `pool[*].size`: Desired runner count for the scheduled pool target. + - `include_busy_runners`: Whether busy runners count toward the desired pool size. + - `role_permissions_boundary`: Permissions boundary applied to IAM roles created for the pool. + - `kms_key_id`: Optional customer-managed KMS key ARN that the pool Lambda may use to decrypt encrypted parameters. + - `role_path`: IAM path applied to roles created for the pool. + - `ssm_token_path`: SSM path under which runner registration tokens are stored. + - `ssm_token_path_arn`: ARN matching the runner registration-token SSM path. + - `ssm_config_path`: SSM path under which runner configuration is stored. + - `arn_ssm_parameters_path_config`: ARN matching the runner configuration SSM path. + - `lambda_tags`: Tags added specifically to the pool Lambda function, overriding common tags with the same key. + - `log_group_tags`: Tags added specifically to the pool Lambda log group, overriding common tags with the same key. + - `user_agent`: User-Agent header used for GitHub API requests. + EOF + type = object({ + lambda = object({ + log_level = string + logging_retention_in_days = number + logging_kms_key_id = string + log_class = string + reserved_concurrent_executions = number + s3_bucket = string + s3_key = string + s3_object_version = string + security_group_ids = list(string) + runtime = string + architecture = string + memory_size = number + timeout = number + zip = string + subnet_ids = list(string) + parameter_store_tags = string + principals = optional(list(object({ + type = string + identifiers = list(string) + })), []) + }) + tags = map(string) + ghes = object({ + url = string + ssl_verify = string + }) + github_app_parameters = object({ + key_base64 = list(map(string)) + id = list(map(string)) + installation_id = list(object({ name = string, arn = string })) + }) + runner = object({ + disable_runner_autoupdate = bool + ephemeral = bool + enable_jit_config = bool + labels = list(string) + group_name = string + name_prefix = string + pool_owner = string + boot_time_in_minutes = number + }) + runners_maximum_count = number + prefix = string + pool = list(object({ + schedule_expression = string + schedule_expression_timezone = string + size = number + })) + include_busy_runners = bool + role_permissions_boundary = string + kms_key_id = optional(string, null) + role_path = string + ssm_token_path = string + ssm_token_path_arn = string + ssm_config_path = string + arn_ssm_parameters_path_config = string + lambda_tags = map(string) + log_group_tags = optional(map(string), {}) + user_agent = string + }) +} + +variable "runner_provider" { + description = <<-EOF + Compute provider integration used by the pool Lambda. + + - `type`: Compute provider type passed to scheduled pool invocations. + - `environment_variables`: Provider-specific environment variables added to the pool Lambda. + - `iam_policy_json`: Provider-specific IAM policy document merged into the pool Lambda policy. + - `managed_policy_enabled`: Whether to attach a provider-specific managed IAM policy to the pool Lambda role. + - `managed_policy_arn`: ARN of the provider-specific managed IAM policy to attach when enabled. + EOF + type = object({ + type = string + environment_variables = map(string) + iam_policy_json = string + managed_policy_enabled = bool + managed_policy_arn = optional(string, null) + }) + + validation { + condition = trimspace(var.runner_provider.type) != "" + error_message = "The compute provider type must not be empty." + } + + validation { + condition = can(jsondecode(var.runner_provider.iam_policy_json)) + error_message = "The compute provider IAM policy must be valid JSON." + } + + validation { + condition = !var.runner_provider.managed_policy_enabled || var.runner_provider.managed_policy_arn != null + error_message = "The compute provider managed policy ARN must be set when its attachment is enabled." + } +} + +variable "aws_partition" { + description = "(optional) partition for the arn if not 'aws'" + type = string + default = "aws" +} + +variable "tracing_config" { + description = <<-EOF + Tracing configuration for the pool Lambda. + + - `mode`: AWS X-Ray tracing mode. A null value disables tracing. + - `capture_http_requests`: Whether Powertools tracing captures outgoing HTTP requests. + - `capture_error`: Whether Powertools tracing captures errors as tracing metadata. + EOF + type = object({ + mode = optional(string, null) + capture_http_requests = optional(bool, false) + capture_error = optional(bool, false) + }) + default = {} +} diff --git a/modules/orchestration-providers/webhook/pool/versions.tf b/modules/orchestration-providers/webhook/pool/versions.tf new file mode 100644 index 0000000000..42a40b33fd --- /dev/null +++ b/modules/orchestration-providers/webhook/pool/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.21" + } + } +} diff --git a/modules/orchestration-providers/webhook/scale-down-state-diagram.md b/modules/orchestration-providers/webhook/scale-down-state-diagram.md new file mode 100644 index 0000000000..dec780cfbf --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-down-state-diagram.md @@ -0,0 +1,150 @@ +# GitHub Actions Runner Scale-Down State Diagram + + + +The scale-down Lambda function runs on a scheduled basis (every 5 minutes by default) to manage GitHub Actions runner instances. It performs a two-phase cleanup process: first terminating confirmed orphaned instances, then evaluating active runners to maintain the desired idle capacity while removing unnecessary instances. + +```mermaid +stateDiagram-v2 + [*] --> ScheduledExecution : Cron Trigger every 5 min + + ScheduledExecution --> Phase1_OrphanTermination : Start Phase 1 + + state Phase1_OrphanTermination { + [*] --> ListOrphanInstances : Query EC2 for ghr orphan true + + ListOrphanInstances --> CheckOrphanType : For each orphan + + state CheckOrphanType <> + CheckOrphanType --> HasRunnerIdTag : Has ghr github runner id + CheckOrphanType --> TerminateOrphan : No runner ID tag + + HasRunnerIdTag --> LastChanceCheck : Query GitHub API + + state LastChanceCheck <> + LastChanceCheck --> ConfirmedOrphan : Offline and busy + LastChanceCheck --> FalsePositive : Exists and not problematic + + ConfirmedOrphan --> TerminateOrphan + FalsePositive --> RemoveOrphanTag + + TerminateOrphan --> NextOrphan : Continue processing + RemoveOrphanTag --> NextOrphan + + NextOrphan --> CheckOrphanType : More orphans? + NextOrphan --> Phase2_ActiveRunners : All processed + } + + Phase1_OrphanTermination --> Phase2_ActiveRunners : Phase 1 Complete + + state Phase2_ActiveRunners { + [*] --> ListActiveRunners : Query non-orphan EC2 instances + + ListActiveRunners --> GroupByOwner : Sort by owner and repo + + GroupByOwner --> ProcessOwnerGroup : For each owner + + state ProcessOwnerGroup { + [*] --> SortByStrategy : Apply eviction strategy + SortByStrategy --> ProcessRunner : Oldest first or newest first + + ProcessRunner --> QueryGitHub : Get GitHub runners for owner + + QueryGitHub --> MatchRunner : Find runner by instance ID suffix + + state MatchRunner <> + MatchRunner --> FoundInGitHub : Runner exists in GitHub + MatchRunner --> NotFoundInGitHub : Runner not in GitHub + + state FoundInGitHub { + [*] --> CheckMinimumTime : Has minimum runtime passed? + + state CheckMinimumTime <> + CheckMinimumTime --> TooYoung : Runtime less than minimum + CheckMinimumTime --> CheckIdleQuota : Runtime greater than or equal to minimum + + TooYoung --> NextRunner + + state CheckIdleQuota <> + CheckIdleQuota --> KeepIdle : Idle quota available + CheckIdleQuota --> CheckBusyState : Quota full + + KeepIdle --> NextRunner + + state CheckBusyState <> + CheckBusyState --> KeepBusy : Runner busy + CheckBusyState --> TerminateIdle : Runner idle + + KeepBusy --> NextRunner + TerminateIdle --> DeregisterFromGitHub + DeregisterFromGitHub --> TerminateInstance + TerminateInstance --> NextRunner + } + + state NotFoundInGitHub { + [*] --> CheckBootTime : Has boot time exceeded? + + state CheckBootTime <> + CheckBootTime --> StillBooting : Boot time less than threshold + CheckBootTime --> MarkOrphan : Boot time greater than or equal to threshold + + StillBooting --> NextRunner + MarkOrphan --> TagAsOrphan : Set ghr orphan true + TagAsOrphan --> NextRunner + } + + NextRunner --> ProcessRunner : More runners in group? + NextRunner --> NextOwnerGroup : Group complete + } + + NextOwnerGroup --> ProcessOwnerGroup : More owner groups? + NextOwnerGroup --> ExecutionComplete : All groups processed + } + + Phase2_ActiveRunners --> ExecutionComplete : Phase 2 Complete + + ExecutionComplete --> [*] : Wait for next cron trigger + + note right of LastChanceCheck + Uses ghr github runner id tag + for precise GitHub API lookup + end note + + note right of MatchRunner + Matches GitHub runner name + ending with EC2 instance ID + end note + + note right of CheckMinimumTime + Minimum running time in minutes + (Linux: 5min, Windows: 15min, OSX: 20min) + end note + + note right of CheckBootTime + Runner boot time in minutes + Default configuration value + end note +``` + + + +## Key Decision Points + +| State | Condition | Action | +|-------|-----------|--------| +| **Orphan w/ Runner ID** | GitHub: offline + busy | Terminate (confirmed orphan) | +| **Orphan w/ Runner ID** | GitHub: exists + healthy | Remove orphan tag (false positive) | +| **Orphan w/o Runner ID** | Always | Terminate (no way to verify) | +| **Active Runner Found** | Runtime < minimum | Keep (too young) | +| **Active Runner Found** | Idle quota available | Keep as idle | +| **Active Runner Found** | Quota full + idle | Terminate + deregister | +| **Active Runner Found** | Quota full + busy | Keep running | +| **Active Runner Missing** | Boot time exceeded | Mark as orphan | +| **Active Runner Missing** | Still booting | Wait | + +## Configuration Parameters + +- **Cron Schedule**: `cron(*/5 * * * ? *)` (every 5 minutes) +- **Minimum Runtime**: Linux 5min, Windows 15min, OSX 20min +- **Boot Timeout**: Configurable via `orchestration.webhook.runner.boot_time_in_minutes`; stable-v1 inputs are translated from `runner_boot_time_in_minutes`. +- **Idle Config**: Per-environment configuration for desired idle runners diff --git a/modules/orchestration-providers/webhook/scale-runners.tf b/modules/orchestration-providers/webhook/scale-runners.tf new file mode 100644 index 0000000000..caf79eefb5 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners.tf @@ -0,0 +1,61 @@ +module "scale_runners" { + source = "./scale-runners" + + aws_partition = var.aws_partition + + config = { + prefix = local.resolved_config.prefix + lambda = { + artifact = local.resolved_config.lambda.artifact + runtime = local.resolved_config.lambda.runtime + architecture = local.resolved_config.lambda.architecture + vpc = { + subnet_ids = local.resolved_config.lambda.subnet_ids + security_group_ids = local.resolved_config.lambda.security_group_ids + } + role = local.resolved_config.lambda.role + } + runner = local.resolved_config.runner + github = local.resolved_config.github + queue = { + build = local.resolved_config.queue.build + kms_key_id = local.resolved_config.queue.kms_key_id + event_source_mapping = local.resolved_config.queue.event_source_mapping + } + ssm = local.resolved_config.ssm + observability = { + logs = local.resolved_config.observability.logs + tracing = local.resolved_config.observability.tracing + metrics = local.resolved_config.observability.metrics + } + scale_up = merge(local.resolved_config.scale_up, { + job_queued_check_enabled = local.enable_job_queued_check + tags = { + resources = local.scale_up_tags + lambda = local.scale_up_lambda_tags + log_group = local.scale_up_log_tags + event_source_mapping = local.scale_up_queue_tags + } + }) + scale_down = merge(local.resolved_config.scale_down, { + tags = { + resources = local.scale_down_tags + lambda = local.scale_down_lambda_tags + log_group = local.scale_down_log_tags + } + }) + job_retry = { + enabled = local.job_retry_enabled + max_attempts = local.resolved_config.job_retry.max_attempts + delay_in_seconds = local.resolved_config.job_retry.delay_in_seconds + delay_backoff = local.resolved_config.job_retry.delay_backoff + queue = one(module.job_retry[*].job_retry_check_queue) + } + } + + runner_provider = { + type = var.runner_provider.type + scale_up = var.runner_provider.scale_up + scale_down = var.runner_provider.scale_down + } +} diff --git a/modules/orchestration-providers/webhook/scale-runners/README.md b/modules/orchestration-providers/webhook/scale-runners/README.md new file mode 100644 index 0000000000..bcb6065b25 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/README.md @@ -0,0 +1,77 @@ +# Scale runners module + +> This module is treated as an internal module; breaking changes do not trigger a major release bump. + +This provider-neutral child module owns the scale-up and scale-down Lambda functions, their event sources and schedules, and their IAM and logging resources. `runner-config` supplies common configuration through the webhook orchestration provider together with the selected compute provider's environment and IAM fragments. + +The module is an implementation detail of the experimental runner configuration. It is composed by the webhook orchestration provider and is not intended to be called directly. + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 6.33 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.33 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_event_rule.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_rule) | resource | +| [aws_cloudwatch_event_target.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_target) | resource | +| [aws_cloudwatch_log_group.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_cloudwatch_log_group.scale_up](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_iam_role.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role.scale_up](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy.job_retry_sqs_publish](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.scale_down_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.scale_down_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.scale_up](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.scale_up_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.scale_up_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.service_linked_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy_attachment.provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_iam_role_policy_attachment.scale_down_vpc_execution_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_iam_role_policy_attachment.scale_up_vpc_execution_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_lambda_event_source_mapping.scale_up](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_event_source_mapping) | resource | +| [aws_lambda_function.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | +| [aws_lambda_function.scale_up](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | +| [aws_lambda_permission.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource | +| [aws_lambda_permission.scale_runners_lambda](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource | +| [aws_iam_policy_document.lambda_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.lambda_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_down](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_down_common](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_down_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_up](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_up_common](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_up_job_retry_publish](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.scale_up_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [aws\_partition](#input\_aws\_partition) | AWS partition used to construct IAM policy ARNs. | `string` | `"aws"` | no | +| [config](#input\_config) | Provider-neutral scale-up and scale-down configuration assembled by runner-config.

- `prefix`: Prefix used to name scaling resources.
- `lambda.artifact.zip`: Resolved local control-plane archive.
- `lambda.artifact.s3.bucket`: Optional S3 bucket containing the Lambda archive.
- `lambda.artifact.s3.key`: Object key of the Lambda archive.
- `lambda.artifact.s3.object_version`: Optional object version of the Lambda archive.
- `lambda.runtime`: Runtime used by both scaling Lambdas.
- `lambda.architecture`: Instruction-set architecture used by both scaling Lambdas.
- `lambda.vpc.subnet_ids`: Subnets used for Lambda VPC configuration.
- `lambda.vpc.security_group_ids`: Security groups used for Lambda VPC configuration.
- `lambda.role.path`: IAM path used for the scaling Lambda roles.
- `lambda.role.permissions_boundary`: Optional permissions boundary for the scaling Lambda roles.
- `lambda.role.principals`: Additional principals allowed to assume the scaling Lambda roles.
- `runner.os`: Runner operating system used for the minimum-runtime default.
- `runner.auto_update_disabled`: Disables the GitHub runner application's built-in updater.
- `runner.ephemeral`: Registers runners in ephemeral mode.
- `runner.jit_config_enabled`: Enables or disables just-in-time runner configuration.
- `runner.labels`: Labels supplied when a runner is registered.
- `runner.group_name`: GitHub runner group used during registration.
- `runner.name_prefix`: Prefix added to registered runner names.
- `runner.boot_time_in_minutes`: Webhook-provider runner boot timeout used by scale-down.
- `runner.maximum_count`: Webhook-provider runner capacity limit for this runner configuration.
- `github.organization_runners`: Registers organization runners when true.
- `github.enterprise_server.url`: Optional GitHub Enterprise Server URL.
- `github.enterprise_server.ssl_verify`: Enables TLS verification for GitHub Enterprise Server.
- `github.user_agent`: Optional User-Agent sent to GitHub.
- `github.app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys.
- `github.app_parameters.id`: Ordered Parameter Store references for GitHub App IDs.
- `github.app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs.
- `queue.build.arn`: ARN of the build queue consumed by scale-up.
- `queue.kms_key_id`: Optional KMS key ARN used to encrypt the build queue. This is distinct from the Parameter Store key.
- `queue.event_source_mapping.batch_size`: Maximum records delivered per scale-up invocation.
- `queue.event_source_mapping.maximum_batching_window_in_seconds`: Maximum event batching window.
- `ssm.token_path`: Parameter Store path used for registration tokens.
- `ssm.token_path_arn`: ARN of the Parameter Store path used for registration tokens.
- `ssm.config_path`: Parameter Store path used for persistent runner configuration.
- `ssm.config_path_arn`: ARN of the persistent runner configuration path.
- `ssm.kms_key_id`: Optional KMS key ARN used to decrypt shared parameters. Its value may be unknown until apply.
- `ssm.parameter_store_tags`: JSON-encoded tags applied to parameters created at runtime.
- `observability.logs`: Shared logging level, retention, encryption, and log-class configuration.
- `observability.tracing`: Lambda X-Ray and tracing-helper configuration.
- `observability.metrics`: Metrics enablement, namespace, and GitHub rate-limit metric configuration.
- `scale_up`: Scale-up Lambda sizing, concurrency, queued-job behavior, and resolved resource tag maps.
- `scale_up.tags.resources`: Tags for the scale-up IAM role and other component resources.
- `scale_up.tags.lambda`: Tags for the scale-up Lambda function.
- `scale_up.tags.log_group`: Tags for the scale-up log group.
- `scale_up.tags.event_source_mapping`: Tags for the build-queue event-source mapping.
- `scale_down`: Scale-down Lambda sizing, schedule, idle configuration, minimum runtime, and resolved resource tag maps.
- `scale_down.tags.resources`: Tags for the scale-down IAM role and EventBridge rule.
- `scale_down.tags.lambda`: Tags for the scale-down Lambda function.
- `scale_down.tags.log_group`: Tags for the scale-down log group.
- `job_retry.enabled`: Enables publishing retry checks from scale-up.
- `job_retry.queue`: Retry queue ARN and URL. Required when job retry is enabled.
- `job_retry.max_attempts`: Maximum queued-job retry attempts.
- `job_retry.delay_in_seconds`: Initial delay before checking the queued job.
- `job_retry.delay_backoff`: Multiplier applied to subsequent delays. |
object({
prefix = string
lambda = object({
artifact = object({
zip = string
s3 = object({
bucket = optional(string, null)
key = optional(string, null)
object_version = optional(string, null)
})
})
runtime = string
architecture = string
vpc = object({
subnet_ids = list(string)
security_group_ids = list(string)
})
role = object({
path = string
permissions_boundary = optional(string, null)
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
})
})
runner = object({
os = string
auto_update_disabled = bool
ephemeral = bool
jit_config_enabled = optional(bool, null)
labels = list(string)
group_name = string
name_prefix = string
boot_time_in_minutes = number
maximum_count = number
})
github = object({
organization_runners = bool
enterprise_server = object({
url = optional(string, null)
ssl_verify = bool
})
user_agent = optional(string, null)
app_parameters = object({
key_base64 = list(map(string))
id = list(map(string))
installation_id = list(object({ name = string, arn = string }))
})
})
queue = object({
build = object({
arn = string
})
kms_key_id = optional(string, null)
event_source_mapping = object({
batch_size = number
maximum_batching_window_in_seconds = number
})
})
ssm = object({
token_path = string
token_path_arn = string
config_path = string
config_path_arn = string
parameter_store_tags = string
kms_key_id = optional(string, null)
})
observability = object({
logs = object({
level = string
retention_in_days = number
kms_key_id = optional(string, null)
class = string
})
tracing = object({
mode = optional(string, null)
capture_http_requests = bool
capture_error = bool
})
metrics = object({
enable = bool
namespace = string
metric = object({
enable_github_app_rate_limit = bool
})
})
})
scale_up = object({
memory_size = number
timeout = number
reserved_concurrent_executions = number
job_queued_check_enabled = bool
tags = object({
resources = map(string)
lambda = map(string)
log_group = map(string)
event_source_mapping = map(string)
})
})
scale_down = object({
memory_size = number
timeout = number
schedule_expression = string
minimum_running_time_in_minutes = optional(number, null)
idle_config = list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = string
}))
tags = object({
resources = map(string)
lambda = map(string)
log_group = map(string)
})
})
job_retry = object({
enabled = bool
max_attempts = number
delay_in_seconds = number
delay_backoff = number
queue = optional(object({
arn = string
url = string
}), null)
})
})
| n/a | yes | +| [runner\_provider](#input\_runner\_provider) | Selected compute-provider integration for the scaling control plane.

- `type`: Compute-provider discriminator supplied to both Lambdas.
- `scale_up.environment_variables`: Provider-specific scale-up environment variables.
- `scale_up.iam_policy_json`: Provider-specific IAM policy merged into the common scale-up policy.
- `scale_up.additional_iam_policy_json`: Optional additional provider policy attached separately to the scale-up role.
- `scale_up.managed_policy`: Optional provider-managed policy attachment. Object presence controls attachment creation.
- `scale_up.managed_policy.arn`: ARN of the provider-managed policy. The ARN may remain unknown until apply.
- `scale_down.environment_variables`: Provider-specific scale-down environment variables.
- `scale_down.iam_policy_json`: Provider-specific IAM policy merged into the common scale-down policy. |
object({
type = string
scale_up = object({
environment_variables = map(string)
iam_policy_json = string
additional_iam_policy_json = optional(string, null)
managed_policy = optional(object({
arn = string
}), null)
})
scale_down = object({
environment_variables = map(string)
iam_policy_json = string
})
})
| n/a | yes | + +## Outputs + +| Name | Description | +|------|-------------| +| [scale\_down](#output\_scale\_down) | Scale-down Lambda resources. | +| [scale\_up](#output\_scale\_up) | Scale-up Lambda resources. | + diff --git a/modules/orchestration-providers/webhook/scale-runners/common-config.tf b/modules/orchestration-providers/webhook/scale-runners/common-config.tf new file mode 100644 index 0000000000..7c8a04d095 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/common-config.tf @@ -0,0 +1,20 @@ +locals { + vpc_enabled = ( + length(var.config.lambda.vpc.subnet_ids) > 0 && + length(var.config.lambda.vpc.security_group_ids) > 0 + ) + + job_retry_config = var.config.job_retry.enabled ? { + enable = true + maxAttempts = var.config.job_retry.max_attempts + delayInSeconds = var.config.job_retry.delay_in_seconds + delayBackoff = var.config.job_retry.delay_backoff + queueUrl = var.config.job_retry.queue.url + } : {} + + min_runtime_defaults = { + windows = 15 + linux = 5 + osx = 20 + } +} diff --git a/modules/orchestration-providers/webhook/scale-runners/lambda-iam-policies.tf b/modules/orchestration-providers/webhook/scale-runners/lambda-iam-policies.tf new file mode 100644 index 0000000000..0c9214d0d3 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/lambda-iam-policies.tf @@ -0,0 +1,36 @@ +data "aws_iam_policy_document" "lambda_assume_role" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + + dynamic "principals" { + for_each = var.config.lambda.role.principals + + content { + type = principals.value.type + identifiers = principals.value.identifiers + } + } + } +} + +data "aws_iam_policy_document" "lambda_xray" { + count = var.config.observability.tracing.mode != null ? 1 : 0 + + # AWS X-Ray write/read trace APIs do not support resource-level permissions. + statement { + sid = "AllowXRay" + effect = "Allow" + actions = [ + "xray:BatchGetTraces", + "xray:GetTraceSummaries", + "xray:PutTelemetryRecords", + "xray:PutTraceSegments", + ] + resources = ["*"] + } +} diff --git a/modules/orchestration-providers/webhook/scale-runners/outputs.tf b/modules/orchestration-providers/webhook/scale-runners/outputs.tf new file mode 100644 index 0000000000..74d54d2101 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/outputs.tf @@ -0,0 +1,17 @@ +output "scale_up" { + description = "Scale-up Lambda resources." + value = { + lambda = aws_lambda_function.scale_up + log_group = aws_cloudwatch_log_group.scale_up + role = aws_iam_role.scale_up + } +} + +output "scale_down" { + description = "Scale-down Lambda resources." + value = { + lambda = aws_lambda_function.scale_down + log_group = aws_cloudwatch_log_group.scale_down + role = aws_iam_role.scale_down + } +} diff --git a/modules/orchestration-providers/webhook/scale-runners/scale-down-iam-policies.tf b/modules/orchestration-providers/webhook/scale-runners/scale-down-iam-policies.tf new file mode 100644 index 0000000000..b95cb9e686 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/scale-down-iam-policies.tf @@ -0,0 +1,46 @@ +data "aws_iam_policy_document" "scale_down_common" { + statement { + sid = "WebhookScaleDownReadGitHubAppParameters" + effect = "Allow" + actions = [ + "ssm:GetParameter", + "ssm:GetParameters", + ] + resources = concat( + [for p in var.config.github.app_parameters.id : p.arn], + [for p in var.config.github.app_parameters.key_base64 : p.arn], + [for p in var.config.github.app_parameters.installation_id : p.arn if p != null], + ) + } + + dynamic "statement" { + for_each = var.config.ssm.kms_key_id == null ? [] : [var.config.ssm.kms_key_id] + iterator = kms_key + + content { + sid = "WebhookScaleDownDecryptParameterStore" + effect = "Allow" + actions = ["kms:Decrypt"] + resources = [kms_key.value] + } + } +} + +data "aws_iam_policy_document" "scale_down" { + source_policy_documents = [ + data.aws_iam_policy_document.scale_down_common.json, + var.runner_provider.scale_down.iam_policy_json, + ] +} + +data "aws_iam_policy_document" "scale_down_logging" { + statement { + sid = "WebhookScaleDownWriteLogs" + effect = "Allow" + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + ] + resources = ["${aws_cloudwatch_log_group.scale_down.arn}*"] + } +} diff --git a/modules/orchestration-providers/webhook/scale-runners/scale-down.tf b/modules/orchestration-providers/webhook/scale-runners/scale-down.tf new file mode 100644 index 0000000000..4951363bc9 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/scale-down.tf @@ -0,0 +1,116 @@ +resource "aws_lambda_function" "scale_down" { + s3_bucket = var.config.lambda.artifact.s3.bucket + s3_key = var.config.lambda.artifact.s3.key + s3_object_version = var.config.lambda.artifact.s3.object_version + filename = var.config.lambda.artifact.s3.bucket == null ? var.config.lambda.artifact.zip : null + source_code_hash = var.config.lambda.artifact.s3.bucket == null ? filebase64sha256(var.config.lambda.artifact.zip) : null + function_name = "${var.config.prefix}-scale-down" + role = aws_iam_role.scale_down.arn + handler = "index.scaleDownHandler" + runtime = var.config.lambda.runtime + timeout = var.config.scale_down.timeout + tags = var.config.scale_down.tags.lambda + memory_size = var.config.scale_down.memory_size + architectures = [var.config.lambda.architecture] + + environment { + variables = merge(var.runner_provider.scale_down.environment_variables, { + ENVIRONMENT = var.config.prefix + ENABLE_METRIC_GITHUB_APP_RATE_LIMIT = var.config.observability.metrics.enable && var.config.observability.metrics.metric.enable_github_app_rate_limit + GHES_URL = var.config.github.enterprise_server.url + USER_AGENT = var.config.github.user_agent + LOG_LEVEL = upper(var.config.observability.logs.level) + MINIMUM_RUNNING_TIME_IN_MINUTES = coalesce(var.config.scale_down.minimum_running_time_in_minutes, local.min_runtime_defaults[var.config.runner.os]) + NODE_TLS_REJECT_UNAUTHORIZED = var.config.github.enterprise_server.url != null && !var.config.github.enterprise_server.ssl_verify ? 0 : 1 + PARAMETER_GITHUB_APP_ID_NAME = join(":", [for p in var.config.github.app_parameters.id : p.name]) + PARAMETER_GITHUB_APP_KEY_BASE64_NAME = join(":", [for p in var.config.github.app_parameters.key_base64 : p.name]) + PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = join(":", [for p in var.config.github.app_parameters.installation_id : p != null ? p.name : ""]) + POWERTOOLS_LOGGER_LOG_EVENT = var.config.observability.logs.level == "debug" ? "true" : "false" + SCALE_DOWN_CONFIG = jsonencode(var.config.scale_down.idle_config) + POWERTOOLS_SERVICE_NAME = "${var.config.prefix}-scale-down" + POWERTOOLS_METRICS_NAMESPACE = var.config.observability.metrics.namespace + POWERTOOLS_TRACE_ENABLED = var.config.observability.tracing.mode != null + POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS = var.config.observability.tracing.capture_http_requests + POWERTOOLS_TRACER_CAPTURE_ERROR = var.config.observability.tracing.capture_error + COMPUTE_PROVIDER_TYPE = var.runner_provider.type + RUNNER_BOOT_TIME_IN_MINUTES = var.config.runner.boot_time_in_minutes + }) + } + + dynamic "vpc_config" { + for_each = local.vpc_enabled ? [true] : [] + + content { + security_group_ids = var.config.lambda.vpc.security_group_ids + subnet_ids = var.config.lambda.vpc.subnet_ids + } + } + + dynamic "tracing_config" { + for_each = var.config.observability.tracing.mode != null ? [true] : [] + + content { + mode = var.config.observability.tracing.mode + } + } +} + +resource "aws_cloudwatch_log_group" "scale_down" { + name = "/aws/lambda/${aws_lambda_function.scale_down.function_name}" + retention_in_days = var.config.observability.logs.retention_in_days + kms_key_id = var.config.observability.logs.kms_key_id + log_group_class = var.config.observability.logs.class + tags = var.config.scale_down.tags.log_group +} + +resource "aws_cloudwatch_event_rule" "scale_down" { + name = "${var.config.prefix}-scale-down-rule" + schedule_expression = var.config.scale_down.schedule_expression + tags = var.config.scale_down.tags.resources +} + +resource "aws_cloudwatch_event_target" "scale_down" { + rule = aws_cloudwatch_event_rule.scale_down.name + arn = aws_lambda_function.scale_down.arn +} + +resource "aws_lambda_permission" "scale_down" { + statement_id = "AllowExecutionFromCloudWatch" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.scale_down.function_name + principal = "events.amazonaws.com" + source_arn = aws_cloudwatch_event_rule.scale_down.arn +} + +resource "aws_iam_role" "scale_down" { + name = "${substr("${var.config.prefix}-scale-down-lambda", 0, 54)}-${substr(md5("${var.config.prefix}-scale-down-lambda"), 0, 8)}" + assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json + path = var.config.lambda.role.path + permissions_boundary = var.config.lambda.role.permissions_boundary + tags = var.config.scale_down.tags.resources +} + +resource "aws_iam_role_policy" "scale_down" { + name = "scale-down-policy" + role = aws_iam_role.scale_down.name + policy = data.aws_iam_policy_document.scale_down.json +} + +resource "aws_iam_role_policy" "scale_down_logging" { + name = "logging-policy" + role = aws_iam_role.scale_down.name + policy = data.aws_iam_policy_document.scale_down_logging.json +} + +resource "aws_iam_role_policy_attachment" "scale_down_vpc_execution_role" { + count = local.vpc_enabled ? 1 : 0 + role = aws_iam_role.scale_down.name + policy_arn = "arn:${var.aws_partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" +} + +resource "aws_iam_role_policy" "scale_down_xray" { + count = var.config.observability.tracing.mode != null ? 1 : 0 + name = "xray-policy" + policy = data.aws_iam_policy_document.lambda_xray[0].json + role = aws_iam_role.scale_down.name +} diff --git a/modules/orchestration-providers/webhook/scale-runners/scale-up-iam-policies.tf b/modules/orchestration-providers/webhook/scale-runners/scale-up-iam-policies.tf new file mode 100644 index 0000000000..b3c87b8ad7 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/scale-up-iam-policies.tf @@ -0,0 +1,102 @@ +data "aws_iam_policy_document" "scale_up_common" { + statement { + sid = "WebhookScaleUpWriteRuntimeParameters" + effect = "Allow" + actions = [ + "ssm:PutParameter", + "ssm:AddTagsToResource", + ] + resources = [ + var.config.ssm.token_path_arn, + "${var.config.ssm.token_path_arn}/*", + var.config.ssm.config_path_arn, + "${var.config.ssm.config_path_arn}/*", + ] + } + + statement { + sid = "WebhookScaleUpReadGitHubAppAndRunnerConfigParameters" + effect = "Allow" + actions = [ + "ssm:GetParameter", + "ssm:GetParameters", + ] + resources = concat( + [for p in var.config.github.app_parameters.id : p.arn], + [for p in var.config.github.app_parameters.key_base64 : p.arn], + [for p in var.config.github.app_parameters.installation_id : p.arn if p != null], + [ + var.config.ssm.config_path_arn, + "${var.config.ssm.config_path_arn}/*", + ], + ) + } + + statement { + sid = "WebhookScaleUpConsumeBuildQueue" + effect = "Allow" + actions = [ + "sqs:ReceiveMessage", + "sqs:GetQueueAttributes", + "sqs:DeleteMessage", + ] + resources = [var.config.queue.build.arn] + } + + dynamic "statement" { + for_each = var.config.ssm.kms_key_id == null ? [] : [var.config.ssm.kms_key_id] + iterator = kms_key + + content { + sid = "WebhookScaleUpDecryptParameterStore" + effect = "Allow" + actions = ["kms:Decrypt"] + resources = [kms_key.value] + } + } + + dynamic "statement" { + for_each = var.config.queue.kms_key_id == null ? [] : [var.config.queue.kms_key_id] + iterator = kms_key + + content { + sid = "WebhookScaleUpDecryptBuildQueue" + effect = "Allow" + actions = ["kms:Decrypt"] + resources = [kms_key.value] + } + } +} + +data "aws_iam_policy_document" "scale_up" { + source_policy_documents = [ + data.aws_iam_policy_document.scale_up_common.json, + var.runner_provider.scale_up.iam_policy_json, + ] +} + +data "aws_iam_policy_document" "scale_up_logging" { + statement { + sid = "WebhookScaleUpWriteLogs" + effect = "Allow" + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + ] + resources = ["${aws_cloudwatch_log_group.scale_up.arn}*"] + } +} + +data "aws_iam_policy_document" "scale_up_job_retry_publish" { + count = var.config.job_retry.enabled ? 1 : 0 + + statement { + sid = "WebhookScaleUpPublishJobRetryQueue" + effect = "Allow" + actions = [ + "sqs:SendMessage", + "sqs:GetQueueAttributes", + ] + resources = [var.config.job_retry.queue.arn] + } +} diff --git a/modules/orchestration-providers/webhook/scale-runners/scale-up.tf b/modules/orchestration-providers/webhook/scale-runners/scale-up.tf new file mode 100644 index 0000000000..92dfa4267a --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/scale-up.tf @@ -0,0 +1,146 @@ +resource "aws_lambda_function" "scale_up" { + s3_bucket = var.config.lambda.artifact.s3.bucket + s3_key = var.config.lambda.artifact.s3.key + s3_object_version = var.config.lambda.artifact.s3.object_version + filename = var.config.lambda.artifact.s3.bucket == null ? var.config.lambda.artifact.zip : null + source_code_hash = var.config.lambda.artifact.s3.bucket == null ? filebase64sha256(var.config.lambda.artifact.zip) : null + function_name = "${var.config.prefix}-scale-up" + role = aws_iam_role.scale_up.arn + handler = "index.scaleUpHandler" + runtime = var.config.lambda.runtime + timeout = var.config.scale_up.timeout + reserved_concurrent_executions = var.config.scale_up.reserved_concurrent_executions + memory_size = var.config.scale_up.memory_size + tags = var.config.scale_up.tags.lambda + architectures = [var.config.lambda.architecture] + + environment { + variables = merge(var.runner_provider.scale_up.environment_variables, { + DISABLE_RUNNER_AUTOUPDATE = var.config.runner.auto_update_disabled + ENABLE_EPHEMERAL_RUNNERS = var.config.runner.ephemeral + ENABLE_JIT_CONFIG = var.config.runner.jit_config_enabled + ENABLE_JOB_QUEUED_CHECK = var.config.scale_up.job_queued_check_enabled + ENABLE_METRIC_GITHUB_APP_RATE_LIMIT = var.config.observability.metrics.enable && var.config.observability.metrics.metric.enable_github_app_rate_limit + ENABLE_ORGANIZATION_RUNNERS = var.config.github.organization_runners + ENVIRONMENT = var.config.prefix + GHES_URL = var.config.github.enterprise_server.url + USER_AGENT = var.config.github.user_agent + LOG_LEVEL = upper(var.config.observability.logs.level) + MINIMUM_RUNNING_TIME_IN_MINUTES = coalesce(var.config.scale_down.minimum_running_time_in_minutes, local.min_runtime_defaults[var.config.runner.os]) + NODE_TLS_REJECT_UNAUTHORIZED = var.config.github.enterprise_server.url != null && !var.config.github.enterprise_server.ssl_verify ? 0 : 1 + PARAMETER_GITHUB_APP_ID_NAME = join(":", [for p in var.config.github.app_parameters.id : p.name]) + PARAMETER_GITHUB_APP_KEY_BASE64_NAME = join(":", [for p in var.config.github.app_parameters.key_base64 : p.name]) + PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = join(":", [for p in var.config.github.app_parameters.installation_id : p != null ? p.name : ""]) + POWERTOOLS_LOGGER_LOG_EVENT = var.config.observability.logs.level == "debug" ? "true" : "false" + POWERTOOLS_METRICS_NAMESPACE = var.config.observability.metrics.namespace + POWERTOOLS_TRACE_ENABLED = var.config.observability.tracing.mode != null + POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS = var.config.observability.tracing.capture_http_requests + POWERTOOLS_TRACER_CAPTURE_ERROR = var.config.observability.tracing.capture_error + RUNNER_LABELS = lower(join(",", var.config.runner.labels)) + RUNNER_GROUP_NAME = var.config.runner.group_name + RUNNER_NAME_PREFIX = var.config.runner.name_prefix + COMPUTE_PROVIDER_TYPE = var.runner_provider.type + RUNNERS_MAXIMUM_COUNT = var.config.runner.maximum_count + POWERTOOLS_SERVICE_NAME = "${var.config.prefix}-scale-up" + SSM_TOKEN_PATH = var.config.ssm.token_path + SSM_CONFIG_PATH = var.config.ssm.config_path + SSM_PARAMETER_STORE_TAGS = var.config.ssm.parameter_store_tags + JOB_RETRY_CONFIG = jsonencode(local.job_retry_config) + }) + } + + dynamic "vpc_config" { + for_each = local.vpc_enabled ? [true] : [] + + content { + security_group_ids = var.config.lambda.vpc.security_group_ids + subnet_ids = var.config.lambda.vpc.subnet_ids + } + } + + dynamic "tracing_config" { + for_each = var.config.observability.tracing.mode != null ? [true] : [] + + content { + mode = var.config.observability.tracing.mode + } + } +} + +resource "aws_cloudwatch_log_group" "scale_up" { + name = "/aws/lambda/${aws_lambda_function.scale_up.function_name}" + retention_in_days = var.config.observability.logs.retention_in_days + kms_key_id = var.config.observability.logs.kms_key_id + log_group_class = var.config.observability.logs.class + tags = var.config.scale_up.tags.log_group +} + +resource "aws_lambda_event_source_mapping" "scale_up" { + event_source_arn = var.config.queue.build.arn + function_name = aws_lambda_function.scale_up.arn + function_response_types = ["ReportBatchItemFailures"] + batch_size = var.config.queue.event_source_mapping.batch_size + maximum_batching_window_in_seconds = var.config.queue.event_source_mapping.maximum_batching_window_in_seconds + tags = var.config.scale_up.tags.event_source_mapping +} + +resource "aws_lambda_permission" "scale_runners_lambda" { + statement_id = "AllowExecutionFromSQS" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.scale_up.function_name + principal = "sqs.amazonaws.com" + source_arn = var.config.queue.build.arn +} + +resource "aws_iam_role" "scale_up" { + name = "${substr("${var.config.prefix}-scale-up-lambda", 0, 54)}-${substr(md5("${var.config.prefix}-scale-up-lambda"), 0, 8)}" + assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json + path = var.config.lambda.role.path + permissions_boundary = var.config.lambda.role.permissions_boundary + tags = var.config.scale_up.tags.resources +} + +resource "aws_iam_role_policy" "scale_up" { + name = "scale-up-policy" + role = aws_iam_role.scale_up.name + policy = data.aws_iam_policy_document.scale_up.json +} + +resource "aws_iam_role_policy" "scale_up_logging" { + name = "logging-policy" + role = aws_iam_role.scale_up.name + policy = data.aws_iam_policy_document.scale_up_logging.json +} + +resource "aws_iam_role_policy" "service_linked_role" { + count = var.runner_provider.scale_up.additional_iam_policy_json != null ? 1 : 0 + name = "service_linked_role" + role = aws_iam_role.scale_up.name + policy = var.runner_provider.scale_up.additional_iam_policy_json +} + +resource "aws_iam_role_policy_attachment" "scale_up_vpc_execution_role" { + count = local.vpc_enabled ? 1 : 0 + role = aws_iam_role.scale_up.name + policy_arn = "arn:${var.aws_partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" +} + +resource "aws_iam_role_policy_attachment" "provider" { + count = var.runner_provider.scale_up.managed_policy != null ? 1 : 0 + role = aws_iam_role.scale_up.name + policy_arn = var.runner_provider.scale_up.managed_policy.arn +} + +resource "aws_iam_role_policy" "scale_up_xray" { + count = var.config.observability.tracing.mode != null ? 1 : 0 + name = "xray-policy" + policy = data.aws_iam_policy_document.lambda_xray[0].json + role = aws_iam_role.scale_up.name +} + +resource "aws_iam_role_policy" "job_retry_sqs_publish" { + count = var.config.job_retry.enabled ? 1 : 0 + name = "publish-retry-check-sqs-policy" + role = aws_iam_role.scale_up.name + policy = data.aws_iam_policy_document.scale_up_job_retry_publish[0].json +} diff --git a/modules/orchestration-providers/webhook/scale-runners/tests/scale-runners.tftest.hcl b/modules/orchestration-providers/webhook/scale-runners/tests/scale-runners.tftest.hcl new file mode 100644 index 0000000000..955c9e7182 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/tests/scale-runners.tftest.hcl @@ -0,0 +1,439 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } + + mock_resource "aws_iam_role" { + defaults = { + arn = "arn:aws:iam::123456789012:role/scale-runners-test" + } + } +} + +variables { + aws_partition = "aws-us-gov" + + config = { + prefix = "scale-runners-test" + lambda = { + artifact = { + zip = "runners.zip" + s3 = { + bucket = "lambda-artifacts" + key = "runners.zip" + object_version = "test-version" + } + } + runtime = "nodejs24.x" + architecture = "arm64" + vpc = { + subnet_ids = ["subnet-12345678"] + security_group_ids = ["sg-12345678"] + } + role = { + path = "/scale-runners-test/" + permissions_boundary = "arn:aws-us-gov:iam::123456789012:policy/permissions-boundary" + principals = [{ + type = "AWS" + identifiers = ["arn:aws-us-gov:iam::123456789012:role/local-testing"] + }] + } + } + runner = { + os = "windows" + auto_update_disabled = true + ephemeral = true + jit_config_enabled = true + labels = ["Self-Hosted", "MicroVM"] + group_name = "test-group" + name_prefix = "test-runner-" + boot_time_in_minutes = 12 + maximum_count = 7 + } + github = { + organization_runners = true + enterprise_server = { + url = "https://github.example.com" + ssl_verify = false + } + user_agent = "scale-runners-test" + app_parameters = { + key_base64 = [ + { + name = "/github-runner/key-base64" + arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/key-base64" + }, + { + name = "/github-runner/key-base64-2" + arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/key-base64-2" + }, + ] + id = [ + { + name = "/github-runner/app-id" + arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/app-id" + }, + { + name = "/github-runner/app-id-2" + arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/app-id-2" + }, + ] + installation_id = [ + null, + { + name = "/github-runner/installation-id-2" + arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/installation-id-2" + }, + ] + } + } + queue = { + build = { + arn = "arn:aws-us-gov:sqs:us-gov-west-1:123456789012:build-queue" + } + kms_key_id = "arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/build-queue-test" + event_source_mapping = { + batch_size = 25 + maximum_batching_window_in_seconds = 5 + } + } + ssm = { + token_path = "/github-runner/tokens" + token_path_arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/tokens" + config_path = "/github-runner/config" + config_path_arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/config" + parameter_store_tags = jsonencode([{ + Key = "Environment" + Value = "test" + }]) + kms_key_id = "arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/scale-runners-test" + } + observability = { + logs = { + level = "debug" + retention_in_days = 14 + kms_key_id = "arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/logs" + class = "INFREQUENT_ACCESS" + } + tracing = { + mode = "Active" + capture_http_requests = true + capture_error = true + } + metrics = { + enable = true + namespace = "ScaleRunnersTest" + metric = { + enable_github_app_rate_limit = true + } + } + } + scale_up = { + memory_size = 768 + timeout = 90 + reserved_concurrent_executions = 2 + job_queued_check_enabled = true + tags = { + resources = { Scope = "scale-up" } + lambda = { Scope = "scale-up-lambda" } + log_group = { Scope = "scale-up-log" } + event_source_mapping = { Scope = "scale-up-queue" } + } + } + scale_down = { + memory_size = 640 + timeout = 75 + schedule_expression = "rate(10 minutes)" + minimum_running_time_in_minutes = null + idle_config = [{ + cron = "* * * * *" + timeZone = "UTC" + idleCount = 2 + evictionStrategy = "oldest_first" + }] + tags = { + resources = { Scope = "scale-down" } + lambda = { Scope = "scale-down-lambda" } + log_group = { Scope = "scale-down-log" } + } + } + job_retry = { + enabled = true + max_attempts = 4 + delay_in_seconds = 120 + delay_backoff = 3 + queue = { + arn = "arn:aws-us-gov:sqs:us-gov-west-1:123456789012:job-retry" + url = "https://sqs.us-gov-west-1.amazonaws.com/123456789012/job-retry" + } + } + } + + runner_provider = { + type = "microvm" + scale_up = { + environment_variables = { + MICROVM_CLUSTER = "runner-cluster" + } + iam_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Action = ["microvm:CreateRunner"] + Resource = ["*"] + }] + }) + additional_iam_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Action = ["iam:CreateServiceLinkedRole"] + Resource = ["*"] + }] + }) + managed_policy = { + arn = "arn:aws-us-gov:iam::123456789012:policy/microvm-scale-up" + } + } + scale_down = { + environment_variables = { + MICROVM_CLUSTER = "runner-cluster" + } + iam_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Action = ["microvm:DeleteRunner"] + Resource = ["*"] + }] + }) + } + } +} + +run "assembles_provider_neutral_scaling_control_plane" { + command = plan + + assert { + condition = ( + length(data.aws_iam_policy_document.lambda_assume_role.statement[0].principals) == 2 && + contains(data.aws_iam_policy_document.lambda_assume_role.statement[0].principals[*].type, "AWS") + ) + error_message = "The scaling Lambda trust policy must include configured additional principals." + } + + assert { + condition = ( + toset(keys(output.scale_up)) == toset(["lambda", "log_group", "role"]) + && toset(keys(output.scale_down)) == toset(["lambda", "log_group", "role"]) + ) + error_message = "Scale runners must expose nested scale-up and scale-down Lambda resource contracts." + } + + assert { + condition = ( + aws_lambda_function.scale_up.environment[0].variables["COMPUTE_PROVIDER_TYPE"] == "microvm" + && aws_lambda_function.scale_down.environment[0].variables["COMPUTE_PROVIDER_TYPE"] == "microvm" + && aws_lambda_function.scale_up.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "7" + && aws_lambda_function.scale_down.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "12" + && aws_lambda_function.scale_up.environment[0].variables["MICROVM_CLUSTER"] == "runner-cluster" + && aws_lambda_function.scale_down.environment[0].variables["MICROVM_CLUSTER"] == "runner-cluster" + && !contains(keys(aws_lambda_function.scale_up.environment[0].variables), "INSTANCE_TYPES") + ) + error_message = "The common scaling Lambdas must select the compute provider while injecting webhook-owned capacity and boot-time settings." + } + + assert { + condition = ( + aws_lambda_function.scale_up.environment[0].variables["LOG_LEVEL"] == "DEBUG" + && aws_lambda_function.scale_up.environment[0].variables["RUNNER_LABELS"] == "self-hosted,microvm" + && aws_lambda_function.scale_up.environment[0].variables["MINIMUM_RUNNING_TIME_IN_MINUTES"] == "15" + && aws_lambda_function.scale_down.environment[0].variables["MINIMUM_RUNNING_TIME_IN_MINUTES"] == "15" + && aws_lambda_function.scale_up.environment[0].variables["NODE_TLS_REJECT_UNAUTHORIZED"] == "0" + && jsondecode(aws_lambda_function.scale_up.environment[0].variables["SSM_PARAMETER_STORE_TAGS"])[0].Value == "test" + ) + error_message = "Scale runners must assemble shared runner, logging, TLS, lifetime, and Parameter Store environment variables." + } + + assert { + condition = ( + aws_lambda_function.scale_up.environment[0].variables["PARAMETER_GITHUB_APP_ID_NAME"] == "/github-runner/app-id:/github-runner/app-id-2" + && aws_lambda_function.scale_down.environment[0].variables["PARAMETER_GITHUB_APP_KEY_BASE64_NAME"] == "/github-runner/key-base64:/github-runner/key-base64-2" + && aws_lambda_function.scale_up.environment[0].variables["PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME"] == ":/github-runner/installation-id-2" + && contains(data.aws_iam_policy_document.scale_up_common.statement[1].resources, "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/app-id-2") + && contains(data.aws_iam_policy_document.scale_down_common.statement[0].resources, "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/key-base64-2") + && contains(data.aws_iam_policy_document.scale_down_common.statement[0].resources, "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/installation-id-2") + ) + error_message = "Scale-up and scale-down must pass every GitHub App parameter and grant access to every corresponding SSM ARN." + } + + assert { + condition = ( + jsondecode(aws_lambda_function.scale_up.environment[0].variables["JOB_RETRY_CONFIG"]).queueUrl == "https://sqs.us-gov-west-1.amazonaws.com/123456789012/job-retry" + && jsondecode(aws_lambda_function.scale_up.environment[0].variables["JOB_RETRY_CONFIG"]).maxAttempts == "4" + && jsondecode(aws_lambda_function.scale_down.environment[0].variables["SCALE_DOWN_CONFIG"])[0].idleCount == 2 + ) + error_message = "Scale runners must preserve job-retry and idle-runner configuration at the Lambda boundary." + } + + assert { + condition = ( + aws_lambda_function.scale_up.memory_size == 768 + && aws_lambda_function.scale_up.timeout == 90 + && aws_lambda_function.scale_up.reserved_concurrent_executions == 2 + && aws_lambda_function.scale_down.memory_size == 640 + && aws_lambda_function.scale_down.timeout == 75 + && aws_cloudwatch_log_group.scale_up.log_group_class == "INFREQUENT_ACCESS" + && aws_cloudwatch_log_group.scale_down.retention_in_days == 14 + ) + error_message = "The child module must preserve Lambda sizing and log-group configuration." + } + + assert { + condition = ( + aws_lambda_event_source_mapping.scale_up.event_source_arn == "arn:aws-us-gov:sqs:us-gov-west-1:123456789012:build-queue" + && aws_lambda_event_source_mapping.scale_up.batch_size == 25 + && aws_lambda_event_source_mapping.scale_up.maximum_batching_window_in_seconds == 5 + && aws_lambda_event_source_mapping.scale_up.tags["Scope"] == "scale-up-queue" + && aws_cloudwatch_event_rule.scale_down.schedule_expression == "rate(10 minutes)" + && aws_cloudwatch_event_rule.scale_down.tags["Scope"] == "scale-down" + ) + error_message = "Scale-up queue and scale-down schedule triggers must remain owned by the child module." + } + + assert { + condition = ( + aws_lambda_function.scale_up.tags["Scope"] == "scale-up-lambda" + && aws_cloudwatch_log_group.scale_up.tags["Scope"] == "scale-up-log" + && aws_iam_role.scale_up.tags["Scope"] == "scale-up" + && aws_lambda_function.scale_down.tags["Scope"] == "scale-down-lambda" + && aws_cloudwatch_log_group.scale_down.tags["Scope"] == "scale-down-log" + && aws_iam_role.scale_down.tags["Scope"] == "scale-down" + ) + error_message = "Resolved component tag maps must reach the resources owned by scale runners." + } + + assert { + condition = ( + length(aws_lambda_function.scale_up.vpc_config) == 1 + && length(aws_lambda_function.scale_down.vpc_config) == 1 + && length(aws_iam_role_policy_attachment.scale_up_vpc_execution_role) == 1 + && length(aws_iam_role_policy_attachment.scale_down_vpc_execution_role) == 1 + && aws_iam_role_policy_attachment.scale_up_vpc_execution_role[0].policy_arn == "arn:aws-us-gov:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" + ) + error_message = "A complete Lambda VPC configuration must configure both Lambdas and their partition-aware execution policies." + } + + assert { + condition = ( + length(aws_lambda_function.scale_up.tracing_config) == 1 + && length(aws_lambda_function.scale_down.tracing_config) == 1 + && length(aws_iam_role_policy.scale_up_xray) == 1 + && length(aws_iam_role_policy.scale_down_xray) == 1 + ) + error_message = "Active tracing must configure both Lambdas and attach their X-Ray policies." + } + + assert { + condition = ( + length(aws_iam_role_policy.service_linked_role) == 1 + && length(aws_iam_role_policy_attachment.provider) == 1 + && aws_iam_role_policy_attachment.provider[0].policy_arn == "arn:aws-us-gov:iam::123456789012:policy/microvm-scale-up" + && length(aws_iam_role_policy.job_retry_sqs_publish) == 1 + ) + error_message = "Optional compute-provider and job-retry IAM integrations must be attached to the scale-up role." + } + + assert { + condition = ( + length(data.aws_iam_policy_document.scale_up.source_policy_documents) == 2 + && length(data.aws_iam_policy_document.scale_down.source_policy_documents) == 2 + && length(data.aws_iam_policy_document.scale_up_common.statement) == 5 + && length(data.aws_iam_policy_document.scale_down_common.statement) == 2 + && one([ + for statement in data.aws_iam_policy_document.scale_up_common.statement : statement + if statement.sid == "WebhookScaleUpDecryptParameterStore" + ]).resources == toset(["arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/scale-runners-test"]) + && one([ + for statement in data.aws_iam_policy_document.scale_up_common.statement : statement + if statement.sid == "WebhookScaleUpDecryptBuildQueue" + ]).resources == toset(["arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/build-queue-test"]) + && one([ + for statement in data.aws_iam_policy_document.scale_up_common.statement : statement + if statement.sid == "WebhookScaleUpDecryptBuildQueue" + ]).actions == toset(["kms:Decrypt"]) + && one([ + for statement in data.aws_iam_policy_document.scale_down_common.statement : statement + if statement.sid == "WebhookScaleDownDecryptParameterStore" + ]).resources == toset(["arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/scale-runners-test"]) + && length(data.aws_iam_policy_document.scale_up_job_retry_publish) == 1 + ) + error_message = "Common, provider, distinct Parameter Store/build-queue KMS, and retry IAM fragments must retain their conditional plan shape." + } + + assert { + condition = ( + one([ + for statement in data.aws_iam_policy_document.scale_up_common.statement : statement + if statement.sid == "WebhookScaleUpWriteRuntimeParameters" + ]).resources == toset([ + "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/tokens", + "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/tokens/*", + "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/config", + "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/config/*", + ]) + && !contains(one([ + for statement in data.aws_iam_policy_document.scale_up_common.statement : statement + if statement.sid == "WebhookScaleUpWriteRuntimeParameters" + ]).resources, "*") + ) + error_message = "Scale-up must scope runtime SSM writes to the token and runner-config parameter paths." + } + + assert { + condition = ( + data.aws_iam_policy_document.lambda_xray[0].statement[0].sid == "AllowXRay" + && data.aws_iam_policy_document.lambda_xray[0].statement[0].resources == toset(["*"]) + && toset(data.aws_iam_policy_document.lambda_xray[0].statement[0].actions) == toset([ + "xray:BatchGetTraces", + "xray:GetTraceSummaries", + "xray:PutTelemetryRecords", + "xray:PutTraceSegments", + ]) + ) + error_message = "Only the resource-agnostic X-Ray APIs may retain a wildcard resource in the scale-runner common policies." + } +} + +run "omits_optional_kms_statements" { + command = plan + + variables { + config = merge(var.config, { + queue = merge(var.config.queue, { + kms_key_id = null + }) + ssm = merge(var.config.ssm, { + kms_key_id = null + }) + }) + } + + assert { + condition = ( + length(data.aws_iam_policy_document.scale_up_common.statement) == 3 + && length(data.aws_iam_policy_document.scale_down_common.statement) == 1 + && length([ + for statement in data.aws_iam_policy_document.scale_up_common.statement : statement + if anytrue([for action in statement.actions : startswith(action, "kms:")]) + ]) == 0 + && length([ + for statement in data.aws_iam_policy_document.scale_down_common.statement : statement + if anytrue([for action in statement.actions : startswith(action, "kms:")]) + ]) == 0 + ) + error_message = "Null Parameter Store and build-queue keys must omit every optional scale-runner KMS statement." + } +} diff --git a/modules/orchestration-providers/webhook/scale-runners/variables.tf b/modules/orchestration-providers/webhook/scale-runners/variables.tf new file mode 100644 index 0000000000..f44c063e9d --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/variables.tf @@ -0,0 +1,236 @@ +variable "aws_partition" { + description = "AWS partition used to construct IAM policy ARNs." + type = string + default = "aws" +} + +variable "config" { + description = <<-EOT + Provider-neutral scale-up and scale-down configuration assembled by runner-config. + + - `prefix`: Prefix used to name scaling resources. + - `lambda.artifact.zip`: Resolved local control-plane archive. + - `lambda.artifact.s3.bucket`: Optional S3 bucket containing the Lambda archive. + - `lambda.artifact.s3.key`: Object key of the Lambda archive. + - `lambda.artifact.s3.object_version`: Optional object version of the Lambda archive. + - `lambda.runtime`: Runtime used by both scaling Lambdas. + - `lambda.architecture`: Instruction-set architecture used by both scaling Lambdas. + - `lambda.vpc.subnet_ids`: Subnets used for Lambda VPC configuration. + - `lambda.vpc.security_group_ids`: Security groups used for Lambda VPC configuration. + - `lambda.role.path`: IAM path used for the scaling Lambda roles. + - `lambda.role.permissions_boundary`: Optional permissions boundary for the scaling Lambda roles. + - `lambda.role.principals`: Additional principals allowed to assume the scaling Lambda roles. + - `runner.os`: Runner operating system used for the minimum-runtime default. + - `runner.auto_update_disabled`: Disables the GitHub runner application's built-in updater. + - `runner.ephemeral`: Registers runners in ephemeral mode. + - `runner.jit_config_enabled`: Enables or disables just-in-time runner configuration. + - `runner.labels`: Labels supplied when a runner is registered. + - `runner.group_name`: GitHub runner group used during registration. + - `runner.name_prefix`: Prefix added to registered runner names. + - `runner.boot_time_in_minutes`: Webhook-provider runner boot timeout used by scale-down. + - `runner.maximum_count`: Webhook-provider runner capacity limit for this runner configuration. + - `github.organization_runners`: Registers organization runners when true. + - `github.enterprise_server.url`: Optional GitHub Enterprise Server URL. + - `github.enterprise_server.ssl_verify`: Enables TLS verification for GitHub Enterprise Server. + - `github.user_agent`: Optional User-Agent sent to GitHub. + - `github.app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys. + - `github.app_parameters.id`: Ordered Parameter Store references for GitHub App IDs. + - `github.app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs. + - `queue.build.arn`: ARN of the build queue consumed by scale-up. + - `queue.kms_key_id`: Optional KMS key ARN used to encrypt the build queue. This is distinct from the Parameter Store key. + - `queue.event_source_mapping.batch_size`: Maximum records delivered per scale-up invocation. + - `queue.event_source_mapping.maximum_batching_window_in_seconds`: Maximum event batching window. + - `ssm.token_path`: Parameter Store path used for registration tokens. + - `ssm.token_path_arn`: ARN of the Parameter Store path used for registration tokens. + - `ssm.config_path`: Parameter Store path used for persistent runner configuration. + - `ssm.config_path_arn`: ARN of the persistent runner configuration path. + - `ssm.kms_key_id`: Optional KMS key ARN used to decrypt shared parameters. Its value may be unknown until apply. + - `ssm.parameter_store_tags`: JSON-encoded tags applied to parameters created at runtime. + - `observability.logs`: Shared logging level, retention, encryption, and log-class configuration. + - `observability.tracing`: Lambda X-Ray and tracing-helper configuration. + - `observability.metrics`: Metrics enablement, namespace, and GitHub rate-limit metric configuration. + - `scale_up`: Scale-up Lambda sizing, concurrency, queued-job behavior, and resolved resource tag maps. + - `scale_up.tags.resources`: Tags for the scale-up IAM role and other component resources. + - `scale_up.tags.lambda`: Tags for the scale-up Lambda function. + - `scale_up.tags.log_group`: Tags for the scale-up log group. + - `scale_up.tags.event_source_mapping`: Tags for the build-queue event-source mapping. + - `scale_down`: Scale-down Lambda sizing, schedule, idle configuration, minimum runtime, and resolved resource tag maps. + - `scale_down.tags.resources`: Tags for the scale-down IAM role and EventBridge rule. + - `scale_down.tags.lambda`: Tags for the scale-down Lambda function. + - `scale_down.tags.log_group`: Tags for the scale-down log group. + - `job_retry.enabled`: Enables publishing retry checks from scale-up. + - `job_retry.queue`: Retry queue ARN and URL. Required when job retry is enabled. + - `job_retry.max_attempts`: Maximum queued-job retry attempts. + - `job_retry.delay_in_seconds`: Initial delay before checking the queued job. + - `job_retry.delay_backoff`: Multiplier applied to subsequent delays. + EOT + + type = object({ + prefix = string + lambda = object({ + artifact = object({ + zip = string + s3 = object({ + bucket = optional(string, null) + key = optional(string, null) + object_version = optional(string, null) + }) + }) + runtime = string + architecture = string + vpc = object({ + subnet_ids = list(string) + security_group_ids = list(string) + }) + role = object({ + path = string + permissions_boundary = optional(string, null) + principals = optional(list(object({ + type = string + identifiers = list(string) + })), []) + }) + }) + runner = object({ + os = string + auto_update_disabled = bool + ephemeral = bool + jit_config_enabled = optional(bool, null) + labels = list(string) + group_name = string + name_prefix = string + boot_time_in_minutes = number + maximum_count = number + }) + github = object({ + organization_runners = bool + enterprise_server = object({ + url = optional(string, null) + ssl_verify = bool + }) + user_agent = optional(string, null) + app_parameters = object({ + key_base64 = list(map(string)) + id = list(map(string)) + installation_id = list(object({ name = string, arn = string })) + }) + }) + queue = object({ + build = object({ + arn = string + }) + kms_key_id = optional(string, null) + event_source_mapping = object({ + batch_size = number + maximum_batching_window_in_seconds = number + }) + }) + ssm = object({ + token_path = string + token_path_arn = string + config_path = string + config_path_arn = string + parameter_store_tags = string + kms_key_id = optional(string, null) + }) + observability = object({ + logs = object({ + level = string + retention_in_days = number + kms_key_id = optional(string, null) + class = string + }) + tracing = object({ + mode = optional(string, null) + capture_http_requests = bool + capture_error = bool + }) + metrics = object({ + enable = bool + namespace = string + metric = object({ + enable_github_app_rate_limit = bool + }) + }) + }) + scale_up = object({ + memory_size = number + timeout = number + reserved_concurrent_executions = number + job_queued_check_enabled = bool + tags = object({ + resources = map(string) + lambda = map(string) + log_group = map(string) + event_source_mapping = map(string) + }) + }) + scale_down = object({ + memory_size = number + timeout = number + schedule_expression = string + minimum_running_time_in_minutes = optional(number, null) + idle_config = list(object({ + cron = string + timeZone = string + idleCount = number + evictionStrategy = string + })) + tags = object({ + resources = map(string) + lambda = map(string) + log_group = map(string) + }) + }) + job_retry = object({ + enabled = bool + max_attempts = number + delay_in_seconds = number + delay_backoff = number + queue = optional(object({ + arn = string + url = string + }), null) + }) + }) + + nullable = false + + validation { + condition = !var.config.job_retry.enabled || var.config.job_retry.queue != null + error_message = "config.job_retry.queue must be set when config.job_retry.enabled is true." + } +} + +variable "runner_provider" { + description = <<-EOT + Selected compute-provider integration for the scaling control plane. + + - `type`: Compute-provider discriminator supplied to both Lambdas. + - `scale_up.environment_variables`: Provider-specific scale-up environment variables. + - `scale_up.iam_policy_json`: Provider-specific IAM policy merged into the common scale-up policy. + - `scale_up.additional_iam_policy_json`: Optional additional provider policy attached separately to the scale-up role. + - `scale_up.managed_policy`: Optional provider-managed policy attachment. Object presence controls attachment creation. + - `scale_up.managed_policy.arn`: ARN of the provider-managed policy. The ARN may remain unknown until apply. + - `scale_down.environment_variables`: Provider-specific scale-down environment variables. + - `scale_down.iam_policy_json`: Provider-specific IAM policy merged into the common scale-down policy. + EOT + + type = object({ + type = string + scale_up = object({ + environment_variables = map(string) + iam_policy_json = string + additional_iam_policy_json = optional(string, null) + managed_policy = optional(object({ + arn = string + }), null) + }) + scale_down = object({ + environment_variables = map(string) + iam_policy_json = string + }) + }) + + nullable = false +} diff --git a/modules/orchestration-providers/webhook/scale-runners/versions.tf b/modules/orchestration-providers/webhook/scale-runners/versions.tf new file mode 100644 index 0000000000..da9769f550 --- /dev/null +++ b/modules/orchestration-providers/webhook/scale-runners/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.33" + } + } +} diff --git a/modules/orchestration-providers/webhook/tests/webhook.tftest.hcl b/modules/orchestration-providers/webhook/tests/webhook.tftest.hcl new file mode 100644 index 0000000000..105648e8be --- /dev/null +++ b/modules/orchestration-providers/webhook/tests/webhook.tftest.hcl @@ -0,0 +1,291 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } + + mock_resource "aws_iam_role" { + defaults = { + arn = "arn:aws:iam::123456789012:role/webhook-orchestration-test" + } + } +} + +variables { + prefix = "webhook-test" + + tags = { + Scope = "common" + Precedence = "common" + } + + runner = { + os = "linux" + auto_update_disabled = false + labels = ["self-hosted", "linux"] + group_name = "default" + name_prefix = "webhook-test-" + } + + github = { + app_parameters = { + key_base64 = [{ + name = "/github-runner/key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" + }] + id = [{ + name = "/github-runner/app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" + }] + installation_id = [null] + } + enterprise_server = { + url = null + ssl_verify = true + } + user_agent = "webhook-orchestration-test" + } + + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + runtime = "nodejs24.x" + architecture = "arm64" + subnet_ids = [] + security_group_ids = [] + tags = { + Lambda = "yes" + Precedence = "lambda" + } + role = { + path = "/webhook-test/" + } + } + + ssm = { + token_path = "/github-runner/tokens" + token_path_arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/tokens" + config_path = "/github-runner/config" + config_path_arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/config" + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/webhook-test" + parameter_store_tags = "[]" + } + + observability = { + logs = { + level = "info" + retention_in_days = 14 + kms_key_id = null + class = "STANDARD" + } + tracing = { + mode = null + capture_http_requests = false + capture_error = false + } + metrics = { + enable = true + namespace = "WebhookTest" + metric = { + enable_github_app_rate_limit = true + enable_job_retry = true + } + } + } + + config = { + runner = { + boot_time_in_minutes = 11 + ephemeral = true + jit_config_enabled = null + maximum_count = 10 + } + github = { + organization_runners = true + } + queue = { + build = { + arn = "arn:aws:sqs:eu-west-1:123456789012:build-queue" + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/build-queue" + } + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/build-queue-test" + tags = { + Queue = "yes" + } + } + lambda = { + artifact = { + s3 = { + key = "runners.zip" + } + } + scale = { + up = { + memory_size = 512 + timeout = 60 + reserved_concurrent_executions = 1 + job_queued_check_enabled = null + event_source_mapping = { + batch_size = 10 + maximum_batching_window_in_seconds = 0 + } + tags = { + ScaleUp = "yes" + Precedence = "scale-up" + } + } + down = { + memory_size = 512 + timeout = 60 + schedule_expression = "cron(*/5 * * * ? *)" + minimum_running_time_in_minutes = null + idle_config = [] + tags = { + ScaleDown = "yes" + } + } + } + pool = { + memory_size = 512 + timeout = 60 + reserved_concurrent_executions = 1 + config = [{ + schedule_expression = "cron(0 8 * * ? *)" + schedule_expression_timezone = "UTC" + size = 1 + }] + include_busy_runners = false + runner_owner = "example" + tags = { + Pool = "yes" + } + } + } + job_retry = { + enabled = true + delay_in_seconds = 300 + delay_backoff = 2 + max_attempts = 2 + tags = { + JobRetry = "yes" + } + lambda = { + memory_size = 256 + reserved_concurrent_executions = 1 + timeout = 30 + } + } + } + + runner_provider = { + type = "test-provider" + scale_up = { + environment_variables = { + TEST_SCALE_UP = "yes" + } + iam_policy_json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + additional_iam_policy_json = null + managed_policy = null + } + scale_down = { + environment_variables = { + TEST_SCALE_DOWN = "yes" + } + iam_policy_json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + pool = { + environment_variables = { + TEST_POOL = "yes" + } + iam_policy_json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + managed_policy_enabled = false + managed_policy_arn = null + } + } +} + +run "owns_webhook_control_plane" { + command = plan + + assert { + condition = ( + toset(keys(output.scale_up)) == toset(["lambda", "log_group", "role"]) + && toset(keys(output.scale_down)) == toset(["lambda", "log_group", "role"]) + ) + error_message = "The webhook provider must own and expose both scaling functions." + } + + assert { + condition = ( + output.pool != null + && output.job_retry != null + && output.job_retry.lambda != null + && output.job_retry.queue != null + ) + error_message = "The webhook provider must own the optional pool and job-retry resources when enabled." + } + + assert { + condition = ( + output.scale_up.lambda.environment[0].variables["COMPUTE_PROVIDER_TYPE"] == "test-provider" + && output.scale_up.lambda.environment[0].variables["TEST_SCALE_UP"] == "yes" + && output.scale_down.lambda.environment[0].variables["TEST_SCALE_DOWN"] == "yes" + && output.pool.lambda.environment[0].variables["TEST_POOL"] == "yes" + ) + error_message = "The webhook provider must forward each compute-provider capability to the matching leaf." + } + + assert { + condition = ( + output.scale_up.lambda.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "10" + && output.pool.lambda.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "10" + && output.scale_down.lambda.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "11" + && output.pool.lambda.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "11" + && output.scale_up.lambda.environment[0].variables["ENABLE_JIT_CONFIG"] == "true" + && output.pool.lambda.environment[0].variables["ENABLE_JIT_CONFIG"] == "true" + ) + error_message = "The webhook provider must route its provider-owned runner lifecycle, capacity, and boot-time values without reading them from common runner values." + } + + assert { + condition = ( + output.runner_lifecycle.ephemeral + && output.runner_lifecycle.jit_config_enabled + ) + error_message = "The webhook provider must expose its resolved lifecycle contract and default JIT configuration to the effective ephemeral mode." + } + + assert { + condition = ( + output.scale_up.lambda.s3_bucket == "lambda-artifacts" + && output.scale_up.lambda.s3_key == "runners.zip" + && output.scale_down.lambda.s3_bucket == "lambda-artifacts" + && output.pool.lambda.s3_key == "runners.zip" + ) + error_message = "The webhook provider must combine the common artifact bucket with its shared runner-control artifact key for scale, pool, and job retry." + } + + assert { + condition = ( + output.scale_up.lambda.tags["Scope"] == "common" + && output.scale_up.lambda.tags["Lambda"] == "yes" + && output.scale_up.lambda.tags["ScaleUp"] == "yes" + && output.scale_up.lambda.tags["Precedence"] == "scale-up" + && output.job_retry.queue.tags["JobRetry"] == "yes" + && output.job_retry.queue.tags["Queue"] == "yes" + ) + error_message = "Provider-owned normalization must preserve common, substrate, and webhook component tag precedence." + } + + assert { + condition = ( + length(module.pool) == 1 + && length(module.job_retry) == 1 + ) + error_message = "Pool and job-retry leaf ownership must remain inside the webhook provider." + } +} diff --git a/modules/orchestration-providers/webhook/variables.tf b/modules/orchestration-providers/webhook/variables.tf new file mode 100644 index 0000000000..dcb6f0b0d8 --- /dev/null +++ b/modules/orchestration-providers/webhook/variables.tf @@ -0,0 +1,223 @@ +variable "aws_partition" { + description = "AWS partition used to construct ARNs." + type = string + default = "aws" +} + +variable "prefix" { + description = "Prefix used to identify resources created for this webhook orchestration provider." + type = string +} + +variable "tags" { + description = "Base tags available to webhook-provider resources. Component-specific tags override this map within their documented scopes." + type = map(string) + default = {} +} + +variable "config" { + description = "Resolved provider-owned values from orchestration.webhook, including runner lifecycle, boot timeout, and capacity limits used by scaling and pool controls." + type = object({ + runner = object({ + boot_time_in_minutes = number + ephemeral = bool + jit_config_enabled = optional(bool, null) + maximum_count = number + }) + github = object({ + organization_runners = bool + }) + queue = object({ + build = object({ + arn = string + url = string + }) + kms_key_id = optional(string, null) + tags = optional(map(string), {}) + }) + lambda = object({ + artifact = object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }) + scale = object({ + up = object({ + memory_size = number + timeout = number + reserved_concurrent_executions = number + job_queued_check_enabled = optional(bool, null) + event_source_mapping = object({ + batch_size = number + maximum_batching_window_in_seconds = number + }) + tags = optional(map(string), {}) + }) + down = object({ + memory_size = number + timeout = number + schedule_expression = string + minimum_running_time_in_minutes = optional(number, null) + idle_config = list(object({ + cron = string + timeZone = string + idleCount = number + evictionStrategy = string + })) + tags = optional(map(string), {}) + }) + }) + pool = object({ + memory_size = number + timeout = number + reserved_concurrent_executions = number + config = list(object({ + schedule_expression = string + schedule_expression_timezone = optional(string) + size = number + })) + include_busy_runners = bool + runner_owner = optional(string, null) + tags = optional(map(string), {}) + }) + }) + job_retry = object({ + enabled = bool + delay_in_seconds = number + delay_backoff = number + max_attempts = number + tags = optional(map(string), {}) + lambda = object({ + memory_size = number + reserved_concurrent_executions = number + timeout = number + }) + }) + }) + nullable = false + + validation { + condition = !( + var.config.lambda.artifact.zip != null && + var.config.lambda.artifact.s3 != null + ) + error_message = "config.lambda.artifact must select at most one of zip or s3." + } +} + +variable "runner" { + description = "Common runner registration values consumed by webhook demand controls. Lifecycle, boot timeout, and capacity remain provider-owned under config.runner." + type = object({ + os = string + auto_update_disabled = bool + labels = list(string) + group_name = string + name_prefix = string + }) +} + +variable "github" { + description = "Common GitHub API client and GitHub App Parameter Store references." + type = object({ + app_parameters = object({ + key_base64 = list(map(string)) + id = list(map(string)) + installation_id = list(object({ name = string, arn = string })) + }) + enterprise_server = object({ + url = optional(string, null) + ssl_verify = bool + }) + user_agent = optional(string, null) + }) +} + +variable "lambda" { + description = "Common Lambda substrate. Only the shared artifact bucket crosses this boundary; the webhook provider owns its archive key, version, and local zip selection." + type = object({ + artifact = object({ + s3 = object({ + bucket = optional(string, null) + }) + }) + runtime = string + architecture = string + subnet_ids = list(string) + security_group_ids = list(string) + tags = optional(map(string), {}) + role = object({ + path = string + permissions_boundary = optional(string, null) + principals = optional(list(object({ + type = string + identifiers = list(string) + })), []) + }) + }) +} + +variable "ssm" { + description = "Resolved Parameter Store paths, optional decrypt key, and runtime parameter tags." + type = object({ + token_path = string + token_path_arn = string + config_path = string + config_path_arn = string + kms_key_id = optional(string, null) + parameter_store_tags = string + }) +} + +variable "observability" { + description = "Common logging, tracing, and metrics configuration consumed by webhook controls." + type = object({ + logs = object({ + level = string + retention_in_days = number + kms_key_id = optional(string, null) + class = string + tags = optional(map(string), {}) + }) + tracing = object({ + mode = optional(string, null) + capture_http_requests = bool + capture_error = bool + }) + metrics = object({ + enable = bool + namespace = string + metric = object({ + enable_github_app_rate_limit = bool + enable_job_retry = bool + }) + }) + }) +} + +variable "runner_provider" { + description = "Selected compute-provider capabilities consumed by webhook scaling, pool, and retry controls." + type = object({ + type = string + scale_up = object({ + environment_variables = map(string) + iam_policy_json = string + additional_iam_policy_json = optional(string, null) + managed_policy = optional(object({ + arn = string + }), null) + }) + scale_down = object({ + environment_variables = map(string) + iam_policy_json = string + }) + pool = object({ + environment_variables = map(string) + iam_policy_json = string + managed_policy_enabled = bool + managed_policy_arn = optional(string, null) + }) + }) + nullable = false +} diff --git a/modules/orchestration-providers/webhook/versions.tf b/modules/orchestration-providers/webhook/versions.tf new file mode 100644 index 0000000000..da9769f550 --- /dev/null +++ b/modules/orchestration-providers/webhook/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.33" + } + } +} diff --git a/modules/runner-config/README.md b/modules/runner-config/README.md new file mode 100644 index 0000000000..e63dddde08 --- /dev/null +++ b/modules/runner-config/README.md @@ -0,0 +1,130 @@ +# Runner configuration module + +> This module is treated as an internal module; breaking changes do not trigger a major release bump. + +This internal module implements the experimental provider-neutral runner configuration selected by `experimental.multi_runner_config`. It is composed by `multi-runner` and is not intended as a standalone public entry point. Its direct contract may change while v2 remains experimental. + +The module selects the [`webhook` orchestration provider](../orchestration-providers/webhook), which owns its [`scale-runners`](../orchestration-providers/webhook/scale-runners), [`pool`](../orchestration-providers/webhook/pool), and [`job-retry`](../orchestration-providers/webhook/job-retry) leaves. The configuration module retains the common [`ssm-housekeeper`](./ssm-housekeeper), creates or selects the runner IAM role, manages shared runner configuration in SSM, and dispatches the selected compute provider. + +Runner demand orchestration is selected independently through `orchestration`. `orchestration.webhook` is the currently supported provider and owns the build queue reference; runner lifecycle, boot time, and capacity under `orchestration.webhook.runner`; runner registration scope; scaling controls; scheduled pool; and job retry. Common `runner` contains no webhook lifecycle or capacity settings. The provider resolves its lifecycle contract before runner-config serializes the existing bootstrap parameters. The provider wrapper is nullable so a future sibling provider can be added without moving this webhook contract again, while validation requires exactly one provider to be selected. + +Common `lambda` contains only shared execution substrate and the optional shared artifact bucket. The webhook provider owns the runner-control archive shared by scale, pool, and job-retry at `orchestration.webhook.lambda.artifact` and combines its zip or S3 key/version with that common substrate. The common SSM housekeeper independently owns `ssm.housekeeper.lambda.artifact`: an S3 selection combines its component key/version with the common bucket, a local zip is used otherwise when configured, and the packaged runner control-plane archive is the final fallback. It never inherits the webhook runner-control archive. + +Provider-owned settings remain nested under a typed provider block. For example, AMI, VPC, instance-profile, capacity, userdata, and runner-host logging settings live under `compute_provider.ec2`. `multi-runner` resolves experimental globals and runner-configuration overrides first, then its final forwarding adapter preserves the wrapped `{ ec2 = ... }` object expected by this module. Exactly one provider block must be non-null, and the configuration module derives its provider type from that block rather than from a separate discriminator. + +The EC2 block reaches runner-config with `compute_provider.ec2.binaries_syncer = { enabled, s3 }`; the S3 object is null when synchronization is disabled. Binary discovery and this shape adaptation happen in `multi-runner`, not inside runner-config. Before creating the common runner role, the configuration module calls the selected provider's isolated `trust-policy` module to combine its default trust with `runner.iam.additional_trust_policy_json`. The resulting assume-role policy does not depend on the full compute-provider module, which receives the resolved runner role only after it is created. EC2 owns the instance profile, launch template, EC2 bootstrap parameters, runner log groups, and its provider policies and Lambda environment variables. The common configuration module attaches each returned policy group to its runner or webhook-provider role. Provider-specific outputs remain grouped under the matching provider key, such as `provider.ec2`. EC2 is the only implemented Terraform compute provider in this phase. + +## Tagging + +`tags` supplies module-wide defaults. Shared resource tags are set with `lambda.tags`, `orchestration.webhook.queue.tags`, and `observability.logs.tags`. Component tags under `runner`, `orchestration.webhook.lambda.scale.up`, `orchestration.webhook.lambda.scale.down`, `orchestration.webhook.lambda.pool`, `orchestration.webhook.job_retry`, and `ssm` apply to the taggable resources owned by that component. `ssm.parameters.tags` and `ssm.housekeeper.tags` provide narrower SSM scopes. + +Tags are merged from broadest to narrowest: module tags, shared resource tags, component tags, and then subcomponent tags. The narrowest value wins when a key is repeated. For example, a scale-up Lambda receives `tags`, `lambda.tags`, and `orchestration.webhook.lambda.scale.up.tags`, while its log group receives `tags`, `observability.logs.tags`, and `orchestration.webhook.lambda.scale.up.tags`. + +Provider-specific runner tags remain inside the provider boundary. `compute_provider.ec2.tags` applies to runtime EC2 instance, volume, network-interface, and spot-request tag specifications. `multi-runner` derives that map from global and runner-configuration `compute_provider.ec2.tags` values. The EC2 provider applies the bootstrap tags `ghr:environment`, `ghr:ssm_config_path`, and `ghr:runner_name_prefix` last so they cannot be overridden; those tags are not added to common Lambda, IAM, queue, log-group, or SSM resources. + +## Overview + +### Action runners on EC2 + +The action runners are created via a launch template; in the launch template only the subnet needs to be provided. During launch the installation is handled via a user data script. The configuration is fetched from SSM parameter store. + +### Lambda scale up + +The scale up lambda is triggered by events on a SQS queue. Events on this queue are delayed, which will give the workflow some time to start running on available runners. For each event the lambda will check if the workflow is still queued and no other limits are reached. In that case the lambda will create a new EC2 instance. The lambda only needs to know which launch template to use and which subnets are available. From the available subnets a random one will be chosen. Once the instance is created the event is assumed as handled, and we assume the workflow wil start at some moment once the created instance is ready. + +### Lambda scale down + +The scale down lambda is triggered via a CloudWatch event. The event is triggered by a cron expression defined in `orchestration.webhook.lambda.scale.down.schedule_expression` (https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html). For scaling down GitHub does not provide a good API yet, therefore we run the scaling down based on this event every x minutes. Each time the lambda is triggered it tries to remove all runners older than x minutes (configurable) managed in this deployment. In case the runner can be removed from GitHub, which means it is not executing a workflow, the lambda will terminate the EC2 instance. + +--8<-- "modules/orchestration-providers/webhook/scale-down-state-diagram.md:mkdocs_scale_down_state_diagram" + +## Lambda Function + +The Lambda function is written in [TypeScript](https://www.typescriptlang.org/) and requires Node 12.x and yarn. Sources are located in [./lambdas/runners]. Two lambda functions share the same sources, there is one entry point for `scaleDown` and another one for `scaleUp`. + +### Install + +```bash +cd lambdas/runners +yarn install +``` + +### Test + +Test are implemented with [vitest][https://vitest.dev/]), calls to AWS and GitHub are mocked. + +```bash +yarn run test +``` + +### Package + +To compile all TypeScript/JavaScript sources in a single file [ncc](https://github.com/zeit/ncc) is used. + +```bash +yarn run dist +``` + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 6.33 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.33 | + +## Modules + +| Name | Source | Version | +|------|--------|---------| +| [ec2](#module\_ec2) | ../compute-providers/ec2 | n/a | +| [ec2\_trust\_policy](#module\_ec2\_trust\_policy) | ../compute-providers/ec2/trust-policy | n/a | +| [ssm\_housekeeper](#module\_ssm\_housekeeper) | ./ssm-housekeeper | n/a | +| [webhook](#module\_webhook) | ../orchestration-providers/webhook | n/a | + +## Resources + +| Name | Type | +|------|------| +| [aws_iam_role.runner](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy.runner_provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy_attachment.runner](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_ssm_parameter.disable_default_labels](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [aws_ssm_parameter.jit_config_enabled](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [aws_ssm_parameter.runner_agent_mode](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [aws_ssm_parameter.token_path](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ssm_parameter) | resource | +| [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [aws\_partition](#input\_aws\_partition) | AWS partition used to construct ARNs. | `string` | `"aws"` | no | +| [aws\_region](#input\_aws\_region) | AWS region. | `string` | n/a | yes | +| [compute\_provider](#input\_compute\_provider) | Typed compute-provider configuration. Provider-owned settings remain inside the selected compute-provider block.

Exactly one compute-provider block must be non-null. The populated block selects the provider, and its presence must be known during planning. Values inside the selected block may remain unknown until apply.

- `ec2`: EC2 compute-provider configuration.
- `ec2.ami`: Optional AMI discovery or external AMI-parameter configuration. Null uses the operating-system and architecture defaults.
- `ec2.ami.filter`: EC2 AMI filters combined with the provider's default AMI-name filter.
- `ec2.ami.owners`: AWS account IDs or aliases allowed to own the selected AMI.
- `ec2.ami.id_ssm_parameter`: Optional externally managed SSM parameter containing the AMI ID. Null creates a provider-managed AMI-ID parameter. The wrapper's presence is the plan-time ownership discriminator, so keep the object literal even when its ARN comes from another resource.
- `ec2.ami.id_ssm_parameter.arn`: ARN of the externally managed SSM parameter. The ARN may be unknown until apply.
- `ec2.ami.kms_key`: Optional KMS key required to launch encrypted AMIs or snapshots. The wrapper's presence is the plan-time policy discriminator.
- `ec2.ami.kms_key.arn`: ARN of the KMS key. The ARN may be unknown until apply.
- `ec2.vpc_id`: VPC in which runner networking resources are created.
- `ec2.subnet_ids`: Subnets from which scale-up may launch runner instances.
- `ec2.overrides`: Optional resource-name overrides.
- `ec2.overrides.name_runner`: Name tag used for runner compute resources. An empty value uses the generated provider name.
- `ec2.overrides.name_sg`: Name tag used for the managed runner security group. An empty value uses the generated provider name.
- `ec2.instance_profile`: Optional externally managed instance profile used by the launch template.
- `ec2.instance_profile.name`: Name of the externally managed instance profile.
- `ec2.instance_profile_path`: IAM path for the provider-managed instance profile. Null uses a path derived from the runner-configuration prefix.
- `ec2.binaries_syncer`: Runner-distribution synchronization configuration.
- `ec2.binaries_syncer.enabled`: Enables use of a synchronized runner distribution from S3.
- `ec2.binaries_syncer.s3`: S3 object containing the synchronized runner distribution. Required when synchronization is enabled.
- `ec2.binaries_syncer.s3.arn`: ARN of the runner-distribution bucket, used by IAM policies.
- `ec2.binaries_syncer.s3.id`: Bucket name used to construct the runner-distribution S3 URI.
- `ec2.binaries_syncer.s3.key`: Object key of the runner distribution.
- `ec2.block_device_mappings`: EBS mappings added to the runner launch template.
- `ec2.block_device_mappings[].delete_on_termination`: Deletes the volume when its runner instance terminates.
- `ec2.block_device_mappings[].device_name`: Device name exposed to the runner instance.
- `ec2.block_device_mappings[].encrypted`: Enables EBS encryption.
- `ec2.block_device_mappings[].iops`: Provisioned IOPS for volume types that support it.
- `ec2.block_device_mappings[].kms_key_id`: KMS key ID or ARN used to encrypt the volume.
- `ec2.block_device_mappings[].snapshot_id`: Snapshot used to initialize the volume.
- `ec2.block_device_mappings[].throughput`: Provisioned throughput for volume types that support it.
- `ec2.block_device_mappings[].volume_initialization_rate`: Fixed initialization rate in MiB/s for supported snapshot-backed volumes.
- `ec2.block_device_mappings[].volume_size`: Volume size in GiB.
- `ec2.block_device_mappings[].volume_type`: EBS volume type.
- `ec2.ebs_optimized`: Requests EBS-optimized runner instances.
- `ec2.instance_target_capacity_type`: Primary capacity type, either `spot` or `on-demand`.
- `ec2.instance_allocation_strategy`: EC2 Fleet allocation strategy used to select instance capacity.
- `ec2.instance_type_priorities`: Optional numeric priorities keyed by instance type.
- `ec2.instance_max_spot_price`: Optional maximum hourly Spot price.
- `ec2.instance_types`: EC2 instance types available to the scale-up and pool functions.
- `ec2.user_data`: Runner bootstrap user-data configuration.
- `ec2.user_data.enabled`: Enables launch-template user data.
- `ec2.user_data.template`: Optional path to a custom user-data template.
- `ec2.user_data.content`: Optional complete user-data content. When set, it is used instead of rendering a template.
- `ec2.user_data.pre_install`: Script content inserted before runner installation in the default template.
- `ec2.user_data.post_install`: Script content inserted after runner installation in the default template.
- `ec2.user_data.debug_logging_enabled`: Enables verbose user-data tracing, which can expose secrets in logs.
- `ec2.ssm_enabled`: Attaches runner permissions and policies required for AWS Systems Manager access.
- `ec2.create_service_linked_role_spot`: Allows scale-up to create the EC2 Spot service-linked role.
- `ec2.cloudwatch_agent`: CloudWatch agent configuration for runner instances.
- `ec2.cloudwatch_agent.enabled`: Installs and configures the CloudWatch agent through the default bootstrap flow.
- `ec2.cloudwatch_agent.config`: Optional complete CloudWatch agent configuration. Null renders the provider default from `log_files`.
- `ec2.managed_security_group_enabled`: Creates and attaches the provider-managed runner security group.
- `ec2.log_files`: Optional log files collected by the CloudWatch agent. Null uses the provider defaults.
- `ec2.log_files[].log_group_name`: CloudWatch log-group name, before optional prefixing.
- `ec2.log_files[].prefix_log_group`: Prefixes the log-group name with the runner configuration path when true.
- `ec2.log_files[].file_path`: File or glob read by the CloudWatch agent.
- `ec2.log_files[].log_stream_name`: CloudWatch log-stream name template.
- `ec2.log_files[].log_class`: CloudWatch log-group class for the collected file.
- `ec2.key_name`: Optional EC2 key-pair name added to the launch template.
- `ec2.additional_security_group_ids`: Existing security groups attached in addition to the managed security group.
- `ec2.detailed_monitoring_enabled`: Enables detailed EC2 monitoring for runner instances.
- `ec2.egress_rules`: Egress rules created on the managed runner security group.
- `ec2.egress_rules[].cidr_blocks`: IPv4 CIDR destinations.
- `ec2.egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations.
- `ec2.egress_rules[].prefix_list_ids`: AWS prefix-list destinations.
- `ec2.egress_rules[].from_port`: First destination port in the permitted range.
- `ec2.egress_rules[].protocol`: IP protocol name or number. Use `-1` for all protocols.
- `ec2.egress_rules[].security_groups`: Destination security-group IDs.
- `ec2.egress_rules[].self`: Allows traffic to the managed security group itself when true.
- `ec2.egress_rules[].to_port`: Last destination port in the permitted range.
- `ec2.egress_rules[].description`: Optional rule description.
- `ec2.tags`: Additional tags for runner instances, EBS volumes, network interfaces, and eligible Spot instance requests created from the launch template. They override module-level tags and the generated runner `Name`; the provider-managed `ghr:environment`, `ghr:ssm_config_path`, and `ghr:runner_name_prefix` bootstrap tags take final precedence. These tags do not apply to static provider resources such as the launch template, security group, IAM resources, SSM parameters, or log groups.
- `ec2.metadata_options`: Instance Metadata Service configuration in the launch template.
- `ec2.metadata_options.instance_metadata_tags`: Exposes instance tags through Instance Metadata Service when `enabled`.
- `ec2.metadata_options.http_endpoint`: Enables or disables the Instance Metadata Service endpoint.
- `ec2.metadata_options.http_tokens`: Controls whether IMDSv2 session tokens are optional or required.
- `ec2.metadata_options.http_put_response_hop_limit`: Network hop limit for Instance Metadata Service token responses.
- `ec2.credit_specification`: CPU credit mode for burstable instance types, either `standard` or `unlimited`.
- `ec2.cpu_options`: CPU topology and processor-feature configuration.
- `ec2.cpu_options.core_count`: Number of CPU cores exposed to the runner instance.
- `ec2.cpu_options.threads_per_core`: Number of hardware threads exposed per CPU core.
- `ec2.cpu_options.amd_sev_snp`: Enables or disables AMD SEV-SNP on supported instance types.
- `ec2.cpu_options.nested_virtualization`: Enables or disables nested virtualization on supported instance types.
- `ec2.placement`: EC2 placement configuration for runner instances.
- `ec2.placement.affinity`: Host affinity setting.
- `ec2.placement.availability_zone`: Availability Zone in which the instance is placed.
- `ec2.placement.group_id`: Placement-group ID.
- `ec2.placement.group_name`: Placement-group name.
- `ec2.placement.host_id`: Dedicated Host ID.
- `ec2.placement.host_resource_group_arn`: ARN of the host resource group used for placement.
- `ec2.placement.spread_domain`: Spread-domain placement value.
- `ec2.placement.tenancy`: Instance tenancy, such as `default`, `dedicated`, or `host`.
- `ec2.placement.partition_number`: Placement-group partition number.
- `ec2.license_specifications`: License Manager configurations added to the launch template.
- `ec2.license_specifications[].license_configuration_arn`: ARN of a License Manager license configuration.
- `ec2.associate_public_ipv4_address`: Associates a public IPv4 address with runner network interfaces.
- `ec2.enable_on_demand_failover_for_errors`: EC2 error codes that trigger an on-demand fallback after a Spot launch failure.
- `ec2.scale_errors`: EC2 error codes treated as retryable scale-up failures.
- `ec2.use_dedicated_host`: Enables the dedicated-host launch path, required for macOS runners. |
object({
ec2 = optional(object({
ami = optional(object({
filter = optional(map(list(string)), { state = ["available"] })
owners = optional(list(string), ["amazon"])
id_ssm_parameter = optional(object({
arn = string
}), null)
kms_key = optional(object({
arn = string
}), null)
}), null)
vpc_id = string
subnet_ids = list(string)
overrides = optional(object({
name_runner = optional(string, "")
name_sg = optional(string, "")
}), {})
instance_profile = optional(object({
name = string
}), null)
instance_profile_path = optional(string, null)
binaries_syncer = optional(object({
enabled = optional(bool, true)
s3 = optional(object({
arn = string
id = string
key = string
}), null)
}), {})
block_device_mappings = optional(list(object({
delete_on_termination = optional(bool, true)
device_name = optional(string, "/dev/xvda")
encrypted = optional(bool, true)
iops = optional(number)
kms_key_id = optional(string)
snapshot_id = optional(string)
throughput = optional(number)
volume_initialization_rate = optional(number)
volume_size = number
volume_type = optional(string, "gp3")
})), [{ volume_size = 30 }])
ebs_optimized = optional(bool, false)
instance_target_capacity_type = optional(string, "spot")
instance_allocation_strategy = optional(string, "lowest-price")
instance_type_priorities = optional(map(number), null)
instance_max_spot_price = optional(string, null)
instance_types = list(string)
user_data = optional(object({
enabled = optional(bool, true)
template = optional(string, null)
content = optional(string, null)
pre_install = optional(string, "")
post_install = optional(string, "")
debug_logging_enabled = optional(bool, false)
}), {})
ssm_enabled = optional(bool, false)
create_service_linked_role_spot = optional(bool, false)
cloudwatch_agent = optional(object({
enabled = optional(bool, true)
config = optional(string, null)
}), {})
managed_security_group_enabled = optional(bool, true)
log_files = optional(list(object({
log_group_name = string
prefix_log_group = bool
file_path = string
log_stream_name = string
log_class = optional(string, "STANDARD")
})), null)
key_name = optional(string, null)
additional_security_group_ids = optional(list(string), [])
detailed_monitoring_enabled = optional(bool, false)
egress_rules = optional(list(object({
cidr_blocks = list(string)
ipv6_cidr_blocks = list(string)
prefix_list_ids = list(string)
from_port = number
protocol = string
security_groups = list(string)
self = bool
to_port = number
description = string
})), [{
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
prefix_list_ids = null
from_port = 0
protocol = "-1"
security_groups = null
self = null
to_port = 0
description = null
}])
tags = optional(map(string), {})
metadata_options = optional(object({
instance_metadata_tags = optional(string, "enabled")
http_endpoint = optional(string, "enabled")
http_tokens = optional(string, "required")
http_put_response_hop_limit = optional(number, 1)
}), {})
credit_specification = optional(string, null)
cpu_options = optional(object({
core_count = optional(number)
threads_per_core = optional(number)
amd_sev_snp = optional(string)
nested_virtualization = optional(string)
}), null)
placement = optional(object({
affinity = optional(string)
availability_zone = optional(string)
group_id = optional(string)
group_name = optional(string)
host_id = optional(string)
host_resource_group_arn = optional(string)
spread_domain = optional(string)
tenancy = optional(string)
partition_number = optional(number)
}), null)
license_specifications = optional(list(object({
license_configuration_arn = string
})), [])
associate_public_ipv4_address = optional(bool, false)
enable_on_demand_failover_for_errors = optional(list(string), [])
scale_errors = optional(list(string), [
"UnfulfillableCapacity",
"MaxSpotInstanceCountExceeded",
"TargetCapacityLimitExceededException",
"RequestLimitExceeded",
"ResourceLimitExceeded",
"MaxSpotInstanceCountExceeded",
"MaxSpotFleetRequestCountExceeded",
"InsufficientInstanceCapacity",
"InsufficientCapacityOnHost",
])
use_dedicated_host = optional(bool, false)
}), null)
})
| n/a | yes | +| [github](#input\_github) | GitHub API and runner-registration configuration.

- `app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys.
- `app_parameters.id`: Ordered Parameter Store references for GitHub App IDs.
- `app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs.
- `enterprise_server.url`: Optional GitHub Enterprise Server base URL. Null selects GitHub.com.
- `enterprise_server.ssl_verify`: Enables TLS certificate verification for GitHub Enterprise Server requests.
- `user_agent`: Optional User-Agent value added to GitHub API requests. |
object({
app_parameters = object({
key_base64 = list(map(string))
id = list(map(string))
installation_id = list(object({ name = string, arn = string }))
})
enterprise_server = optional(object({
url = optional(string, null)
ssl_verify = optional(bool, true)
}), {})
user_agent = optional(string, null)
})
| n/a | yes | +| [lambda](#input\_lambda) | Common Lambda substrate independent of the selected runner orchestration provider.

- `artifact.s3.bucket`: Optional shared S3 bucket containing component-owned Lambda artifacts. An orchestration provider selects its own object key and version; the bucket alone selects no artifact.
- `runtime`: Runtime used by the control-plane Lambda functions.
- `architecture`: Instruction-set architecture used by the control-plane Lambda functions. Supported values are `arm64` and `x86_64`.
- `subnet_ids`: Subnets used for Lambda VPC configuration.
- `security_group_ids`: Security groups used for Lambda VPC configuration.
- `tags`: Shared tags applied to Lambda function resources only. These override module-level `tags`; component `tags` override this map when keys conflict.
- `principals`: Additional principals allowed to assume the control-plane Lambda roles.
- `role.path`: IAM path for module-managed Lambda execution roles. Defaults to a path derived from `prefix`.
- `role.permissions_boundary`: Permissions-boundary ARN applied to module-managed Lambda execution roles. |
object({
artifact = optional(object({
s3 = optional(object({
bucket = optional(string, null)
}), {})
}), {})
runtime = optional(string, "nodejs24.x")
architecture = optional(string, "arm64")
subnet_ids = optional(list(string), [])
security_group_ids = optional(list(string), [])
tags = optional(map(string), {})
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
role = optional(object({
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
})
| `{}` | no | +| [observability](#input\_observability) | Logging, tracing, and metrics configuration for control-plane and provider resources.

- `logs.level`: Application log level supplied to the control-plane functions.
- `logs.retention_in_days`: CloudWatch Logs retention period.
- `logs.kms_key_id`: Optional KMS key ID or ARN used to encrypt CloudWatch log groups.
- `logs.class`: CloudWatch log-group class. Supported values are `STANDARD` and `INFREQUENT_ACCESS`.
- `logs.tags`: Shared tags for CloudWatch log groups. These override module-level `tags`; component `tags` override this map when keys conflict.
- `tracing.mode`: Optional Lambda active-tracing mode. Null disables X-Ray tracing configuration.
- `tracing.capture_http_requests`: Enables HTTP request capture in the tracing helper.
- `tracing.capture_error`: Enables error capture in the tracing helper.
- `metrics.enable`: Enables module-emitted metrics.
- `metrics.namespace`: CloudWatch namespace used for emitted metrics.
- `metrics.metric.enable_github_app_rate_limit`: Emits GitHub App rate-limit metrics.
- `metrics.metric.enable_job_retry`: Emits job-retry metrics.
- `metrics.metric.enable_spot_termination_warning`: Emits spot-termination warning metrics where supported. |
object({
logs = optional(object({
level = optional(string, "info")
retention_in_days = optional(number, 180)
kms_key_id = optional(string, null)
class = optional(string, "STANDARD")
tags = optional(map(string), {})
}), {})
tracing = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
}), {})
metrics = optional(object({
enable = optional(bool, false)
namespace = optional(string, "GitHub Runners")
metric = optional(object({
enable_github_app_rate_limit = optional(bool, true)
enable_job_retry = optional(bool, true)
enable_spot_termination_warning = optional(bool, true)
}), {})
}), {})
})
| `{}` | no | +| [orchestration](#input\_orchestration) | Runner demand-orchestration provider configuration. Exactly one provider block must be non-null.

`webhook` is the currently supported provider. It owns the build queue reference, the runner-control
artifact shared by scale, pool, and job-retry, runner lifecycle and capacity limits, scale-up, scale-down, and scheduled pool
controls. Wrapper presence selects the provider and must therefore be known during planning. Future
providers can be added as sibling blocks without moving the webhook contract again. |
object({
webhook = optional(object({
runner = optional(object({
boot_time_in_minutes = optional(number, 5)
ephemeral = optional(bool, false)
jit_config_enabled = optional(bool, null)
maximum_count = optional(number, 3)
}), {})
github = object({
organization_runners = bool
})
queue = object({
build = object({
arn = string
url = string
})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
scale = optional(object({
up = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
reserved_concurrent_executions = optional(number, 1)
job_queued_check_enabled = optional(bool, null)
event_source_mapping = optional(object({
batch_size = optional(number, 10)
maximum_batching_window_in_seconds = optional(number, 0)
}), {})
tags = optional(map(string), {})
}), {})
down = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
schedule_expression = optional(string, "cron(*/5 * * * ? *)")
minimum_running_time_in_minutes = optional(number, null)
tags = optional(map(string), {})
idle_config = optional(list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = optional(string, "oldest_first")
})), [])
}), {})
}), {})
pool = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
reserved_concurrent_executions = optional(number, 1)
config = optional(list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
})), [])
include_busy_runners = optional(bool, false)
runner_owner = optional(string, null)
tags = optional(map(string), {})
}), {})
}), {})
job_retry = optional(object({
enabled = optional(bool, false)
delay_in_seconds = optional(number, 300)
delay_backoff = optional(number, 2)
max_attempts = optional(number, 1)
tags = optional(map(string), {})
lambda = optional(object({
memory_size = optional(number, 256)
reserved_concurrent_executions = optional(number, 1)
timeout = optional(number, 30)
}), {})
}), {})
}), null)
})
| n/a | yes | +| [prefix](#input\_prefix) | The prefix used for naming resources. | `string` | `"github-actions"` | no | +| [runner](#input\_runner) | Provider-neutral GitHub runner configuration.

- `os`: Runner operating system. Supported values are `linux`, `osx`, and `windows`.
- `architecture`: Runner distribution architecture, such as `x64` or `arm64`.
- `disable_default_labels`: Prevents GitHub's default self-hosted, operating-system, and architecture labels from being registered.
- `labels`: Complete set of labels supplied to the control-plane functions.
- `group_name`: GitHub runner group used during registration.
- `name_prefix`: Prefix added to registered runner names.
- `run_as_root`: Runs the runner service as root when supported by the compute provider.
- `run_as`: Operating-system user used when `run_as_root` is false.
- `auto_update_disabled`: Disables the GitHub runner application's built-in updater.
- `tags`: Additional tags for common runner resources, currently the managed runner IAM role. These override module-level `tags` with the same key.
- `hooks.job_started`: Script content installed as the runner job-started hook.
- `hooks.job_completed`: Script content installed as the runner job-completed hook.
- `iam.role.arn`: ARN of an externally managed runner role. When set, this module does not create or modify that role.
- `iam.managed_policy_arns`: Named managed-policy ARNs attached to the module-managed runner role.
- `iam.additional_trust_policy_json`: Optional IAM policy document merged with the selected compute provider's default runner-role trust policy.
- `iam.path`: IAM path for the module-managed runner role. Defaults to a path derived from `prefix`.
- `iam.permissions_boundary`: Permissions-boundary ARN for the module-managed runner role. |
object({
os = optional(string, "linux")
architecture = optional(string, "x64")
disable_default_labels = optional(bool, false)
labels = list(string)
group_name = optional(string, "Default")
name_prefix = optional(string, "")
run_as_root = optional(bool, false)
run_as = optional(string, "ec2-user")
auto_update_disabled = optional(bool, false)
tags = optional(map(string), {})
hooks = optional(object({
job_started = optional(string, "")
job_completed = optional(string, "")
}), {})
iam = optional(object({
role = optional(object({
arn = string
}), null)
managed_policy_arns = optional(map(string), {})
additional_trust_policy_json = optional(string, null)
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
})
| n/a | yes | +| [ssm](#input\_ssm) | Parameter Store paths, encryption, tag scopes, and housekeeper configuration.

- `paths.root`: Root Parameter Store path for this runner configuration.
- `paths.tokens`: Path segment under `paths.root` used for registration tokens and just-in-time configuration.
- `paths.config`: Path segment under `paths.root` used for persistent runner configuration.
- `kms_key_id`: Optional customer-managed KMS key ARN used by control-plane IAM policies to decrypt shared GitHub App parameters. The ARN may be unknown until apply; null omits the provider-owned KMS statements. It does not select encryption for runtime-created runner parameters.
- `tags`: Shared tags for SSM-related resources. These override module-level `tags` and are inherited by parameter and housekeeper resources.
- `parameters.tags`: Tags for Terraform-managed runner configuration parameters and temporary parameters created by the scale-up and pool Lambdas. These override module-level and `ssm.tags` values with the same key.
- `housekeeper.schedule_expression`: EventBridge schedule expression that invokes the SSM housekeeper.
- `housekeeper.state`: EventBridge rule state, such as `ENABLED` or `DISABLED`.
- `housekeeper.tags`: Tags for housekeeper resources, including the Lambda function, log group, EventBridge rule, and IAM role. These override module-level, `ssm.tags`, shared Lambda, and shared log tags when keys conflict.
- `housekeeper.lambda.artifact`: Component-owned SSM-housekeeper artifact selection. Set at most one of `zip` or `s3`; when neither is selected, the module uses its packaged runner control-plane archive. This selector does not inherit an orchestration-provider artifact.
- `housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive.
- `housekeeper.lambda.artifact.s3`: Optional object key and version in the shared `lambda.artifact.s3.bucket`. Selecting S3 requires that common bucket.
- `housekeeper.lambda.artifact.s3.key`: Object key of the SSM-housekeeper Lambda archive.
- `housekeeper.lambda.artifact.s3.object_version`: Optional object version of the SSM-housekeeper Lambda archive.
- `housekeeper.lambda.memory_size`: Memory allocated to the SSM housekeeper Lambda in MB.
- `housekeeper.lambda.timeout`: SSM housekeeper Lambda timeout in seconds.
- `housekeeper.config.tokenPath`: Parameter Store token path cleaned by the housekeeper. When omitted, the configured runner token path is used.
- `housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed.
- `housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true. |
object({
paths = object({
root = string
tokens = string
config = string
})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
}), {})
housekeeper = optional(object({
schedule_expression = optional(string, "rate(1 day)")
state = optional(string, "ENABLED")
tags = optional(map(string), {})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
memory_size = optional(number, 512)
timeout = optional(number, 60)
}), {})
config = optional(object({
tokenPath = optional(string)
minimumDaysOld = optional(number, 1)
dryRun = optional(bool, false)
}), {})
}), {})
})
| n/a | yes | +| [tags](#input\_tags) | Base tags added to taggable resources created by this runner configuration. Shared, component, and compute-provider tag maps override matching keys within their documented resource scopes. | `map(string)` | `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [orchestration](#output\_orchestration) | Resources grouped under the selected runner orchestration provider. | +| [pool](#output\_pool) | Scheduled pool resources. Null when no pool configuration is supplied. | +| [provider](#output\_provider) | Provider-specific resources grouped under the selected provider key. | +| [runner](#output\_runner) | Common runner resources. The role is null when an external runner role is used. | +| [scale\_down](#output\_scale\_down) | Scale-down control-plane resources. Null when webhook orchestration is not configured. | +| [scale\_up](#output\_scale\_up) | Scale-up control-plane resources. Null when webhook orchestration is not configured. | + diff --git a/modules/runner-config/common-config.tf b/modules/runner-config/common-config.tf new file mode 100644 index 0000000000..67b9cc1d07 --- /dev/null +++ b/modules/runner-config/common-config.tf @@ -0,0 +1,54 @@ +# Shared control-plane configuration: naming, paths, tags, and normalized values. +locals { + common_tags = var.tags + runner_tags = merge(local.common_tags, var.runner.tags) + lambda_tags = merge(local.common_tags, var.lambda.tags) + observability_log_tags = merge(local.common_tags, var.observability.logs.tags) + + ssm_tags = merge(local.common_tags, var.ssm.tags) + ssm_parameter_tags = merge(local.ssm_tags, var.ssm.parameters.tags) + ssm_housekeeper_tags = merge(local.ssm_tags, var.ssm.housekeeper.tags) + ssm_housekeeper_lambda_tags = merge(local.lambda_tags, var.ssm.tags, var.ssm.housekeeper.tags) + ssm_housekeeper_log_tags = merge(local.observability_log_tags, var.ssm.tags, var.ssm.housekeeper.tags) + + lambda_role_path = var.lambda.role.path == null ? "/${var.prefix}/" : var.lambda.role.path + runner_role_path = var.runner.iam.path == null ? "/${var.prefix}/" : var.runner.iam.path + packaged_runners_lambda_zip = "${path.module}/../../lambdas/functions/control-plane/runners.zip" + ssm_housekeeper_artifact_s3_selected = ( + var.ssm.housekeeper.lambda.artifact.s3 != null + ) + ssm_housekeeper_artifact = { + zip = local.ssm_housekeeper_artifact_s3_selected ? null : coalesce( + var.ssm.housekeeper.lambda.artifact.zip, + local.packaged_runners_lambda_zip, + ) + s3 = { + bucket = local.ssm_housekeeper_artifact_s3_selected ? var.lambda.artifact.s3.bucket : null + key = try(var.ssm.housekeeper.lambda.artifact.s3.key, null) + object_version = try(var.ssm.housekeeper.lambda.artifact.s3.object_version, null) + } + } + kms_key_id = var.ssm.kms_key_id + token_path = "${var.ssm.paths.root}/${var.ssm.paths.tokens}" + arn_ssm_parameters_path_tokens = "arn:${var.aws_partition}:ssm:${var.aws_region}:${data.aws_caller_identity.current.account_id}:parameter${var.ssm.paths.root}/${var.ssm.paths.tokens}" + arn_ssm_parameters_path_config = "arn:${var.aws_partition}:ssm:${var.aws_region}:${data.aws_caller_identity.current.account_id}:parameter${var.ssm.paths.root}/${var.ssm.paths.config}" + + parameter_store_tags = jsonencode([ + for key, value in local.ssm_parameter_tags : { + Key = key + Value = value + } + ]) +} + +data "aws_caller_identity" "current" { + lifecycle { + precondition { + condition = ( + var.ssm.housekeeper.lambda.artifact.s3 == null || + var.lambda.artifact.s3.bucket != null + ) + error_message = "lambda.artifact.s3.bucket must be set when ssm.housekeeper.lambda.artifact.s3 is selected." + } + } +} diff --git a/modules/runner-config/compute-provider.tf b/modules/runner-config/compute-provider.tf new file mode 100644 index 0000000000..78e00bf03c --- /dev/null +++ b/modules/runner-config/compute-provider.tf @@ -0,0 +1,18 @@ +locals { + provider_type = one([ + for provider_type, provider_config in var.compute_provider : provider_type + if provider_config != null + ]) + + provider_assume_role_policies = { + ec2 = try(module.ec2_trust_policy[0].assume_role_policy, null) + } + + provider_assume_role_policy = local.provider_assume_role_policies[local.provider_type] + + provider_contracts = { + ec2 = one(module.ec2[*].provider) + } + + provider_contract = local.provider_contracts[local.provider_type] +} diff --git a/modules/runner-config/ec2.tf b/modules/runner-config/ec2.tf new file mode 100644 index 0000000000..071174f859 --- /dev/null +++ b/modules/runner-config/ec2.tf @@ -0,0 +1,27 @@ +module "ec2_trust_policy" { + count = local.provider_type == "ec2" ? 1 : 0 + source = "../compute-providers/ec2/trust-policy" + + additional_trust_policy_json = var.runner.iam.additional_trust_policy_json +} + +module "ec2" { + count = local.provider_type == "ec2" ? 1 : 0 + source = "../compute-providers/ec2" + + aws_partition = var.aws_partition + aws_region = var.aws_region + prefix = var.prefix + tags = var.tags + + config = var.compute_provider.ec2 + runner = merge(var.runner, { + iam = merge(var.runner.iam, { + role = local.runner_role + managed_policy_arns = local.common_runner_managed_policy_arns + }) + }) + github = var.github + ssm = var.ssm + observability = var.observability +} diff --git a/modules/runner-config/orchestration-provider.tf b/modules/runner-config/orchestration-provider.tf new file mode 100644 index 0000000000..f7d8d7ab7d --- /dev/null +++ b/modules/runner-config/orchestration-provider.tf @@ -0,0 +1,91 @@ +locals { + orchestration_providers = { + for provider_type, provider_config in var.orchestration : provider_type => provider_config + if provider_config != null + } + + orchestration_provider_type = one(keys(local.orchestration_providers)) + + orchestration_provider_enabled = { + webhook = local.orchestration_provider_type == "webhook" + } + + orchestration_provider_runner_lifecycle = { + webhook = one([for provider in values(module.webhook) : provider.runner_lifecycle]) + }[local.orchestration_provider_type] +} + +moved { + from = module.scale_runners + to = module.webhook["webhook"].module.scale_runners +} + +moved { + from = module.pool + to = module.webhook["webhook"].module.pool +} + +moved { + from = module.job_retry + to = module.webhook["webhook"].module.job_retry +} + +module "webhook" { + source = "../orchestration-providers/webhook" + for_each = { + for provider_type, provider_config in local.orchestration_providers : provider_type => provider_config + if provider_type == "webhook" + } + + aws_partition = var.aws_partition + prefix = var.prefix + tags = var.tags + + config = each.value + runner = var.runner + github = var.github + lambda = { + artifact = var.lambda.artifact + runtime = var.lambda.runtime + architecture = var.lambda.architecture + subnet_ids = var.lambda.subnet_ids + security_group_ids = var.lambda.security_group_ids + tags = var.lambda.tags + role = { + path = local.lambda_role_path + permissions_boundary = var.lambda.role.permissions_boundary + principals = var.lambda.principals + } + } + ssm = { + token_path = local.token_path + token_path_arn = local.arn_ssm_parameters_path_tokens + config_path = "${var.ssm.paths.root}/${var.ssm.paths.config}" + config_path_arn = local.arn_ssm_parameters_path_config + kms_key_id = local.kms_key_id + parameter_store_tags = local.parameter_store_tags + } + observability = var.observability + + runner_provider = { + type = local.provider_type + scale_up = { + environment_variables = local.provider_contract.environment_variables.scale_up + iam_policy_json = local.provider_contract.policies.scale_up.iam_policy_json + additional_iam_policy_json = local.provider_contract.policies.scale_up.additional_iam_policy_json + managed_policy = local.provider_contract.policies.scale_up.managed_policy_enabled ? { + arn = local.provider_contract.policies.scale_up.managed_policy_arn + } : null + } + scale_down = { + environment_variables = local.provider_contract.environment_variables.scale_down + iam_policy_json = local.provider_contract.policies.scale_down.iam_policy_json + } + pool = { + environment_variables = local.provider_contract.environment_variables.pool + iam_policy_json = local.provider_contract.policies.pool.iam_policy_json + managed_policy_enabled = local.provider_contract.policies.pool.managed_policy_enabled + managed_policy_arn = local.provider_contract.policies.pool.managed_policy_arn + } + } +} diff --git a/modules/runner-config/outputs.tf b/modules/runner-config/outputs.tf new file mode 100644 index 0000000000..6a2ec80e86 --- /dev/null +++ b/modules/runner-config/outputs.tf @@ -0,0 +1,40 @@ +output "runner" { + description = "Common runner resources. The role is null when an external runner role is used." + value = { + role = one(aws_iam_role.runner[*]) + } +} + +output "scale_up" { + description = "Scale-up control-plane resources. Null when webhook orchestration is not configured." + value = one([for provider in values(module.webhook) : provider.scale_up]) +} + +output "scale_down" { + description = "Scale-down control-plane resources. Null when webhook orchestration is not configured." + value = one([for provider in values(module.webhook) : provider.scale_down]) +} + +output "pool" { + description = "Scheduled pool resources. Null when no pool configuration is supplied." + value = one([for provider in values(module.webhook) : provider.pool]) +} + +output "orchestration" { + description = "Resources grouped under the selected runner orchestration provider." + value = { + webhook = local.orchestration_provider_enabled.webhook ? { + scale_up = one([for provider in values(module.webhook) : provider.scale_up]) + scale_down = one([for provider in values(module.webhook) : provider.scale_down]) + pool = one([for provider in values(module.webhook) : provider.pool]) + job_retry = one([for provider in values(module.webhook) : provider.job_retry]) + } : null + } +} + +output "provider" { + description = "Provider-specific resources grouped under the selected provider key." + value = { + (local.provider_type) = local.provider_contract.resources + } +} diff --git a/modules/runner-config/runner-role.tf b/modules/runner-config/runner-role.tf new file mode 100644 index 0000000000..6baa1e4206 --- /dev/null +++ b/modules/runner-config/runner-role.tf @@ -0,0 +1,48 @@ +locals { + # Role ownership belongs to the common runner configuration. The selected trust-policy + # submodule supplies the assume-role document, while the full compute provider + # supplies permissions after the role has been resolved. + create_runner_role = var.runner.iam.role == null + + runner_role = { + arn = local.create_runner_role ? one(aws_iam_role.runner[*].arn) : var.runner.iam.role.arn + name = local.create_runner_role ? one(aws_iam_role.runner[*].name) : basename(var.runner.iam.role.arn) + managed = local.create_runner_role + } + + common_runner_managed_policy_arns = merge( + { + for policy_name, policy_arn in var.runner.iam.managed_policy_arns : + "user-${policy_name}" => policy_arn + }, + var.observability.tracing.mode != null ? { + xray = "arn:${var.aws_partition}:iam::aws:policy/AWSXRayDaemonWriteAccess" + } : {}, + ) + + provider_runner_policies = local.provider_contract.policies.runner +} + +resource "aws_iam_role" "runner" { + count = local.create_runner_role ? 1 : 0 + name = "${substr("${var.prefix}-runner", 0, 54)}-${substr(md5("${var.prefix}-runner"), 0, 8)}" + assume_role_policy = local.provider_assume_role_policy + path = local.runner_role_path + permissions_boundary = var.runner.iam.permissions_boundary + tags = local.runner_tags +} + +resource "aws_iam_role_policy" "runner_provider" { + for_each = local.create_runner_role ? local.provider_runner_policies.inline_policies : {} + + name = each.value.name + role = aws_iam_role.runner[0].name + policy = each.value.policy_json +} + +resource "aws_iam_role_policy_attachment" "runner" { + for_each = local.create_runner_role ? local.provider_runner_policies.managed_policy_arns : {} + + role = aws_iam_role.runner[0].name + policy_arn = each.value +} diff --git a/modules/runner-config/runner-ssm-parameters.tf b/modules/runner-config/runner-ssm-parameters.tf new file mode 100644 index 0000000000..1d97c908a8 --- /dev/null +++ b/modules/runner-config/runner-ssm-parameters.tf @@ -0,0 +1,28 @@ +# Shared runner configuration stored in SSM Parameter Store. +resource "aws_ssm_parameter" "runner_agent_mode" { + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/agent_mode" + type = "String" + value = local.orchestration_provider_runner_lifecycle.ephemeral ? "ephemeral" : "persistent" + tags = local.ssm_parameter_tags +} + +resource "aws_ssm_parameter" "disable_default_labels" { + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/disable_default_labels" + type = "String" + value = var.runner.disable_default_labels + tags = local.ssm_parameter_tags +} + +resource "aws_ssm_parameter" "jit_config_enabled" { + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/enable_jit_config" + type = "String" + value = local.orchestration_provider_runner_lifecycle.jit_config_enabled + tags = local.ssm_parameter_tags +} + +resource "aws_ssm_parameter" "token_path" { + name = "${var.ssm.paths.root}/${var.ssm.paths.config}/token_path" + type = "String" + value = "${var.ssm.paths.root}/${var.ssm.paths.tokens}" + tags = local.ssm_parameter_tags +} diff --git a/modules/runner-config/ssm-housekeeper.tf b/modules/runner-config/ssm-housekeeper.tf new file mode 100644 index 0000000000..5bb31bb7b5 --- /dev/null +++ b/modules/runner-config/ssm-housekeeper.tf @@ -0,0 +1,57 @@ +locals { + ssm_housekeeper_token_path = coalesce(var.ssm.housekeeper.config.tokenPath, local.token_path) + ssm_housekeeper_parameter_path_arn = ( + "arn:${var.aws_partition}:ssm:${var.aws_region}:${data.aws_caller_identity.current.account_id}:parameter${local.ssm_housekeeper_token_path}*" + ) +} + +module "ssm_housekeeper" { + source = "./ssm-housekeeper" + + config = { + prefix = var.prefix + aws_partition = var.aws_partition + schedule = { + expression = var.ssm.housekeeper.schedule_expression + state = var.ssm.housekeeper.state + } + cleanup = { + token_path = local.ssm_housekeeper_token_path + parameter_path_arn = local.ssm_housekeeper_parameter_path_arn + minimum_days_old = var.ssm.housekeeper.config.minimumDaysOld + dry_run = var.ssm.housekeeper.config.dryRun + } + lambda = { + # The housekeeper resolves only its component-owned selector and never + # inherits the selected orchestration provider's runner-control artifact. + artifact = local.ssm_housekeeper_artifact + runtime = var.lambda.runtime + architecture = var.lambda.architecture + memory_size = var.ssm.housekeeper.lambda.memory_size + timeout = var.ssm.housekeeper.lambda.timeout + vpc = { + subnet_ids = var.lambda.subnet_ids + security_group_ids = var.lambda.security_group_ids + } + role = { + path = local.lambda_role_path + permissions_boundary = var.lambda.role.permissions_boundary + principals = var.lambda.principals + } + } + observability = { + logs = { + level = var.observability.logs.level + retention_in_days = var.observability.logs.retention_in_days + kms_key_id = var.observability.logs.kms_key_id + class = var.observability.logs.class + } + tracing = var.observability.tracing + } + tags = { + resources = local.ssm_housekeeper_tags + lambda = local.ssm_housekeeper_lambda_tags + log_group = local.ssm_housekeeper_log_tags + } + } +} diff --git a/modules/runner-config/ssm-housekeeper/README.md b/modules/runner-config/ssm-housekeeper/README.md new file mode 100644 index 0000000000..5f5d1ad166 --- /dev/null +++ b/modules/runner-config/ssm-housekeeper/README.md @@ -0,0 +1,57 @@ +# SSM housekeeper module + +> This module is treated as an internal module; breaking changes do not trigger a major release bump. + +This provider-neutral child module owns the Lambda function, EventBridge schedule, IAM policies, and CloudWatch log group used to remove expired runner registration parameters from Parameter Store. + +The module is an implementation detail of the experimental runner configuration. It is composed by `runner-config` and is not intended to be called directly. + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 6.33 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.33 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_cloudwatch_event_rule.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_rule) | resource | +| [aws_cloudwatch_event_target.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_target) | resource | +| [aws_cloudwatch_log_group.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource | +| [aws_iam_role.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource | +| [aws_iam_role_policy.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.ssm_housekeeper_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy.ssm_housekeeper_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy) | resource | +| [aws_iam_role_policy_attachment.ssm_housekeeper_vpc_execution_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource | +| [aws_lambda_function.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource | +| [aws_lambda_permission.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource | +| [aws_iam_policy_document.lambda_assume_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.lambda_xray](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.ssm_housekeeper](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | +| [aws_iam_policy_document.ssm_housekeeper_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [config](#input\_config) | Provider-neutral SSM housekeeper configuration assembled by runner-config.

- `prefix`: Prefix used to name the housekeeper resources.
- `aws_partition`: AWS partition used to construct IAM policy ARNs.
- `schedule.expression`: EventBridge schedule expression that invokes the housekeeper.
- `schedule.state`: State of the EventBridge rule.
- `cleanup.token_path`: Parameter Store token path supplied to the Lambda.
- `cleanup.parameter_path_arn`: IAM resource ARN matching `cleanup.token_path`.
- `cleanup.minimum_days_old`: Minimum parameter age before deletion.
- `cleanup.dry_run`: Reports eligible parameters without deleting them when true.
- `lambda.artifact.zip`: Resolved local control-plane archive.
- `lambda.artifact.s3.bucket`: Optional S3 bucket containing the Lambda archive.
- `lambda.artifact.s3.key`: Object key of the Lambda archive.
- `lambda.artifact.s3.object_version`: Optional object version of the Lambda archive.
- `lambda.runtime`: Runtime used by the housekeeper Lambda.
- `lambda.architecture`: Instruction-set architecture used by the housekeeper Lambda.
- `lambda.memory_size`: Memory allocated to the housekeeper Lambda.
- `lambda.timeout`: Housekeeper Lambda timeout in seconds.
- `lambda.vpc.subnet_ids`: Subnets used for Lambda VPC configuration.
- `lambda.vpc.security_group_ids`: Security groups used for Lambda VPC configuration.
- `lambda.role.path`: IAM path used for the housekeeper Lambda role.
- `lambda.role.permissions_boundary`: Optional permissions boundary for the housekeeper role.
- `lambda.role.principals`: Additional principals allowed to assume the housekeeper Lambda role.
- `observability.logs`: Logging level, retention, encryption, and log-class configuration.
- `observability.tracing`: Lambda X-Ray and tracing-helper configuration.
- `tags.resources`: Tags for the housekeeper role and EventBridge rule.
- `tags.lambda`: Tags for the housekeeper Lambda function.
- `tags.log_group`: Tags for the housekeeper log group. |
object({
prefix = string
aws_partition = string
schedule = object({
expression = string
state = string
})
cleanup = object({
token_path = string
parameter_path_arn = string
minimum_days_old = number
dry_run = bool
})
lambda = object({
artifact = object({
zip = string
s3 = object({
bucket = optional(string, null)
key = optional(string, null)
object_version = optional(string, null)
})
})
runtime = string
architecture = string
memory_size = number
timeout = number
vpc = object({
subnet_ids = list(string)
security_group_ids = list(string)
})
role = object({
path = string
permissions_boundary = optional(string, null)
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
})
})
observability = object({
logs = object({
level = string
retention_in_days = number
kms_key_id = optional(string, null)
class = string
})
tracing = object({
mode = optional(string, null)
capture_http_requests = bool
capture_error = bool
})
})
tags = object({
resources = map(string)
lambda = map(string)
log_group = map(string)
})
})
| n/a | yes | + +## Outputs + +| Name | Description | +|------|-------------| +| [housekeeper](#output\_housekeeper) | SSM housekeeper Lambda resources. | + diff --git a/modules/runner-config/ssm-housekeeper/iam-policies.tf b/modules/runner-config/ssm-housekeeper/iam-policies.tf new file mode 100644 index 0000000000..8d3bab2865 --- /dev/null +++ b/modules/runner-config/ssm-housekeeper/iam-policies.tf @@ -0,0 +1,58 @@ +data "aws_iam_policy_document" "lambda_assume_role" { + statement { + actions = ["sts:AssumeRole"] + + principals { + type = "Service" + identifiers = ["lambda.amazonaws.com"] + } + + dynamic "principals" { + for_each = var.config.lambda.role.principals + + content { + type = principals.value.type + identifiers = principals.value.identifiers + } + } + } +} + +data "aws_iam_policy_document" "lambda_xray" { + count = var.config.observability.tracing.mode != null ? 1 : 0 + + # AWS X-Ray trace APIs do not support resource-level permissions. + statement { + sid = "AllowXRay" + effect = "Allow" + actions = [ + "xray:BatchGetTraces", + "xray:GetTraceSummaries", + "xray:PutTelemetryRecords", + "xray:PutTraceSegments", + ] + resources = ["*"] + } +} + +data "aws_iam_policy_document" "ssm_housekeeper" { + statement { + effect = "Allow" + actions = [ + "ssm:DeleteParameter", + "ssm:GetParametersByPath", + ] + resources = [var.config.cleanup.parameter_path_arn] + } +} + +data "aws_iam_policy_document" "ssm_housekeeper_logging" { + statement { + effect = "Allow" + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + ] + resources = ["${aws_cloudwatch_log_group.ssm_housekeeper.arn}*"] + } +} diff --git a/modules/runner-config/ssm-housekeeper/outputs.tf b/modules/runner-config/ssm-housekeeper/outputs.tf new file mode 100644 index 0000000000..064f5a1ab1 --- /dev/null +++ b/modules/runner-config/ssm-housekeeper/outputs.tf @@ -0,0 +1,8 @@ +output "housekeeper" { + description = "SSM housekeeper Lambda resources." + value = { + lambda = aws_lambda_function.ssm_housekeeper + log_group = aws_cloudwatch_log_group.ssm_housekeeper + role = aws_iam_role.ssm_housekeeper + } +} diff --git a/modules/runner-config/ssm-housekeeper/ssm-housekeeper.tf b/modules/runner-config/ssm-housekeeper/ssm-housekeeper.tf new file mode 100644 index 0000000000..bcafed201a --- /dev/null +++ b/modules/runner-config/ssm-housekeeper/ssm-housekeeper.tf @@ -0,0 +1,119 @@ +locals { + vpc_enabled = ( + length(var.config.lambda.vpc.subnet_ids) > 0 && + length(var.config.lambda.vpc.security_group_ids) > 0 + ) + + cleanup_config = { + tokenPath = var.config.cleanup.token_path + minimumDaysOld = var.config.cleanup.minimum_days_old + dryRun = var.config.cleanup.dry_run + } +} + +resource "aws_lambda_function" "ssm_housekeeper" { + s3_bucket = var.config.lambda.artifact.s3.bucket + s3_key = var.config.lambda.artifact.s3.key + s3_object_version = var.config.lambda.artifact.s3.object_version + filename = var.config.lambda.artifact.s3.bucket == null ? var.config.lambda.artifact.zip : null + source_code_hash = var.config.lambda.artifact.s3.bucket == null ? filebase64sha256(var.config.lambda.artifact.zip) : null + function_name = "${var.config.prefix}-ssm-housekeeper" + role = aws_iam_role.ssm_housekeeper.arn + handler = "index.ssmHousekeeper" + runtime = var.config.lambda.runtime + timeout = var.config.lambda.timeout + tags = var.config.tags.lambda + memory_size = var.config.lambda.memory_size + architectures = [var.config.lambda.architecture] + + environment { + variables = { + ENVIRONMENT = var.config.prefix + LOG_LEVEL = upper(var.config.observability.logs.level) + SSM_CLEANUP_CONFIG = jsonencode(local.cleanup_config) + POWERTOOLS_SERVICE_NAME = "${var.config.prefix}-ssm-housekeeper" + POWERTOOLS_TRACE_ENABLED = var.config.observability.tracing.mode != null + POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS = var.config.observability.tracing.capture_http_requests + POWERTOOLS_TRACER_CAPTURE_ERROR = var.config.observability.tracing.capture_error + } + } + + dynamic "vpc_config" { + for_each = local.vpc_enabled ? [true] : [] + + content { + security_group_ids = var.config.lambda.vpc.security_group_ids + subnet_ids = var.config.lambda.vpc.subnet_ids + } + } + + dynamic "tracing_config" { + for_each = var.config.observability.tracing.mode != null ? [true] : [] + + content { + mode = var.config.observability.tracing.mode + } + } +} + +resource "aws_cloudwatch_log_group" "ssm_housekeeper" { + name = "/aws/lambda/${aws_lambda_function.ssm_housekeeper.function_name}" + retention_in_days = var.config.observability.logs.retention_in_days + kms_key_id = var.config.observability.logs.kms_key_id + log_group_class = var.config.observability.logs.class + tags = var.config.tags.log_group +} + +resource "aws_cloudwatch_event_rule" "ssm_housekeeper" { + name = "${var.config.prefix}-ssm-housekeeper" + schedule_expression = var.config.schedule.expression + state = var.config.schedule.state + tags = var.config.tags.resources +} + +resource "aws_cloudwatch_event_target" "ssm_housekeeper" { + rule = aws_cloudwatch_event_rule.ssm_housekeeper.name + arn = aws_lambda_function.ssm_housekeeper.arn +} + +resource "aws_lambda_permission" "ssm_housekeeper" { + statement_id = "AllowExecutionFromCloudWatch" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.ssm_housekeeper.function_name + principal = "events.amazonaws.com" + source_arn = aws_cloudwatch_event_rule.ssm_housekeeper.arn +} + +resource "aws_iam_role" "ssm_housekeeper" { + name = "${substr("${var.config.prefix}-ssm-hk-lambda", 0, 54)}-${substr(md5("${var.config.prefix}-ssm-hk-lambda"), 0, 8)}" + description = "Lambda role for SSM Housekeeper (${var.config.prefix})" + assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json + path = var.config.lambda.role.path + permissions_boundary = var.config.lambda.role.permissions_boundary + tags = var.config.tags.resources +} + +resource "aws_iam_role_policy" "ssm_housekeeper" { + name = "ssm-policy" + role = aws_iam_role.ssm_housekeeper.name + policy = data.aws_iam_policy_document.ssm_housekeeper.json +} + +resource "aws_iam_role_policy" "ssm_housekeeper_logging" { + name = "logging-policy" + role = aws_iam_role.ssm_housekeeper.name + policy = data.aws_iam_policy_document.ssm_housekeeper_logging.json +} + +resource "aws_iam_role_policy_attachment" "ssm_housekeeper_vpc_execution_role" { + count = local.vpc_enabled ? 1 : 0 + role = aws_iam_role.ssm_housekeeper.name + policy_arn = "arn:${var.config.aws_partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" +} + +resource "aws_iam_role_policy" "ssm_housekeeper_xray" { + count = var.config.observability.tracing.mode != null ? 1 : 0 + name = "xray-policy" + policy = data.aws_iam_policy_document.lambda_xray[0].json + role = aws_iam_role.ssm_housekeeper.name +} diff --git a/modules/runner-config/ssm-housekeeper/tests/ssm-housekeeper.tftest.hcl b/modules/runner-config/ssm-housekeeper/tests/ssm-housekeeper.tftest.hcl new file mode 100644 index 0000000000..bac30c6752 --- /dev/null +++ b/modules/runner-config/ssm-housekeeper/tests/ssm-housekeeper.tftest.hcl @@ -0,0 +1,263 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } + + mock_resource "aws_iam_role" { + defaults = { + arn = "arn:aws:iam::123456789012:role/ssm-housekeeper-test" + } + } + + mock_resource "aws_lambda_function" { + defaults = { + arn = "arn:aws:lambda:eu-west-1:123456789012:function:ssm-housekeeper-test" + } + } + + mock_resource "aws_cloudwatch_event_rule" { + defaults = { + arn = "arn:aws:events:eu-west-1:123456789012:rule/ssm-housekeeper-test" + } + } + + mock_resource "aws_cloudwatch_log_group" { + defaults = { + arn = "arn:aws:logs:eu-west-1:123456789012:log-group:/aws/lambda/ssm-housekeeper-test" + } + } +} + +variables { + config = { + prefix = "ssm-housekeeper-test" + aws_partition = "aws-us-gov" + schedule = { + expression = "rate(6 hours)" + state = "DISABLED" + } + cleanup = { + token_path = "/custom/runner/tokens" + parameter_path_arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/custom/runner/tokens*" + minimum_days_old = 7 + dry_run = true + } + lambda = { + artifact = { + zip = "unused-with-s3.zip" + s3 = { + bucket = "lambda-artifacts" + key = "control-plane/runners.zip" + object_version = "version-1" + } + } + runtime = "nodejs24.x" + architecture = "arm64" + memory_size = 384 + timeout = 45 + vpc = { + subnet_ids = [] + security_group_ids = [] + } + role = { + path = "/runner-config/" + permissions_boundary = null + principals = [{ + type = "AWS" + identifiers = ["arn:aws-us-gov:iam::123456789012:role/local-testing"] + }] + } + } + observability = { + logs = { + level = "debug" + retention_in_days = 30 + kms_key_id = null + class = "STANDARD" + } + tracing = { + mode = null + capture_http_requests = false + capture_error = false + } + } + tags = { + resources = { + Scope = "housekeeper" + } + lambda = { + Scope = "housekeeper" + Resource = "lambda" + } + log_group = { + Scope = "housekeeper" + Resource = "logs" + } + } + } +} + +run "configures_schedule_cleanup_and_outputs" { + command = plan + + assert { + condition = ( + length(data.aws_iam_policy_document.lambda_assume_role.statement[0].principals) == 2 && + contains(data.aws_iam_policy_document.lambda_assume_role.statement[0].principals[*].type, "AWS") + ) + error_message = "The housekeeper Lambda trust policy must include configured additional principals." + } + + assert { + condition = ( + aws_cloudwatch_event_rule.ssm_housekeeper.schedule_expression == "rate(6 hours)" && + aws_cloudwatch_event_rule.ssm_housekeeper.state == "DISABLED" + ) + error_message = "The housekeeper EventBridge rule must use the configured schedule and state." + } + + assert { + condition = ( + jsondecode(aws_lambda_function.ssm_housekeeper.environment[0].variables["SSM_CLEANUP_CONFIG"]).tokenPath == "/custom/runner/tokens" && + jsondecode(aws_lambda_function.ssm_housekeeper.environment[0].variables["SSM_CLEANUP_CONFIG"]).minimumDaysOld == 7 && + jsondecode(aws_lambda_function.ssm_housekeeper.environment[0].variables["SSM_CLEANUP_CONFIG"]).dryRun + ) + error_message = "The Lambda cleanup configuration must preserve the configured path override, age, and dry-run setting." + } + + assert { + condition = contains( + data.aws_iam_policy_document.ssm_housekeeper.statement[0].resources, + "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/custom/runner/tokens*", + ) + error_message = "The housekeeper IAM policy must authorize the same overridden Parameter Store path supplied to the Lambda." + } + + assert { + condition = toset(keys(output.housekeeper)) == toset(["lambda", "log_group", "role"]) + error_message = "The module must expose Lambda, log-group, and role resources through one nested housekeeper output." + } + + assert { + condition = ( + output.housekeeper.lambda.tags == tomap({ + Scope = "housekeeper" + Resource = "lambda" + }) && + output.housekeeper.log_group.tags == tomap({ + Scope = "housekeeper" + Resource = "logs" + }) && + output.housekeeper.role.tags == tomap({ + Scope = "housekeeper" + }) + ) + error_message = "Each nested output resource must retain its resolved component tags." + } + + assert { + condition = ( + length(aws_lambda_function.ssm_housekeeper.vpc_config) == 0 && + length(aws_iam_role_policy_attachment.ssm_housekeeper_vpc_execution_role) == 0 && + length(aws_lambda_function.ssm_housekeeper.tracing_config) == 0 && + length(aws_iam_role_policy.ssm_housekeeper_xray) == 0 + ) + error_message = "Empty VPC configuration and disabled tracing must not create their optional Lambda or IAM configuration." + } +} + +run "enables_vpc_and_xray_together" { + command = plan + + variables { + config = { + prefix = "ssm-housekeeper-vpc-test" + aws_partition = "aws-us-gov" + schedule = { + expression = "rate(1 day)" + state = "ENABLED" + } + cleanup = { + token_path = "/github-runner/tokens" + parameter_path_arn = "arn:aws-us-gov:ssm:us-gov-west-1:123456789012:parameter/github-runner/tokens*" + minimum_days_old = 1 + dry_run = false + } + lambda = { + artifact = { + zip = "unused-with-s3.zip" + s3 = { + bucket = "lambda-artifacts" + key = "control-plane/runners.zip" + } + } + runtime = "nodejs24.x" + architecture = "arm64" + memory_size = 512 + timeout = 60 + vpc = { + subnet_ids = ["subnet-12345678"] + security_group_ids = ["sg-12345678"] + } + role = { + path = "/runner-config/" + permissions_boundary = null + } + } + observability = { + logs = { + level = "info" + retention_in_days = 14 + kms_key_id = null + class = "STANDARD" + } + tracing = { + mode = "Active" + capture_http_requests = true + capture_error = true + } + } + tags = { + resources = {} + lambda = {} + log_group = {} + } + } + } + + assert { + condition = ( + length(aws_lambda_function.ssm_housekeeper.vpc_config) == 1 && + aws_lambda_function.ssm_housekeeper.vpc_config[0].subnet_ids == toset(["subnet-12345678"]) && + aws_lambda_function.ssm_housekeeper.vpc_config[0].security_group_ids == toset(["sg-12345678"]) && + length(aws_iam_role_policy_attachment.ssm_housekeeper_vpc_execution_role) == 1 && + aws_iam_role_policy_attachment.ssm_housekeeper_vpc_execution_role[0].policy_arn == "arn:aws-us-gov:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" + ) + error_message = "A complete VPC configuration must configure the Lambda and attach the partition-aware VPC execution policy." + } + + assert { + condition = ( + length(aws_lambda_function.ssm_housekeeper.tracing_config) == 1 && + aws_lambda_function.ssm_housekeeper.tracing_config[0].mode == "Active" && + length(aws_iam_role_policy.ssm_housekeeper_xray) == 1 && + aws_lambda_function.ssm_housekeeper.environment[0].variables["POWERTOOLS_TRACE_ENABLED"] == "true" && + aws_lambda_function.ssm_housekeeper.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS"] == "true" && + aws_lambda_function.ssm_housekeeper.environment[0].variables["POWERTOOLS_TRACER_CAPTURE_ERROR"] == "true" + ) + error_message = "Active tracing must configure Lambda tracing, X-Ray IAM permissions, and tracing-helper environment variables." + } + + assert { + condition = ( + data.aws_iam_policy_document.lambda_xray[0].statement[0].resources == toset(["*"]) + && alltrue([ + for action in data.aws_iam_policy_document.lambda_xray[0].statement[0].actions : + startswith(action, "xray:") + ]) + ) + error_message = "The housekeeper wildcard resource must be limited to X-Ray APIs, which do not support resource-level IAM permissions." + } +} diff --git a/modules/runner-config/ssm-housekeeper/variables.tf b/modules/runner-config/ssm-housekeeper/variables.tf new file mode 100644 index 0000000000..64848fc33c --- /dev/null +++ b/modules/runner-config/ssm-housekeeper/variables.tf @@ -0,0 +1,93 @@ +variable "config" { + description = <<-EOT + Provider-neutral SSM housekeeper configuration assembled by runner-config. + + - `prefix`: Prefix used to name the housekeeper resources. + - `aws_partition`: AWS partition used to construct IAM policy ARNs. + - `schedule.expression`: EventBridge schedule expression that invokes the housekeeper. + - `schedule.state`: State of the EventBridge rule. + - `cleanup.token_path`: Parameter Store token path supplied to the Lambda. + - `cleanup.parameter_path_arn`: IAM resource ARN matching `cleanup.token_path`. + - `cleanup.minimum_days_old`: Minimum parameter age before deletion. + - `cleanup.dry_run`: Reports eligible parameters without deleting them when true. + - `lambda.artifact.zip`: Resolved local control-plane archive. + - `lambda.artifact.s3.bucket`: Optional S3 bucket containing the Lambda archive. + - `lambda.artifact.s3.key`: Object key of the Lambda archive. + - `lambda.artifact.s3.object_version`: Optional object version of the Lambda archive. + - `lambda.runtime`: Runtime used by the housekeeper Lambda. + - `lambda.architecture`: Instruction-set architecture used by the housekeeper Lambda. + - `lambda.memory_size`: Memory allocated to the housekeeper Lambda. + - `lambda.timeout`: Housekeeper Lambda timeout in seconds. + - `lambda.vpc.subnet_ids`: Subnets used for Lambda VPC configuration. + - `lambda.vpc.security_group_ids`: Security groups used for Lambda VPC configuration. + - `lambda.role.path`: IAM path used for the housekeeper Lambda role. + - `lambda.role.permissions_boundary`: Optional permissions boundary for the housekeeper role. + - `lambda.role.principals`: Additional principals allowed to assume the housekeeper Lambda role. + - `observability.logs`: Logging level, retention, encryption, and log-class configuration. + - `observability.tracing`: Lambda X-Ray and tracing-helper configuration. + - `tags.resources`: Tags for the housekeeper role and EventBridge rule. + - `tags.lambda`: Tags for the housekeeper Lambda function. + - `tags.log_group`: Tags for the housekeeper log group. + EOT + + type = object({ + prefix = string + aws_partition = string + schedule = object({ + expression = string + state = string + }) + cleanup = object({ + token_path = string + parameter_path_arn = string + minimum_days_old = number + dry_run = bool + }) + lambda = object({ + artifact = object({ + zip = string + s3 = object({ + bucket = optional(string, null) + key = optional(string, null) + object_version = optional(string, null) + }) + }) + runtime = string + architecture = string + memory_size = number + timeout = number + vpc = object({ + subnet_ids = list(string) + security_group_ids = list(string) + }) + role = object({ + path = string + permissions_boundary = optional(string, null) + principals = optional(list(object({ + type = string + identifiers = list(string) + })), []) + }) + }) + observability = object({ + logs = object({ + level = string + retention_in_days = number + kms_key_id = optional(string, null) + class = string + }) + tracing = object({ + mode = optional(string, null) + capture_http_requests = bool + capture_error = bool + }) + }) + tags = object({ + resources = map(string) + lambda = map(string) + log_group = map(string) + }) + }) + + nullable = false +} diff --git a/modules/runner-config/ssm-housekeeper/versions.tf b/modules/runner-config/ssm-housekeeper/versions.tf new file mode 100644 index 0000000000..da9769f550 --- /dev/null +++ b/modules/runner-config/ssm-housekeeper/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.33" + } + } +} diff --git a/modules/runner-config/tests/README.md b/modules/runner-config/tests/README.md new file mode 100644 index 0000000000..fa55dfecd9 --- /dev/null +++ b/modules/runner-config/tests/README.md @@ -0,0 +1,72 @@ +# Terraform Tests + +This directory contains [Terraform test files](https://developer.hashicorp.com/terraform/language/tests) (`.tftest.hcl`) for the runners module. + +## Why `terraform test` instead of `terraform validate`? + +`terraform validate` only checks syntax and basic type correctness of the configuration. It **cannot** detect: + +- Conditional expressions with inconsistent result types (e.g., one branch returns an object with 1 attribute, the other returns 16) +- Runtime type mismatches that only surface during `plan` +- Invalid cross-module references that depend on resource attribute shapes + +`terraform test` with `mock_provider` runs a full plan without needing real cloud credentials, catching these classes of bugs in CI. + +## Requirements + +- Terraform >= 1.7 (for `mock_provider` and `mock_data` support) +- No AWS credentials required — all providers are mocked + +## Running locally + +```bash +cd modules/runners +terraform test -test-directory=tests +``` + +Expected output: + +``` +tests/pool.tftest.hcl... in progress + run "plan_with_pool_enabled"... pass +tests/pool.tftest.hcl... pass + +Success! 1 passed, 0 failed. +``` + +## Writing new tests + +1. Create a `.tftest.hcl` file in this directory +2. Use `mock_provider "aws" {}` to avoid needing credentials +3. Use `mock_data` blocks to provide realistic values for data sources that perform validation (e.g., `aws_iam_policy_document` validates JSON) +4. Set all required variables in a `variables {}` block +5. Use `run` blocks with `command = plan` and `assert` conditions + +### Example template + +```hcl +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" + } + } +} + +variables { + # ... required variables ... +} + +run "descriptive_test_name" { + command = plan + + assert { + condition = + error_message = "Explanation of what failed" + } +} +``` + +## CI integration + +These tests run automatically in the `terraform_test` job of `.github/workflows/terraform.yml` on every PR that touches `*.tf` or `*.hcl` files. diff --git a/modules/runner-config/tests/computed-iam-inputs.tftest.hcl b/modules/runner-config/tests/computed-iam-inputs.tftest.hcl new file mode 100644 index 0000000000..9fcea735ed --- /dev/null +++ b/modules/runner-config/tests/computed-iam-inputs.tftest.hcl @@ -0,0 +1,35 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } +} + +run "computed_external_values_keep_plan_shape_known" { + command = plan + + module { + source = "./tests/fixtures/computed-iam-inputs" + } + + # The packaged runner archive is added by the release build, so the computed + # IAM fixture isolates the two common housekeeper children in a source checkout. + override_module { + target = module.external_iam.module.ssm_housekeeper + } + + override_module { + target = module.generated_policy.module.ssm_housekeeper + } + + assert { + condition = output.external_role_runner_count == 0 + error_message = "Computed external AMI parameter, KMS key, role, and profile values must not make resource or policy-block counts unknown." + } + + assert { + condition = output.generated_policy_role_runner_count == 1 + error_message = "A computed managed-policy ARN under a caller-known map key must keep attachment planning stable." + } +} diff --git a/modules/runner-config/tests/fixtures/computed-iam-inputs/README.md b/modules/runner-config/tests/fixtures/computed-iam-inputs/README.md new file mode 100644 index 0000000000..3bbf0f9027 --- /dev/null +++ b/modules/runner-config/tests/fixtures/computed-iam-inputs/README.md @@ -0,0 +1,39 @@ + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3 | +| [random](#requirement\_random) | ~> 3.0 | + +## Providers + +| Name | Version | +|------|---------| +| [random](#provider\_random) | ~> 3.0 | + +## Modules + +| Name | Source | Version | +|------|--------|---------| +| [external\_iam](#module\_external\_iam) | ../../.. | n/a | +| [generated\_policy](#module\_generated\_policy) | ../../.. | n/a | + +## Resources + +| Name | Type | +|------|------| +| [random_id.external](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/id) | resource | +| [random_id.generated_policy](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/id) | resource | + +## Inputs + +No inputs. + +## Outputs + +| Name | Description | +|------|-------------| +| [external\_role\_runner\_count](#output\_external\_role\_runner\_count) | n/a | +| [generated\_policy\_role\_runner\_count](#output\_generated\_policy\_role\_runner\_count) | n/a | + diff --git a/modules/runner-config/tests/fixtures/computed-iam-inputs/computed-iam-inputs.tf b/modules/runner-config/tests/fixtures/computed-iam-inputs/computed-iam-inputs.tf new file mode 100644 index 0000000000..dc262b3d1d --- /dev/null +++ b/modules/runner-config/tests/fixtures/computed-iam-inputs/computed-iam-inputs.tf @@ -0,0 +1,210 @@ +# A .tftest.hcl variable block supplies plan-known values. This wrapper uses +# random_id results to exercise caller inputs that remain unknown during plan, +# which catches invalid count, for_each, and dynamic-block expressions in the +# IAM boundary. +resource "random_id" "external" { + byte_length = 4 +} + +resource "random_id" "generated_policy" { + byte_length = 4 +} + +module "external_iam" { + source = "../../.." + + aws_region = "eu-west-1" + prefix = "computed-external" + + compute_provider = { + ec2 = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + ami = { + id_ssm_parameter = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/external-ami-${random_id.external.hex}" + } + kms_key = { + arn = "arn:aws:kms:eu-west-1:123456789012:key/${random_id.external.hex}" + } + } + instance_profile = { + name = "external-runner-${random_id.external.hex}" + } + cloudwatch_agent = { + enabled = false + } + binaries_syncer = { + enabled = false + } + } + } + + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/external-runner-${random_id.external.hex}" + } + } + } + + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + } + + github = { + app_parameters = { + key_base64 = [{ + name = "/github-runner/key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" + }] + id = [{ + name = "/github-runner/app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" + }] + installation_id = [null] + } + } + + orchestration = { + webhook = { + runner = { + maximum_count = 3 + } + github = { + organization_runners = true + } + queue = { + build = { + arn = "arn:aws:sqs:eu-west-1:123456789012:computed-external" + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/computed-external" + } + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/build-queue-${random_id.external.hex}" + } + lambda = { + artifact = { + s3 = { + key = "runners.zip" + } + } + pool = { + runner_owner = "example" + config = [{ + schedule_expression = "cron(0 8 * * ? *)" + size = 1 + }] + } + } + job_retry = { + enabled = true + } + } + } + + ssm = { + kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/${random_id.external.hex}" + paths = { + root = "/github-runner/computed-external" + tokens = "tokens" + config = "config" + } + } +} + +module "generated_policy" { + source = "../../.." + + aws_region = "eu-west-1" + prefix = "computed-policy" + + compute_provider = { + ec2 = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + cloudwatch_agent = { + enabled = false + } + binaries_syncer = { + enabled = false + } + } + } + + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + managed_policy_arns = { + generated = "arn:aws:iam::123456789012:policy/generated-runner-${random_id.generated_policy.hex}" + } + } + } + + lambda = { + artifact = { + s3 = { + bucket = "lambda-artifacts" + } + } + } + + github = { + app_parameters = { + key_base64 = [{ + name = "/github-runner/key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" + }] + id = [{ + name = "/github-runner/app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" + }] + installation_id = [null] + } + } + + orchestration = { + webhook = { + runner = { + maximum_count = 3 + } + github = { + organization_runners = true + } + queue = { + build = { + arn = "arn:aws:sqs:eu-west-1:123456789012:computed-policy" + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/computed-policy" + } + } + lambda = { + artifact = { + s3 = { + key = "runners.zip" + } + } + } + } + } + + ssm = { + paths = { + root = "/github-runner/computed-policy" + tokens = "tokens" + config = "config" + } + } +} + +output "external_role_runner_count" { + value = module.external_iam.runner.role == null ? 0 : 1 +} + +output "generated_policy_role_runner_count" { + value = module.generated_policy.runner.role == null ? 0 : 1 +} diff --git a/modules/runner-config/tests/fixtures/computed-iam-inputs/versions.tf b/modules/runner-config/tests/fixtures/computed-iam-inputs/versions.tf new file mode 100644 index 0000000000..9fd85fad8f --- /dev/null +++ b/modules/runner-config/tests/fixtures/computed-iam-inputs/versions.tf @@ -0,0 +1,13 @@ +terraform { + required_version = ">= 1.3" + + required_providers { + aws = { + source = "hashicorp/aws" + } + random = { + source = "hashicorp/random" + version = "~> 3.0" + } + } +} diff --git a/modules/runner-config/tests/pool.tftest.hcl b/modules/runner-config/tests/pool.tftest.hcl new file mode 100644 index 0000000000..58667f3cfe --- /dev/null +++ b/modules/runner-config/tests/pool.tftest.hcl @@ -0,0 +1,601 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}" + } + } + + mock_resource "aws_iam_role" { + defaults = { + arn = "arn:aws:iam::123456789012:role/runner-test" + } + } + + mock_resource "aws_ssm_parameter" { + defaults = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/ami-id" + } + } +} + +# The runner archive is injected during packaging, so isolate the common +# housekeeper child in source-checkout tests where that build artifact is absent. +override_module { + target = module.ssm_housekeeper +} + +variables { + aws_region = "eu-west-1" + + compute_provider = { + ec2 = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + ami = { + filter = { state = ["available"] } + owners = ["amazon"] + id_ssm_parameter = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/external-ami-id" + } + kms_key = null + } + binaries_syncer = { + s3 = { + arn = "arn:aws:s3:::my-bucket" + id = "my-bucket" + key = "runners/linux/actions-runner.tar.gz" + } + } + ssm_enabled = true + } + } + + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + managed_policy_arns = { + readonly = "arn:aws:iam::aws:policy/ReadOnlyAccess" + } + additional_trust_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Sid = "AdditionalTrustedAccount" + Effect = "Allow" + Action = "sts:AssumeRole" + Principal = { AWS = "arn:aws:iam::210987654321:root" } + }] + }) + } + } + + lambda = { + artifact = { + s3 = { + bucket = "my-lambda-bucket" + } + } + } + + github = { + app_parameters = { + key_base64 = [{ name = "/github-runner/key-base64", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" }] + id = [{ name = "/github-runner/app-id", arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" }] + installation_id = [null] + } + } + + orchestration = { + webhook = { + runner = { + boot_time_in_minutes = 8 + ephemeral = true + jit_config_enabled = null + maximum_count = 9 + } + github = { + organization_runners = true + } + queue = { + build = { + arn = "arn:aws:sqs:eu-west-1:123456789012:build-queue" + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/build-queue" + } + } + lambda = { + artifact = { + s3 = { + key = "runners.zip" + } + } + pool = { + config = [{ + schedule_expression = "cron(0 8 * * ? *)" + size = 1 + }] + } + } + } + } + + ssm = { + paths = { + root = "/github-runner" + tokens = "tokens" + config = "config" + } + } + +} + +run "plan_with_pool_enabled" { + command = plan + + assert { + condition = module.webhook["webhook"].pool != null + error_message = "Pool module should be enabled when pool.config is non-empty" + } + + assert { + condition = ( + !contains(keys(var.runner), "maximum_count") + && !contains(keys(var.runner), "boot_time_in_minutes") + && !contains(keys(var.runner), "ephemeral") + && !contains(keys(var.runner), "jit_config_enabled") + && var.orchestration.webhook.runner.boot_time_in_minutes == 8 + && var.orchestration.webhook.runner.ephemeral + && var.orchestration.webhook.runner.jit_config_enabled == null + && var.orchestration.webhook.runner.maximum_count == 9 + && module.webhook["webhook"].scale_up.lambda.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "9" + && module.webhook["webhook"].scale_down.lambda.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "8" + && module.webhook["webhook"].pool.lambda.environment[0].variables["RUNNERS_MAXIMUM_COUNT"] == "9" + && module.webhook["webhook"].pool.lambda.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "8" + ) + error_message = "Runner capacity and boot time must be owned by orchestration.webhook.runner and routed to webhook controls, not retained in the common runner contract." + } + + assert { + condition = ( + aws_ssm_parameter.runner_agent_mode.value == "ephemeral" + && aws_ssm_parameter.jit_config_enabled.value == "true" + ) + error_message = "Runner-config must serialize the webhook provider's resolved lifecycle contract without duplicating its JIT fallback." + } + + assert { + condition = ( + module.webhook["webhook"].scale_up.lambda.s3_bucket == "my-lambda-bucket" + && module.webhook["webhook"].scale_up.lambda.s3_key == "runners.zip" + && local.ssm_housekeeper_artifact.s3.bucket == null + && endswith(local.ssm_housekeeper_artifact.zip, "/lambdas/functions/control-plane/runners.zip") + ) + error_message = "The webhook provider must combine its artifact key with the shared bucket while the common SSM housekeeper remains on the packaged archive." + } + + assert { + condition = toset(keys(output.provider)) == toset(["ec2"]) + error_message = "The runner configuration must expose resources only under the selected provider key." + } + + assert { + condition = contains(keys(output.provider.ec2), "launch_template") + error_message = "The runner configuration must expose EC2 resources only under provider.ec2." + } + + assert { + condition = length(aws_iam_role.runner) == 1 && output.runner.role != null + error_message = "The common runner configuration must create and expose the runner role." + } + + assert { + condition = ( + length(module.ec2_trust_policy) == 1 + && aws_iam_role.runner[0].assume_role_policy == module.ec2_trust_policy[0].assume_role_policy + ) + error_message = "The common runner role must use the selected EC2 trust-policy submodule output." + } + + assert { + condition = ( + output.pool != null + && toset(keys(output.pool)) == toset(["lambda", "log_group", "role"]) + ) + error_message = "An enabled pool must expose its Lambda, log group, and role through the nested pool output." + } + + assert { + condition = ( + toset(keys(output.orchestration)) == toset(["webhook"]) + && output.orchestration.webhook != null + && output.orchestration.webhook.scale_up != null + && output.orchestration.webhook.scale_down != null + && output.orchestration.webhook.pool != null + ) + error_message = "The canonical orchestration output must group the existing webhook control-plane resources while flat aliases remain available." + } + + assert { + condition = length(jsondecode(module.webhook["webhook"].scale_up.lambda.environment[0].variables["SSM_PARAMETER_STORE_TAGS"])) == 0 + error_message = "Runtime Parameter Store tags must remain empty when no module or SSM tags are configured; EC2 bootstrap tags must not leak into them." + } + + assert { + condition = !contains(keys(output.provider.ec2), "role_runner") + error_message = "The common runner role must not be duplicated in the EC2 resource output." + } + + assert { + condition = toset(keys(aws_iam_role_policy.runner_provider)) == toset([ + "ssm_parameters", + "describe_tags", + "create_tags", + "terminate_self", + "session_manager", + "distribution_bucket", + "cloudwatch", + ]) + error_message = "The common runner configuration must attach every enabled EC2 runner policy by its stable provider key." + } + + assert { + condition = aws_iam_role_policy_attachment.runner["user-readonly"].policy_arn == "arn:aws:iam::aws:policy/ReadOnlyAccess" + error_message = "The selected EC2 provider contract must return common managed runner policies for one attachment path." + } + + assert { + condition = ( + module.webhook["webhook"].scale_up.lambda.environment[0].variables["COMPUTE_PROVIDER_TYPE"] == "ec2" + && module.webhook["webhook"].scale_down.lambda.environment[0].variables["COMPUTE_PROVIDER_TYPE"] == "ec2" + ) + error_message = "Scaling Lambdas must receive the provider type from the selected provider." + } + + assert { + condition = module.webhook["webhook"].scale_up.lambda.environment[0].variables["INSTANCE_TYPES"] == "m5.large" + error_message = "Scale-up must merge the EC2 environment fragment." + } + + assert { + condition = module.webhook["webhook"].scale_down.lambda.environment[0].variables["RUNNER_BOOT_TIME_IN_MINUTES"] == "8" + error_message = "Scale-down must receive boot time from the webhook orchestration configuration." + } + + assert { + condition = ( + toset(keys(module.webhook["webhook"].scale_up)) == toset(["lambda", "log_group", "role"]) + && toset(keys(module.webhook["webhook"].scale_down)) == toset(["lambda", "log_group", "role"]) + ) + error_message = "The scale-runners child module must forward the nested scale-up and scale-down resource contracts." + } + +} + +run "housekeeper_uses_component_s3_artifact" { + command = plan + + variables { + ssm = { + paths = { + root = "/github-runner" + tokens = "tokens" + config = "config" + } + housekeeper = { + lambda = { + artifact = { + s3 = { + key = "housekeeper/runner-config.zip" + object_version = "housekeeper-version" + } + } + } + } + } + } + + assert { + condition = ( + local.ssm_housekeeper_artifact.zip == null + && local.ssm_housekeeper_artifact.s3.bucket == "my-lambda-bucket" + && local.ssm_housekeeper_artifact.s3.key == "housekeeper/runner-config.zip" + && local.ssm_housekeeper_artifact.s3.object_version == "housekeeper-version" + ) + error_message = "The SSM housekeeper must combine its component-owned S3 key and version with the common Lambda artifact bucket." + } +} + +run "housekeeper_uses_component_local_zip" { + command = plan + + variables { + ssm = { + paths = { + root = "/github-runner" + tokens = "tokens" + config = "config" + } + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + } + } + } + } + } + + assert { + condition = ( + local.ssm_housekeeper_artifact.zip == "README.md" + && local.ssm_housekeeper_artifact.s3.bucket == null + && local.ssm_housekeeper_artifact.s3.key == null + && local.ssm_housekeeper_artifact.s3.object_version == null + ) + error_message = "The SSM housekeeper must use its component-owned local zip without inheriting the common bucket or webhook artifact." + } +} + +run "rejects_conflicting_housekeeper_artifacts" { + command = plan + + variables { + ssm = { + paths = { + root = "/github-runner" + tokens = "tokens" + config = "config" + } + housekeeper = { + lambda = { + artifact = { + zip = "README.md" + s3 = { + key = "housekeeper/runner-config.zip" + } + } + } + } + } + } + + expect_failures = [var.ssm] +} + +run "rejects_housekeeper_s3_without_common_bucket" { + command = plan + + variables { + lambda = { + artifact = { + s3 = { + bucket = null + } + } + } + ssm = { + paths = { + root = "/github-runner" + tokens = "tokens" + config = "config" + } + housekeeper = { + lambda = { + artifact = { + s3 = { + key = "housekeeper/runner-config.zip" + } + } + } + } + } + } + + expect_failures = [data.aws_caller_identity.current] +} + +run "rejects_missing_orchestration_provider" { + command = plan + + variables { + orchestration = { + webhook = null + } + } + + expect_failures = [var.orchestration] +} + +run "external_runner_role_is_not_managed_by_common" { + command = plan + + variables { + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/external/runner-role" + } + } + } + } + + assert { + condition = length(aws_iam_role.runner) == 0 && length(aws_iam_role_policy.runner_provider) == 0 && length(aws_iam_role_policy_attachment.runner) == 0 + error_message = "An external runner role must remain unmanaged by the common runner configuration." + } + + assert { + condition = output.runner.role == null + error_message = "The nested runner role output must be null when an external role is selected." + } + + + assert { + condition = output.provider.ec2.launch_template.iam_instance_profile[0].name == "github-actions-runner-profile" + error_message = "EC2 must create an instance profile around an externally supplied runner role when no profile override is provided." + } +} + +run "external_runner_role_and_profile_remain_external" { + command = plan + + variables { + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/external/runner-role" + } + } + } + compute_provider = { + ec2 = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + instance_profile = { + name = "external-runner-profile" + } + binaries_syncer = { + enabled = false + } + } + } + } + + assert { + condition = length(aws_iam_role.runner) == 0 && length(aws_iam_role_policy.runner_provider) == 0 + error_message = "The common runner configuration must not manage an external role." + } + + assert { + condition = output.provider.ec2.launch_template.iam_instance_profile[0].name == "external-runner-profile" + error_message = "The EC2 launch template must use the external instance profile." + } +} + +run "empty_runner_iam_uses_common_role" { + command = plan + + variables { + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = {} + } + } + + assert { + condition = length(aws_iam_role.runner) == 1 + error_message = "An empty runner.iam object must use common role ownership." + } +} + +run "external_role_rejects_managed_policy_attachments" { + command = plan + + variables { + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/external/runner-role" + } + managed_policy_arns = { + readonly = "arn:aws:iam::aws:policy/ReadOnlyAccess" + } + } + } + } + + expect_failures = [var.runner] +} + +run "external_role_rejects_trust_policy_extension" { + command = plan + + variables { + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/external/runner-role" + } + additional_trust_policy_json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } + } + + expect_failures = [var.runner] +} + +run "rejects_invalid_trust_policy_extension" { + command = plan + + variables { + runner = { + labels = ["self-hosted", "linux", "x64"] + iam = { + additional_trust_policy_json = "{" + } + } + } + + expect_failures = [var.runner] +} + +run "rejects_empty_compute_provider" { + command = plan + + variables { + compute_provider = {} + } + + expect_failures = [var.compute_provider] +} + +run "job_retry_uses_common_runner_configuration_identity" { + command = plan + + variables { + runner = { + labels = ["self-hosted", "linux", "x64"] + name_prefix = "provider-neutral-" + } + orchestration = { + webhook = { + github = { + organization_runners = true + } + queue = { + build = { + arn = "arn:aws:sqs:eu-west-1:123456789012:build-queue" + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/build-queue" + } + } + lambda = { + artifact = { + s3 = { + key = "runners.zip" + } + } + } + job_retry = { + enabled = true + lambda = { + reserved_concurrent_executions = 2 + } + } + } + } + } + + assert { + condition = module.webhook["webhook"].job_retry.lambda.function.environment[0].variables["RUNNER_NAME_PREFIX"] == "provider-neutral-" + error_message = "Job retry must receive the common runner-configuration name prefix." + } + + assert { + condition = module.webhook["webhook"].job_retry.lambda.function.reserved_concurrent_executions == 2 + error_message = "Job retry must apply its configured Lambda reserved concurrency." + } +} diff --git a/modules/runner-config/tests/tags.tftest.hcl b/modules/runner-config/tests/tags.tftest.hcl new file mode 100644 index 0000000000..c620ba12ef --- /dev/null +++ b/modules/runner-config/tests/tags.tftest.hcl @@ -0,0 +1,320 @@ +mock_provider "aws" { + mock_data "aws_iam_policy_document" { + defaults = { + json = "{\"Version\":\"2012-10-17\",\"Statement\":[]}" + } + } + + mock_resource "aws_iam_role" { + defaults = { + arn = "arn:aws:iam::123456789012:role/runner-test" + } + } + + mock_resource "aws_ssm_parameter" { + defaults = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/config" + } + } +} + +# The runner archive is injected during packaging, so model the common +# housekeeper output while testing parent-level tag composition from source. +override_module { + target = module.ssm_housekeeper +} + +variables { + aws_region = "eu-west-1" + + tags = { + precedence = "module" + module = "yes" + } + + compute_provider = { + ec2 = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + ami = { + filter = { state = ["available"] } + owners = ["amazon"] + id_ssm_parameter = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/external-ami-id" + } + kms_key = null + } + binaries_syncer = { + s3 = { + arn = "arn:aws:s3:::my-bucket" + id = "my-bucket" + key = "runners/linux/actions-runner.tar.gz" + } + } + } + } + + runner = { + labels = ["self-hosted", "linux", "x64"] + tags = { + precedence = "runner" + runner = "yes" + } + } + + lambda = { + artifact = { + s3 = { + bucket = "my-lambda-bucket" + } + } + tags = { + precedence = "lambda" + lambda = "yes" + } + } + + github = { + app_parameters = { + key_base64 = [{ + name = "/github-runner/key-base64" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/key-base64" + }] + id = [{ + name = "/github-runner/app-id" + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/app-id" + }] + installation_id = [null] + } + } + + orchestration = { + webhook = { + github = { + organization_runners = true + } + queue = { + build = { + arn = "arn:aws:sqs:eu-west-1:123456789012:build-queue" + url = "https://sqs.eu-west-1.amazonaws.com/123456789012/build-queue" + } + tags = { + precedence = "queue" + queue = "yes" + } + } + lambda = { + artifact = { + s3 = { + key = "runners.zip" + } + } + scale = { + up = { + tags = { + precedence = "scale-up" + scale_up = "yes" + } + } + down = { + tags = { + precedence = "scale-down" + scale_down = "yes" + } + } + } + pool = { + config = [{ + schedule_expression = "cron(0 8 * * ? *)" + size = 1 + }] + tags = { + precedence = "pool" + pool = "yes" + } + } + } + job_retry = { + enabled = true + tags = { + precedence = "job-retry" + job_retry = "yes" + } + } + } + } + + ssm = { + paths = { + root = "/github-runner" + tokens = "tokens" + config = "config" + } + tags = { + precedence = "ssm" + ssm = "yes" + } + parameters = { + tags = { + precedence = "ssm-parameter" + parameter = "yes" + } + } + housekeeper = { + tags = { + precedence = "ssm-housekeeper" + housekeeper = "yes" + } + } + } + + observability = { + logs = { + level = "debug" + tags = { + precedence = "log" + log = "yes" + } + } + } +} + +run "layered_component_tags" { + command = plan + + assert { + condition = module.webhook["webhook"].scale_up.lambda.environment[0].variables["LOG_LEVEL"] == "DEBUG" + error_message = "The nested observability.logs.level value must configure the control-plane functions." + } + + assert { + condition = module.webhook["webhook"].scale_up.lambda.tags == tomap({ + precedence = "scale-up" + module = "yes" + lambda = "yes" + scale_up = "yes" + }) && module.webhook["webhook"].scale_up.log_group.tags == tomap({ + precedence = "scale-up" + module = "yes" + log = "yes" + scale_up = "yes" + }) && module.webhook["webhook"].scale_up.role.tags == tomap({ + precedence = "scale-up" + module = "yes" + scale_up = "yes" + }) + error_message = "Scale-up tags must layer module, shared resource, and component tags with the component taking precedence." + } + + assert { + condition = module.webhook["webhook"].scale_down.lambda.tags == tomap({ + precedence = "scale-down" + module = "yes" + lambda = "yes" + scale_down = "yes" + }) && module.webhook["webhook"].scale_down.log_group.tags == tomap({ + precedence = "scale-down" + module = "yes" + log = "yes" + scale_down = "yes" + }) && module.webhook["webhook"].scale_down.role.tags == tomap({ + precedence = "scale-down" + module = "yes" + scale_down = "yes" + }) + error_message = "Scale-down tags must layer module, shared resource, and component tags with the component taking precedence." + } + + assert { + condition = aws_iam_role.runner[0].tags == tomap({ + precedence = "runner" + module = "yes" + runner = "yes" + }) + error_message = "Runner tags must override module tags on the common runner role." + } + + assert { + condition = aws_ssm_parameter.runner_agent_mode.tags == tomap({ + precedence = "ssm-parameter" + module = "yes" + ssm = "yes" + parameter = "yes" + }) && tomap({ + for tag in jsondecode(module.webhook["webhook"].scale_up.lambda.environment[0].variables["SSM_PARAMETER_STORE_TAGS"]) : + tag.Key => tag.Value + }) == tomap({ + precedence = "ssm-parameter" + module = "yes" + ssm = "yes" + parameter = "yes" + }) + error_message = "Terraform-managed and runtime-created SSM parameters must use the same layered parameter tags." + } + + assert { + condition = local.ssm_housekeeper_lambda_tags == tomap({ + precedence = "ssm-housekeeper" + module = "yes" + lambda = "yes" + ssm = "yes" + housekeeper = "yes" + }) && local.ssm_housekeeper_log_tags == tomap({ + precedence = "ssm-housekeeper" + module = "yes" + log = "yes" + ssm = "yes" + housekeeper = "yes" + }) && local.ssm_housekeeper_tags == tomap({ + precedence = "ssm-housekeeper" + module = "yes" + ssm = "yes" + housekeeper = "yes" + }) + error_message = "SSM housekeeper tags must layer module, SSM, shared resource, and housekeeper tags." + } + + assert { + condition = module.webhook["webhook"].pool.lambda.tags == tomap({ + precedence = "pool" + module = "yes" + lambda = "yes" + pool = "yes" + }) && module.webhook["webhook"].pool.log_group.tags == tomap({ + precedence = "pool" + module = "yes" + log = "yes" + pool = "yes" + }) && module.webhook["webhook"].pool.role.tags == tomap({ + precedence = "pool" + module = "yes" + pool = "yes" + }) + error_message = "Pool tags must layer module, shared resource, and component tags with the component taking precedence." + } + + assert { + condition = module.webhook["webhook"].job_retry.lambda.function.tags == tomap({ + precedence = "job-retry" + module = "yes" + lambda = "yes" + job_retry = "yes" + }) && module.webhook["webhook"].job_retry.lambda.log_group.tags == tomap({ + precedence = "job-retry" + module = "yes" + log = "yes" + job_retry = "yes" + }) && module.webhook["webhook"].job_retry.lambda.role.tags == tomap({ + precedence = "job-retry" + module = "yes" + job_retry = "yes" + }) && module.webhook["webhook"].job_retry.queue.tags == tomap({ + precedence = "job-retry" + module = "yes" + queue = "yes" + job_retry = "yes" + }) + error_message = "Job-retry tags must layer module, shared resource, and component tags with the component taking precedence." + } +} diff --git a/modules/runner-config/variables.compute-provider.tf b/modules/runner-config/variables.compute-provider.tf new file mode 100644 index 0000000000..a8306cad14 --- /dev/null +++ b/modules/runner-config/variables.compute-provider.tf @@ -0,0 +1,255 @@ +# Typed compute-provider input boundary between the common control plane and compute implementations. +variable "compute_provider" { + description = <<-EOT + Typed compute-provider configuration. Provider-owned settings remain inside the selected compute-provider block. + + Exactly one compute-provider block must be non-null. The populated block selects the provider, and its presence must be known during planning. Values inside the selected block may remain unknown until apply. + + - `ec2`: EC2 compute-provider configuration. + - `ec2.ami`: Optional AMI discovery or external AMI-parameter configuration. Null uses the operating-system and architecture defaults. + - `ec2.ami.filter`: EC2 AMI filters combined with the provider's default AMI-name filter. + - `ec2.ami.owners`: AWS account IDs or aliases allowed to own the selected AMI. + - `ec2.ami.id_ssm_parameter`: Optional externally managed SSM parameter containing the AMI ID. Null creates a provider-managed AMI-ID parameter. The wrapper's presence is the plan-time ownership discriminator, so keep the object literal even when its ARN comes from another resource. + - `ec2.ami.id_ssm_parameter.arn`: ARN of the externally managed SSM parameter. The ARN may be unknown until apply. + - `ec2.ami.kms_key`: Optional KMS key required to launch encrypted AMIs or snapshots. The wrapper's presence is the plan-time policy discriminator. + - `ec2.ami.kms_key.arn`: ARN of the KMS key. The ARN may be unknown until apply. + - `ec2.vpc_id`: VPC in which runner networking resources are created. + - `ec2.subnet_ids`: Subnets from which scale-up may launch runner instances. + - `ec2.overrides`: Optional resource-name overrides. + - `ec2.overrides.name_runner`: Name tag used for runner compute resources. An empty value uses the generated provider name. + - `ec2.overrides.name_sg`: Name tag used for the managed runner security group. An empty value uses the generated provider name. + - `ec2.instance_profile`: Optional externally managed instance profile used by the launch template. + - `ec2.instance_profile.name`: Name of the externally managed instance profile. + - `ec2.instance_profile_path`: IAM path for the provider-managed instance profile. Null uses a path derived from the runner-configuration prefix. + - `ec2.binaries_syncer`: Runner-distribution synchronization configuration. + - `ec2.binaries_syncer.enabled`: Enables use of a synchronized runner distribution from S3. + - `ec2.binaries_syncer.s3`: S3 object containing the synchronized runner distribution. Required when synchronization is enabled. + - `ec2.binaries_syncer.s3.arn`: ARN of the runner-distribution bucket, used by IAM policies. + - `ec2.binaries_syncer.s3.id`: Bucket name used to construct the runner-distribution S3 URI. + - `ec2.binaries_syncer.s3.key`: Object key of the runner distribution. + - `ec2.block_device_mappings`: EBS mappings added to the runner launch template. + - `ec2.block_device_mappings[].delete_on_termination`: Deletes the volume when its runner instance terminates. + - `ec2.block_device_mappings[].device_name`: Device name exposed to the runner instance. + - `ec2.block_device_mappings[].encrypted`: Enables EBS encryption. + - `ec2.block_device_mappings[].iops`: Provisioned IOPS for volume types that support it. + - `ec2.block_device_mappings[].kms_key_id`: KMS key ID or ARN used to encrypt the volume. + - `ec2.block_device_mappings[].snapshot_id`: Snapshot used to initialize the volume. + - `ec2.block_device_mappings[].throughput`: Provisioned throughput for volume types that support it. + - `ec2.block_device_mappings[].volume_initialization_rate`: Fixed initialization rate in MiB/s for supported snapshot-backed volumes. + - `ec2.block_device_mappings[].volume_size`: Volume size in GiB. + - `ec2.block_device_mappings[].volume_type`: EBS volume type. + - `ec2.ebs_optimized`: Requests EBS-optimized runner instances. + - `ec2.instance_target_capacity_type`: Primary capacity type, either `spot` or `on-demand`. + - `ec2.instance_allocation_strategy`: EC2 Fleet allocation strategy used to select instance capacity. + - `ec2.instance_type_priorities`: Optional numeric priorities keyed by instance type. + - `ec2.instance_max_spot_price`: Optional maximum hourly Spot price. + - `ec2.instance_types`: EC2 instance types available to the scale-up and pool functions. + - `ec2.user_data`: Runner bootstrap user-data configuration. + - `ec2.user_data.enabled`: Enables launch-template user data. + - `ec2.user_data.template`: Optional path to a custom user-data template. + - `ec2.user_data.content`: Optional complete user-data content. When set, it is used instead of rendering a template. + - `ec2.user_data.pre_install`: Script content inserted before runner installation in the default template. + - `ec2.user_data.post_install`: Script content inserted after runner installation in the default template. + - `ec2.user_data.debug_logging_enabled`: Enables verbose user-data tracing, which can expose secrets in logs. + - `ec2.ssm_enabled`: Attaches runner permissions and policies required for AWS Systems Manager access. + - `ec2.create_service_linked_role_spot`: Allows scale-up to create the EC2 Spot service-linked role. + - `ec2.cloudwatch_agent`: CloudWatch agent configuration for runner instances. + - `ec2.cloudwatch_agent.enabled`: Installs and configures the CloudWatch agent through the default bootstrap flow. + - `ec2.cloudwatch_agent.config`: Optional complete CloudWatch agent configuration. Null renders the provider default from `log_files`. + - `ec2.managed_security_group_enabled`: Creates and attaches the provider-managed runner security group. + - `ec2.log_files`: Optional log files collected by the CloudWatch agent. Null uses the provider defaults. + - `ec2.log_files[].log_group_name`: CloudWatch log-group name, before optional prefixing. + - `ec2.log_files[].prefix_log_group`: Prefixes the log-group name with the runner configuration path when true. + - `ec2.log_files[].file_path`: File or glob read by the CloudWatch agent. + - `ec2.log_files[].log_stream_name`: CloudWatch log-stream name template. + - `ec2.log_files[].log_class`: CloudWatch log-group class for the collected file. + - `ec2.key_name`: Optional EC2 key-pair name added to the launch template. + - `ec2.additional_security_group_ids`: Existing security groups attached in addition to the managed security group. + - `ec2.detailed_monitoring_enabled`: Enables detailed EC2 monitoring for runner instances. + - `ec2.egress_rules`: Egress rules created on the managed runner security group. + - `ec2.egress_rules[].cidr_blocks`: IPv4 CIDR destinations. + - `ec2.egress_rules[].ipv6_cidr_blocks`: IPv6 CIDR destinations. + - `ec2.egress_rules[].prefix_list_ids`: AWS prefix-list destinations. + - `ec2.egress_rules[].from_port`: First destination port in the permitted range. + - `ec2.egress_rules[].protocol`: IP protocol name or number. Use `-1` for all protocols. + - `ec2.egress_rules[].security_groups`: Destination security-group IDs. + - `ec2.egress_rules[].self`: Allows traffic to the managed security group itself when true. + - `ec2.egress_rules[].to_port`: Last destination port in the permitted range. + - `ec2.egress_rules[].description`: Optional rule description. + - `ec2.tags`: Additional tags for runner instances, EBS volumes, network interfaces, and eligible Spot instance requests created from the launch template. They override module-level tags and the generated runner `Name`; the provider-managed `ghr:environment`, `ghr:ssm_config_path`, and `ghr:runner_name_prefix` bootstrap tags take final precedence. These tags do not apply to static provider resources such as the launch template, security group, IAM resources, SSM parameters, or log groups. + - `ec2.metadata_options`: Instance Metadata Service configuration in the launch template. + - `ec2.metadata_options.instance_metadata_tags`: Exposes instance tags through Instance Metadata Service when `enabled`. + - `ec2.metadata_options.http_endpoint`: Enables or disables the Instance Metadata Service endpoint. + - `ec2.metadata_options.http_tokens`: Controls whether IMDSv2 session tokens are optional or required. + - `ec2.metadata_options.http_put_response_hop_limit`: Network hop limit for Instance Metadata Service token responses. + - `ec2.credit_specification`: CPU credit mode for burstable instance types, either `standard` or `unlimited`. + - `ec2.cpu_options`: CPU topology and processor-feature configuration. + - `ec2.cpu_options.core_count`: Number of CPU cores exposed to the runner instance. + - `ec2.cpu_options.threads_per_core`: Number of hardware threads exposed per CPU core. + - `ec2.cpu_options.amd_sev_snp`: Enables or disables AMD SEV-SNP on supported instance types. + - `ec2.cpu_options.nested_virtualization`: Enables or disables nested virtualization on supported instance types. + - `ec2.placement`: EC2 placement configuration for runner instances. + - `ec2.placement.affinity`: Host affinity setting. + - `ec2.placement.availability_zone`: Availability Zone in which the instance is placed. + - `ec2.placement.group_id`: Placement-group ID. + - `ec2.placement.group_name`: Placement-group name. + - `ec2.placement.host_id`: Dedicated Host ID. + - `ec2.placement.host_resource_group_arn`: ARN of the host resource group used for placement. + - `ec2.placement.spread_domain`: Spread-domain placement value. + - `ec2.placement.tenancy`: Instance tenancy, such as `default`, `dedicated`, or `host`. + - `ec2.placement.partition_number`: Placement-group partition number. + - `ec2.license_specifications`: License Manager configurations added to the launch template. + - `ec2.license_specifications[].license_configuration_arn`: ARN of a License Manager license configuration. + - `ec2.associate_public_ipv4_address`: Associates a public IPv4 address with runner network interfaces. + - `ec2.enable_on_demand_failover_for_errors`: EC2 error codes that trigger an on-demand fallback after a Spot launch failure. + - `ec2.scale_errors`: EC2 error codes treated as retryable scale-up failures. + - `ec2.use_dedicated_host`: Enables the dedicated-host launch path, required for macOS runners. + EOT + + type = object({ + ec2 = optional(object({ + ami = optional(object({ + filter = optional(map(list(string)), { state = ["available"] }) + owners = optional(list(string), ["amazon"]) + id_ssm_parameter = optional(object({ + arn = string + }), null) + kms_key = optional(object({ + arn = string + }), null) + }), null) + vpc_id = string + subnet_ids = list(string) + overrides = optional(object({ + name_runner = optional(string, "") + name_sg = optional(string, "") + }), {}) + instance_profile = optional(object({ + name = string + }), null) + instance_profile_path = optional(string, null) + binaries_syncer = optional(object({ + enabled = optional(bool, true) + s3 = optional(object({ + arn = string + id = string + key = string + }), null) + }), {}) + block_device_mappings = optional(list(object({ + delete_on_termination = optional(bool, true) + device_name = optional(string, "/dev/xvda") + encrypted = optional(bool, true) + iops = optional(number) + kms_key_id = optional(string) + snapshot_id = optional(string) + throughput = optional(number) + volume_initialization_rate = optional(number) + volume_size = number + volume_type = optional(string, "gp3") + })), [{ volume_size = 30 }]) + ebs_optimized = optional(bool, false) + instance_target_capacity_type = optional(string, "spot") + instance_allocation_strategy = optional(string, "lowest-price") + instance_type_priorities = optional(map(number), null) + instance_max_spot_price = optional(string, null) + instance_types = list(string) + user_data = optional(object({ + enabled = optional(bool, true) + template = optional(string, null) + content = optional(string, null) + pre_install = optional(string, "") + post_install = optional(string, "") + debug_logging_enabled = optional(bool, false) + }), {}) + ssm_enabled = optional(bool, false) + create_service_linked_role_spot = optional(bool, false) + cloudwatch_agent = optional(object({ + enabled = optional(bool, true) + config = optional(string, null) + }), {}) + managed_security_group_enabled = optional(bool, true) + log_files = optional(list(object({ + log_group_name = string + prefix_log_group = bool + file_path = string + log_stream_name = string + log_class = optional(string, "STANDARD") + })), null) + key_name = optional(string, null) + additional_security_group_ids = optional(list(string), []) + detailed_monitoring_enabled = optional(bool, false) + egress_rules = optional(list(object({ + cidr_blocks = list(string) + ipv6_cidr_blocks = list(string) + prefix_list_ids = list(string) + from_port = number + protocol = string + security_groups = list(string) + self = bool + to_port = number + description = string + })), [{ + cidr_blocks = ["0.0.0.0/0"] + ipv6_cidr_blocks = ["::/0"] + prefix_list_ids = null + from_port = 0 + protocol = "-1" + security_groups = null + self = null + to_port = 0 + description = null + }]) + tags = optional(map(string), {}) + metadata_options = optional(object({ + instance_metadata_tags = optional(string, "enabled") + http_endpoint = optional(string, "enabled") + http_tokens = optional(string, "required") + http_put_response_hop_limit = optional(number, 1) + }), {}) + credit_specification = optional(string, null) + cpu_options = optional(object({ + core_count = optional(number) + threads_per_core = optional(number) + amd_sev_snp = optional(string) + nested_virtualization = optional(string) + }), null) + placement = optional(object({ + affinity = optional(string) + availability_zone = optional(string) + group_id = optional(string) + group_name = optional(string) + host_id = optional(string) + host_resource_group_arn = optional(string) + spread_domain = optional(string) + tenancy = optional(string) + partition_number = optional(number) + }), null) + license_specifications = optional(list(object({ + license_configuration_arn = string + })), []) + associate_public_ipv4_address = optional(bool, false) + enable_on_demand_failover_for_errors = optional(list(string), []) + scale_errors = optional(list(string), [ + "UnfulfillableCapacity", + "MaxSpotInstanceCountExceeded", + "TargetCapacityLimitExceededException", + "RequestLimitExceeded", + "ResourceLimitExceeded", + "MaxSpotInstanceCountExceeded", + "MaxSpotFleetRequestCountExceeded", + "InsufficientInstanceCapacity", + "InsufficientCapacityOnHost", + ]) + use_dedicated_host = optional(bool, false) + }), null) + }) + + validation { + condition = length([ + for provider_type, provider_config in var.compute_provider : provider_type + if provider_config != null + ]) == 1 + error_message = "Exactly one compute-provider block must be set. Supported compute-provider blocks: ec2." + } +} diff --git a/modules/runner-config/variables.orchestration-provider.tf b/modules/runner-config/variables.orchestration-provider.tf new file mode 100644 index 0000000000..d17d5e6b97 --- /dev/null +++ b/modules/runner-config/variables.orchestration-provider.tf @@ -0,0 +1,124 @@ +# Typed orchestration-provider input boundary between the common runner configuration and demand controllers. +variable "orchestration" { + description = <<-EOT + Runner demand-orchestration provider configuration. Exactly one provider block must be non-null. + + `webhook` is the currently supported provider. It owns the build queue reference, the runner-control + artifact shared by scale, pool, and job-retry, runner lifecycle and capacity limits, scale-up, scale-down, and scheduled pool + controls. Wrapper presence selects the provider and must therefore be known during planning. Future + providers can be added as sibling blocks without moving the webhook contract again. + EOT + type = object({ + webhook = optional(object({ + runner = optional(object({ + boot_time_in_minutes = optional(number, 5) + ephemeral = optional(bool, false) + jit_config_enabled = optional(bool, null) + maximum_count = optional(number, 3) + }), {}) + github = object({ + organization_runners = bool + }) + queue = object({ + build = object({ + arn = string + url = string + }) + kms_key_id = optional(string, null) + tags = optional(map(string), {}) + }) + lambda = optional(object({ + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + scale = optional(object({ + up = optional(object({ + memory_size = optional(number, 512) + timeout = optional(number, 60) + reserved_concurrent_executions = optional(number, 1) + job_queued_check_enabled = optional(bool, null) + event_source_mapping = optional(object({ + batch_size = optional(number, 10) + maximum_batching_window_in_seconds = optional(number, 0) + }), {}) + tags = optional(map(string), {}) + }), {}) + down = optional(object({ + memory_size = optional(number, 512) + timeout = optional(number, 60) + schedule_expression = optional(string, "cron(*/5 * * * ? *)") + minimum_running_time_in_minutes = optional(number, null) + tags = optional(map(string), {}) + idle_config = optional(list(object({ + cron = string + timeZone = string + idleCount = number + evictionStrategy = optional(string, "oldest_first") + })), []) + }), {}) + }), {}) + pool = optional(object({ + memory_size = optional(number, 512) + timeout = optional(number, 60) + reserved_concurrent_executions = optional(number, 1) + config = optional(list(object({ + schedule_expression = string + schedule_expression_timezone = optional(string) + size = number + })), []) + include_busy_runners = optional(bool, false) + runner_owner = optional(string, null) + tags = optional(map(string), {}) + }), {}) + }), {}) + job_retry = optional(object({ + enabled = optional(bool, false) + delay_in_seconds = optional(number, 300) + delay_backoff = optional(number, 2) + max_attempts = optional(number, 1) + tags = optional(map(string), {}) + lambda = optional(object({ + memory_size = optional(number, 256) + reserved_concurrent_executions = optional(number, 1) + timeout = optional(number, 30) + }), {}) + }), {}) + }), null) + }) + nullable = false + + validation { + condition = length([ + for provider_name, provider_config in var.orchestration : provider_name + if provider_config != null + ]) == 1 + error_message = "Exactly one orchestration provider must be configured. Supported providers: webhook." + } + + validation { + condition = var.orchestration.webhook == null ? true : ( + var.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size >= 1 && + var.orchestration.webhook.lambda.scale.up.event_source_mapping.batch_size <= 1000 && + var.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds >= 0 && + var.orchestration.webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds <= 300 + ) + error_message = "orchestration.webhook.lambda.scale.up.event_source_mapping batch size must be between 1 and 1000 and its batching window between 0 and 300 seconds." + } + + validation { + condition = var.orchestration.webhook == null ? true : !( + var.orchestration.webhook.lambda.artifact.zip != null && + var.orchestration.webhook.lambda.artifact.s3 != null + ) + error_message = "orchestration.webhook.lambda.artifact must select at most one of zip or s3." + } + + validation { + condition = var.orchestration.webhook == null ? true : (!var.orchestration.webhook.job_retry.enabled || var.orchestration.webhook.job_retry.delay_in_seconds <= 900) + error_message = "orchestration.webhook.job_retry.delay_in_seconds cannot exceed the SQS maximum of 900 seconds." + } +} diff --git a/modules/runner-config/variables.tf b/modules/runner-config/variables.tf new file mode 100644 index 0000000000..f2d2cba5ab --- /dev/null +++ b/modules/runner-config/variables.tf @@ -0,0 +1,297 @@ +variable "aws_region" { + description = "AWS region." + type = string +} + +variable "aws_partition" { + description = "AWS partition used to construct ARNs." + type = string + default = "aws" +} + +variable "prefix" { + description = "The prefix used for naming resources." + type = string + default = "github-actions" +} + +variable "tags" { + description = "Base tags added to taggable resources created by this runner configuration. Shared, component, and compute-provider tag maps override matching keys within their documented resource scopes." + type = map(string) + default = {} +} + +variable "runner" { + description = <<-EOT + Provider-neutral GitHub runner configuration. + + - `os`: Runner operating system. Supported values are `linux`, `osx`, and `windows`. + - `architecture`: Runner distribution architecture, such as `x64` or `arm64`. + - `disable_default_labels`: Prevents GitHub's default self-hosted, operating-system, and architecture labels from being registered. + - `labels`: Complete set of labels supplied to the control-plane functions. + - `group_name`: GitHub runner group used during registration. + - `name_prefix`: Prefix added to registered runner names. + - `run_as_root`: Runs the runner service as root when supported by the compute provider. + - `run_as`: Operating-system user used when `run_as_root` is false. + - `auto_update_disabled`: Disables the GitHub runner application's built-in updater. + - `tags`: Additional tags for common runner resources, currently the managed runner IAM role. These override module-level `tags` with the same key. + - `hooks.job_started`: Script content installed as the runner job-started hook. + - `hooks.job_completed`: Script content installed as the runner job-completed hook. + - `iam.role.arn`: ARN of an externally managed runner role. When set, this module does not create or modify that role. + - `iam.managed_policy_arns`: Named managed-policy ARNs attached to the module-managed runner role. + - `iam.additional_trust_policy_json`: Optional IAM policy document merged with the selected compute provider's default runner-role trust policy. + - `iam.path`: IAM path for the module-managed runner role. Defaults to a path derived from `prefix`. + - `iam.permissions_boundary`: Permissions-boundary ARN for the module-managed runner role. + EOT + type = object({ + os = optional(string, "linux") + architecture = optional(string, "x64") + disable_default_labels = optional(bool, false) + labels = list(string) + group_name = optional(string, "Default") + name_prefix = optional(string, "") + run_as_root = optional(bool, false) + run_as = optional(string, "ec2-user") + auto_update_disabled = optional(bool, false) + tags = optional(map(string), {}) + hooks = optional(object({ + job_started = optional(string, "") + job_completed = optional(string, "") + }), {}) + iam = optional(object({ + role = optional(object({ + arn = string + }), null) + managed_policy_arns = optional(map(string), {}) + additional_trust_policy_json = optional(string, null) + path = optional(string, null) + permissions_boundary = optional(string, null) + }), {}) + }) + + validation { + condition = contains(["linux", "osx", "windows"], var.runner.os) + error_message = "Valid values for runner.os are linux, osx, and windows." + } + + validation { + condition = length(var.runner.name_prefix) <= 45 + error_message = "runner.name_prefix must be at most 45 characters." + } + + validation { + condition = var.runner.iam.role == null ? true : trimspace(var.runner.iam.role.arn) != "" + error_message = "runner.iam.role.arn must be a non-empty ARN when set." + } + + validation { + condition = var.runner.iam.role == null || length(var.runner.iam.managed_policy_arns) == 0 + error_message = "runner.iam.managed_policy_arns cannot be set with an external runner.iam.role because external roles are not managed by this module." + } + + validation { + condition = var.runner.iam.additional_trust_policy_json == null ? true : can(jsondecode(var.runner.iam.additional_trust_policy_json)) + error_message = "runner.iam.additional_trust_policy_json must be valid JSON when set." + } + + validation { + condition = var.runner.iam.role == null || var.runner.iam.additional_trust_policy_json == null + error_message = "runner.iam.additional_trust_policy_json cannot be set with an external runner.iam.role because external role trust is not managed by this module." + } +} + +variable "github" { + description = <<-EOT + GitHub API and runner-registration configuration. + + - `app_parameters.key_base64`: Ordered Parameter Store references for GitHub App private keys. + - `app_parameters.id`: Ordered Parameter Store references for GitHub App IDs. + - `app_parameters.installation_id`: Ordered optional Parameter Store references for GitHub App installation IDs. + - `enterprise_server.url`: Optional GitHub Enterprise Server base URL. Null selects GitHub.com. + - `enterprise_server.ssl_verify`: Enables TLS certificate verification for GitHub Enterprise Server requests. + - `user_agent`: Optional User-Agent value added to GitHub API requests. + EOT + type = object({ + app_parameters = object({ + key_base64 = list(map(string)) + id = list(map(string)) + installation_id = list(object({ name = string, arn = string })) + }) + enterprise_server = optional(object({ + url = optional(string, null) + ssl_verify = optional(bool, true) + }), {}) + user_agent = optional(string, null) + }) +} + +variable "lambda" { + description = <<-EOT + Common Lambda substrate independent of the selected runner orchestration provider. + + - `artifact.s3.bucket`: Optional shared S3 bucket containing component-owned Lambda artifacts. An orchestration provider selects its own object key and version; the bucket alone selects no artifact. + - `runtime`: Runtime used by the control-plane Lambda functions. + - `architecture`: Instruction-set architecture used by the control-plane Lambda functions. Supported values are `arm64` and `x86_64`. + - `subnet_ids`: Subnets used for Lambda VPC configuration. + - `security_group_ids`: Security groups used for Lambda VPC configuration. + - `tags`: Shared tags applied to Lambda function resources only. These override module-level `tags`; component `tags` override this map when keys conflict. + - `principals`: Additional principals allowed to assume the control-plane Lambda roles. + - `role.path`: IAM path for module-managed Lambda execution roles. Defaults to a path derived from `prefix`. + - `role.permissions_boundary`: Permissions-boundary ARN applied to module-managed Lambda execution roles. + EOT + type = object({ + artifact = optional(object({ + s3 = optional(object({ + bucket = optional(string, null) + }), {}) + }), {}) + runtime = optional(string, "nodejs24.x") + architecture = optional(string, "arm64") + subnet_ids = optional(list(string), []) + security_group_ids = optional(list(string), []) + tags = optional(map(string), {}) + principals = optional(list(object({ + type = string + identifiers = list(string) + })), []) + role = optional(object({ + path = optional(string, null) + permissions_boundary = optional(string, null) + }), {}) + }) + default = {} + + validation { + condition = contains(["arm64", "x86_64"], var.lambda.architecture) + error_message = "lambda.architecture must be arm64 or x86_64." + } +} + +variable "ssm" { + description = <<-EOT + Parameter Store paths, encryption, tag scopes, and housekeeper configuration. + + - `paths.root`: Root Parameter Store path for this runner configuration. + - `paths.tokens`: Path segment under `paths.root` used for registration tokens and just-in-time configuration. + - `paths.config`: Path segment under `paths.root` used for persistent runner configuration. + - `kms_key_id`: Optional customer-managed KMS key ARN used by control-plane IAM policies to decrypt shared GitHub App parameters. The ARN may be unknown until apply; null omits the provider-owned KMS statements. It does not select encryption for runtime-created runner parameters. + - `tags`: Shared tags for SSM-related resources. These override module-level `tags` and are inherited by parameter and housekeeper resources. + - `parameters.tags`: Tags for Terraform-managed runner configuration parameters and temporary parameters created by the scale-up and pool Lambdas. These override module-level and `ssm.tags` values with the same key. + - `housekeeper.schedule_expression`: EventBridge schedule expression that invokes the SSM housekeeper. + - `housekeeper.state`: EventBridge rule state, such as `ENABLED` or `DISABLED`. + - `housekeeper.tags`: Tags for housekeeper resources, including the Lambda function, log group, EventBridge rule, and IAM role. These override module-level, `ssm.tags`, shared Lambda, and shared log tags when keys conflict. + - `housekeeper.lambda.artifact`: Component-owned SSM-housekeeper artifact selection. Set at most one of `zip` or `s3`; when neither is selected, the module uses its packaged runner control-plane archive. This selector does not inherit an orchestration-provider artifact. + - `housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive. + - `housekeeper.lambda.artifact.s3`: Optional object key and version in the shared `lambda.artifact.s3.bucket`. Selecting S3 requires that common bucket. + - `housekeeper.lambda.artifact.s3.key`: Object key of the SSM-housekeeper Lambda archive. + - `housekeeper.lambda.artifact.s3.object_version`: Optional object version of the SSM-housekeeper Lambda archive. + - `housekeeper.lambda.memory_size`: Memory allocated to the SSM housekeeper Lambda in MB. + - `housekeeper.lambda.timeout`: SSM housekeeper Lambda timeout in seconds. + - `housekeeper.config.tokenPath`: Parameter Store token path cleaned by the housekeeper. When omitted, the configured runner token path is used. + - `housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed. + - `housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true. + EOT + type = object({ + paths = object({ + root = string + tokens = string + config = string + }) + kms_key_id = optional(string, null) + tags = optional(map(string), {}) + parameters = optional(object({ + tags = optional(map(string), {}) + }), {}) + housekeeper = optional(object({ + schedule_expression = optional(string, "rate(1 day)") + state = optional(string, "ENABLED") + tags = optional(map(string), {}) + lambda = optional(object({ + artifact = optional(object({ + zip = optional(string, null) + s3 = optional(object({ + key = string + object_version = optional(string, null) + }), null) + }), {}) + memory_size = optional(number, 512) + timeout = optional(number, 60) + }), {}) + config = optional(object({ + tokenPath = optional(string) + minimumDaysOld = optional(number, 1) + dryRun = optional(bool, false) + }), {}) + }), {}) + }) + + validation { + condition = !( + var.ssm.housekeeper.lambda.artifact.zip != null && + var.ssm.housekeeper.lambda.artifact.s3 != null + ) + error_message = "ssm.housekeeper.lambda.artifact must select at most one of zip or s3." + } +} + +variable "observability" { + description = <<-EOT + Logging, tracing, and metrics configuration for control-plane and provider resources. + + - `logs.level`: Application log level supplied to the control-plane functions. + - `logs.retention_in_days`: CloudWatch Logs retention period. + - `logs.kms_key_id`: Optional KMS key ID or ARN used to encrypt CloudWatch log groups. + - `logs.class`: CloudWatch log-group class. Supported values are `STANDARD` and `INFREQUENT_ACCESS`. + - `logs.tags`: Shared tags for CloudWatch log groups. These override module-level `tags`; component `tags` override this map when keys conflict. + - `tracing.mode`: Optional Lambda active-tracing mode. Null disables X-Ray tracing configuration. + - `tracing.capture_http_requests`: Enables HTTP request capture in the tracing helper. + - `tracing.capture_error`: Enables error capture in the tracing helper. + - `metrics.enable`: Enables module-emitted metrics. + - `metrics.namespace`: CloudWatch namespace used for emitted metrics. + - `metrics.metric.enable_github_app_rate_limit`: Emits GitHub App rate-limit metrics. + - `metrics.metric.enable_job_retry`: Emits job-retry metrics. + - `metrics.metric.enable_spot_termination_warning`: Emits spot-termination warning metrics where supported. + EOT + type = object({ + logs = optional(object({ + level = optional(string, "info") + retention_in_days = optional(number, 180) + kms_key_id = optional(string, null) + class = optional(string, "STANDARD") + tags = optional(map(string), {}) + }), {}) + tracing = optional(object({ + mode = optional(string, null) + capture_http_requests = optional(bool, false) + capture_error = optional(bool, false) + }), {}) + metrics = optional(object({ + enable = optional(bool, false) + namespace = optional(string, "GitHub Runners") + metric = optional(object({ + enable_github_app_rate_limit = optional(bool, true) + enable_job_retry = optional(bool, true) + enable_spot_termination_warning = optional(bool, true) + }), {}) + }), {}) + }) + default = {} + + validation { + condition = contains(["STANDARD", "INFREQUENT_ACCESS"], var.observability.logs.class) + error_message = "observability.logs.class must be STANDARD or INFREQUENT_ACCESS." + } + + validation { + condition = contains([ + "silly", + "trace", + "debug", + "info", + "warn", + "error", + "fatal", + ], var.observability.logs.level) + error_message = "observability.logs.level must be one of silly, trace, debug, info, warn, error, or fatal." + } +} diff --git a/modules/runner-config/versions.tf b/modules/runner-config/versions.tf new file mode 100644 index 0000000000..da9769f550 --- /dev/null +++ b/modules/runner-config/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.33" + } + } +} diff --git a/modules/webhook/README.md b/modules/webhook/README.md index 70121458a7..458ff5a7aa 100644 --- a/modules/webhook/README.md +++ b/modules/webhook/README.md @@ -89,7 +89,7 @@ yarn run dist | [repository\_white\_list](#input\_repository\_white\_list) | List of github repository full names (owner/repo\_name) that will be allowed to use the github app. Leave empty for no filtering. | `list(string)` | `[]` | no | | [role\_path](#input\_role\_path) | The path that will be added to the role; if not set, the environment name will be used. | `string` | `null` | no | | [role\_permissions\_boundary](#input\_role\_permissions\_boundary) | Permissions boundary that will be added to the created role for the lambda. | `string` | `null` | no | -| [runner\_matcher\_config](#input\_runner\_matcher\_config) | SQS queue to publish accepted build events based on the runner type. `computeProvider` defaults to `ec2`; EC2 is the only provider currently implemented. When exact match is disabled the webhook accepts the event if one of the workflow job labels is part of the matcher. The priority defines the order the matchers are applied. Optional `matcherConfig.enableDynamicLabels` and `matcherConfig.awsDynamicLabelsPolicy` are evaluated by the dispatcher to gate provider dynamic labels per runner. The policy supports `blocked_keys = []` and `restricted_keys = { = { allowed = [globs], denied = [globs], max = number|string } }`; keys use the provider dynamic label suffix form, for example `instance-type` for `ghr-ec2-instance-type`. |
map(object({
arn = string
id = string
computeProvider = optional(string, "ec2")
matcherConfig = object({
labelMatchers = list(list(string))
exactMatch = bool
bidirectionalLabelMatch = optional(bool, false)
priority = optional(number, 999)
enableDynamicLabels = optional(bool, false)
awsDynamicLabelsPolicy = optional(any, null)
})
}))
| n/a | yes | +| [runner\_matcher\_config](#input\_runner\_matcher\_config) | SQS queue to publish accepted build events based on the runner type. `computeProvider` defaults to `ec2`; EC2 is the only provider currently implemented. When exact match is disabled the webhook accepts the event if one of the workflow job labels is part of the matcher. The priority defines the order the matchers are applied. Optional `matcherConfig.enableDynamicLabels` and `matcherConfig.awsDynamicLabelsPolicy` are evaluated by the dispatcher to gate provider dynamic labels per runner. The policy supports `blocked_keys = []` and `restricted_keys = { = { allowed = [globs], denied = [globs], max = number|string } }`; keys use the provider dynamic label suffix form, for example `instance-type` for `ghr-ec2-instance-type`. |
map(object({
arn = string
id = string
computeProvider = optional(string, "ec2")
matcherConfig = object({
labelMatchers = list(list(string))
exactMatch = bool
bidirectionalLabelMatch = optional(bool, false)
priority = optional(number, 999)
enableDynamicLabels = optional(bool, false)
awsDynamicLabelsPolicy = optional(object({
blocked_keys = optional(list(string), [])
restricted_keys = optional(map(object({
allowed = optional(list(string), [])
denied = optional(list(string), [])
max = optional(string, null)
})), {})
}), null)
})
}))
| n/a | yes | | [ssm\_paths](#input\_ssm\_paths) | The root path used in SSM to store configuration and secrets. |
object({
root = string
webhook = string
})
| n/a | yes | | [tags](#input\_tags) | Map of tags that will be added to created resources. By default resources will be tagged with name and environment. | `map(string)` | `{}` | no | | [tracing\_config](#input\_tracing\_config) | Configuration for lambda tracing. |
object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
})
| `{}` | no | diff --git a/modules/webhook/variables.tf b/modules/webhook/variables.tf index 2e5fafd205..a2fae87e4a 100644 --- a/modules/webhook/variables.tf +++ b/modules/webhook/variables.tf @@ -34,20 +34,20 @@ variable "runner_matcher_config" { bidirectionalLabelMatch = optional(bool, false) priority = optional(number, 999) enableDynamicLabels = optional(bool, false) - awsDynamicLabelsPolicy = optional(any, null) + awsDynamicLabelsPolicy = optional(object({ + blocked_keys = optional(list(string), []) + restricted_keys = optional(map(object({ + allowed = optional(list(string), []) + denied = optional(list(string), []) + max = optional(string, null) + })), {}) + }), null) }) })) validation { condition = try(var.runner_matcher_config.matcherConfig.priority, 999) >= 0 && try(var.runner_matcher_config.matcherConfig.priority, 999) < 1000 error_message = "The priority of the matcher must be between 0 and 999." } - validation { - condition = alltrue([ - for config in values(var.runner_matcher_config) : - lower(trimspace(config.computeProvider)) == "ec2" - ]) - error_message = "computeProvider must be ec2." - } } variable "lambda_zip" {