Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ Join our discord community via [this invite link](https://discord.gg/bxgXW8jJGh)
| <a name="input_runner_binaries_syncer_lambda_timeout"></a> [runner\_binaries\_syncer\_lambda\_timeout](#input\_runner\_binaries\_syncer\_lambda\_timeout) | Time out of the binaries sync lambda in seconds. | `number` | `300` | no |
| <a name="input_runner_binaries_syncer_lambda_zip"></a> [runner\_binaries\_syncer\_lambda\_zip](#input\_runner\_binaries\_syncer\_lambda\_zip) | File location of the binaries sync lambda zip file. | `string` | `null` | no |
| <a name="input_runner_boot_time_in_minutes"></a> [runner\_boot\_time\_in\_minutes](#input\_runner\_boot\_time\_in\_minutes) | The minimum time for an EC2 runner to boot and register as a runner. | `number` | `5` | no |
| <a name="input_runner_config_ssm_parameter_tier"></a> [runner\_config\_ssm\_parameter\_tier](#input\_runner\_config\_ssm\_parameter\_tier) | Optional SSM parameter tier (`Standard` or `Advanced`) used for the parameters holding the runner registration token / JIT config written by the scale-up and pool Lambdas. When `null`, the tier is selected per parameter: `Advanced` when the value is 4000 bytes or larger or `ssm_ttl_seconds.tokens` is set, otherwise `Standard`. Forcing `Standard` makes the write fail if the value exceeds the Standard tier size limit (4 KB), and cannot be combined with `ssm_ttl_seconds.tokens` since expiration policies require the Advanced tier. | `string` | `null` | no |
| <a name="input_runner_cpu_options"></a> [runner\_cpu\_options](#input\_runner\_cpu\_options) | The CPU options for the instance. See https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/launch_template#cpu-options for details. Note that not all instance types support CPU options, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html#instance-cpu-options | <pre>object({<br/> core_count = optional(number)<br/> threads_per_core = optional(number)<br/> amd_sev_snp = optional(string)<br/> nested_virtualization = optional(string)<br/> })</pre> | `null` | no |
| <a name="input_runner_credit_specification"></a> [runner\_credit\_specification](#input\_runner\_credit\_specification) | The credit option for CPU usage of a T instance. Can be unset, "standard" or "unlimited". | `string` | `null` | no |
| <a name="input_runner_disable_default_labels"></a> [runner\_disable\_default\_labels](#input\_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. | `bool` | `false` | no |
Expand Down
7 changes: 7 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ When upgrading the housekeeper Lambda, also apply the Terraform IAM changes gran
Furthermore, to accommodate larger JIT configurations or other stored values, the module implements automatic tier selection for SSM parameters:

- **Parameter Tiering**: If the size of a parameter's value exceeds 4KB (specifically, 4000 bytes), the module will automatically use the 'Advanced' tier for that SSM parameter. Values smaller than this threshold will use the 'Standard' tier.
- **Overriding the tier**: Set `runner_config_ssm_parameter_tier` to `Standard` or `Advanced` to skip the size-based selection and always write the runner registration token / JIT config parameters (the parameters written by the scale-up and pool Lambdas under the token path) with that tier. Leave it unset (`null`, the default) to keep the automatic selection. Other parameters are not affected. For example, to keep all runner config parameters on the Standard tier:

```hcl
runner_config_ssm_parameter_tier = "Standard"
```

Forcing `Standard` makes writing a parameter fail when its value exceeds the Standard tier limit of 4 KB, which can happen for large JIT configurations, so only use it if your configurations stay below that limit. It also cannot be combined with `ssm_ttl_seconds.tokens`, because SSM expiration policies require the Advanced tier. For the experimental multi-runner configuration use `runner_config.runner_config_ssm_parameter_tier` (stable shape) or `storage_provider.aws.ssm.runner_config_tier` (v2 shape) per runner configuration.
- **Cost Implications**: While the 'Standard' tier is generally free for a certain number of parameters and operations, the 'Advanced' tier incurs costs. These costs are typically pro-rated per hour for each parameter stored using the Advanced tier. For detailed and up-to-date pricing, please refer to the [AWS Systems Manager Pricing page](https://aws.amazon.com/systems-manager/pricing/#Parameter_Store).
- **Housekeeping Recommendation**: The last sentence of the "AWS SSM Parameters" section already mentions that "data not deleted after a day will be deleted by a SSM housekeeper lambda." It is crucial to ensure this or a similar housekeeping mechanism is active and correctly configured, especially considering the potential costs associated with 'Advanced' tier parameters. This utility should identify and delete any orphaned parameters to help manage costs and maintain a clean SSM environment.

Expand Down
42 changes: 42 additions & 0 deletions lambdas/libs/aws-ssm-util/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,48 @@ describe('Test getParameter and putParameter', () => {
});
});

it.each([
['a', 'Advanced'],
['a'.repeat(SSM_ADVANCED_TIER_THRESHOLD + 1), 'Standard'],
] as const)('Uses the requested tier %# instead of the size-based selection', async (data, tier) => {
// Arrange
mockSSMClient.on(PutParameterCommand).resolves({ $metadata: { httpStatusCode: 200 } });

// Act
await putParameter('testParam', data, true, { tier });

// Assert
expect(mockSSMClient).toHaveReceivedCommandWith(PutParameterCommand, {
Name: 'testParam',
Value: data,
Type: 'SecureString',
Tier: tier,
});
});

it('Keeps the Advanced tier when a TTL is given together with an explicit Advanced tier', async () => {
// Arrange
mockSSMClient.on(PutParameterCommand).resolves({ $metadata: { httpStatusCode: 200 } });

// Act
await putParameter('testParam', 'test', true, { ttlSeconds: 60, tier: 'Advanced' });

// Assert
expect(mockSSMClient).toHaveReceivedCommandWith(PutParameterCommand, { Name: 'testParam', Tier: 'Advanced' });
});

it('Rejects a TTL combined with an explicit Standard tier without calling SSM', async () => {
// Arrange
mockSSMClient.reset();
mockSSMClient.on(PutParameterCommand).resolves({ $metadata: { httpStatusCode: 200 } });

// Act & Assert
await expect(putParameter('testParam', 'test', true, { ttlSeconds: 60, tier: 'Standard' })).rejects.toThrow(
'A parameter TTL requires the Advanced SSM parameter tier',
);
expect(mockSSMClient).not.toHaveReceivedCommand(PutParameterCommand);
});

it('Puts parameters without an expiration policy when no TTL is given', async () => {
// Arrange
mockSSMClient.on(PutParameterCommand).resolves({ $metadata: { httpStatusCode: 200 } });
Expand Down
11 changes: 9 additions & 2 deletions lambdas/libs/aws-ssm-util/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,20 @@ export async function getParameters(parameter_names: string[]): Promise<Map<stri

export const SSM_ADVANCED_TIER_THRESHOLD = 4000;

export type SsmParameterTier = 'Standard' | 'Advanced';

export async function putParameter(
parameter_name: string,
parameter_value: string,
secure: boolean,
options: { tags?: Tag[]; ttlSeconds?: number } = {},
options: { tags?: Tag[]; ttlSeconds?: number; tier?: SsmParameterTier } = {},
): Promise<void> {
const client = ssmClient();

if (options.tier === 'Standard' && options.ttlSeconds !== undefined) {
throw new Error('A parameter TTL requires the Advanced SSM parameter tier, but the Standard tier was requested');
}

// Determine tier based on parameter_value size
const valueSizeBytes = Buffer.byteLength(parameter_value, 'utf8');

Expand All @@ -132,13 +138,14 @@ export async function putParameter(
])
: undefined;

// An explicitly requested tier takes precedence over the TTL / size-based selection.
await client.send(
new PutParameterCommand({
Name: parameter_name,
Value: parameter_value,
Type: secure ? 'SecureString' : 'String',
Tags: options.tags,
Tier: expiration || valueSizeBytes >= SSM_ADVANCED_TIER_THRESHOLD ? 'Advanced' : 'Standard',
Tier: options.tier ?? (expiration || valueSizeBytes >= SSM_ADVANCED_TIER_THRESHOLD ? 'Advanced' : 'Standard'),
Policies: expiration,
}),
);
Expand Down
1 change: 1 addition & 0 deletions lambdas/libs/storage-providers/aws/ssm/environment.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ declare global {
SSM_CONFIG_PATH?: string;
SSM_TOKEN_PATH?: string;
SSM_TOKEN_TTL_SECONDS?: string;
SSM_RUNNER_CONFIG_TIER?: string;
PARAMETER_GITHUB_APP_ID_NAME?: string;
PARAMETER_GITHUB_APP_KEY_BASE64_NAME?: string;
PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ describe('aws_ssm runner config store', () => {
process.env = { ...cleanEnv };
delete process.env.SSM_PARAMETER_STORE_TAGS;
delete process.env.SSM_TOKEN_TTL_SECONDS;
delete process.env.SSM_RUNNER_CONFIG_TIER;
process.env.SSM_TOKEN_PATH = '/runner/tokens';
});

Expand Down Expand Up @@ -73,6 +74,28 @@ describe('aws_ssm runner config store', () => {
});
});

it.each(['Standard', 'Advanced'] as const)('passes the configured %s tier to SSM', async (tier) => {
process.env.SSM_RUNNER_CONFIG_TIER = tier;
await createAwsSsmRunnerConfigStore().create({ runnerId: 'runner-1', value: 'jit-config' });
expect(putParameterMock).toHaveBeenCalledWith('/runner/tokens/runner-1', 'jit-config', true, {
tags: [],
tier,
});
});

it('leaves the tier to the size-based selection when none is configured', async () => {
await createAwsSsmRunnerConfigStore().create({ runnerId: 'runner-1', value: 'jit-config' });
expect(putParameterMock.mock.calls[0][3]).not.toHaveProperty('tier', expect.anything());
});

it('rejects an invalid runner config tier before writing', () => {
process.env.SSM_RUNNER_CONFIG_TIER = 'Premium';
expect(() => createAwsSsmRunnerConfigStore()).toThrow(
'SSM_RUNNER_CONFIG_TIER must be either "Standard" or "Advanced"',
);
expect(putParameterMock).not.toHaveBeenCalled();
});

it('rejects an invalid token TTL before writing', () => {
process.env.SSM_TOKEN_TTL_SECONDS = 'not-a-number';
expect(() => createAwsSsmRunnerConfigStore()).toThrow('SSM_TOKEN_TTL_SECONDS must be a positive number');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { putParameter } from '@aws-github-runner/aws-ssm-util';
import { putParameter, type SsmParameterTier } from '@aws-github-runner/aws-ssm-util';

import type { RunnerConfigMetadata, RunnerConfigRecord, RunnerConfigStore } from '../../core';
import type {} from './environment';
import { createAwsSsmStorageLogger, getErrorNames } from './logger';
import { loadSsmParameterStoreTagsFromEnvironment } from './parameter-store-tags';

import { parseSsmRunnerConfigTier } from './runner-config-tier';
import { parseSsmTokenTtlSeconds } from './token-ttl';

const logger = createAwsSsmStorageLogger('runner-config-store');
Expand All @@ -21,6 +22,7 @@ export function resolveMaxWritesPerSecond(rawValue: string | undefined): number
export interface AwsSsmRunnerConfigStoreConfig {
tokenPath: string;
tokenTtlSeconds?: number;
parameterTier?: SsmParameterTier;
parameterStoreTags: ReadonlyArray<Readonly<{ Key: string; Value: string }>>;
maxWritesPerSecond?: number;
}
Expand All @@ -42,6 +44,7 @@ export function createAwsSsmRunnerConfigStore(config?: AwsSsmRunnerConfigStoreCo
return new AwsSsmRunnerConfigStore({
tokenPath,
tokenTtlSeconds: parseSsmTokenTtlSeconds(process.env.SSM_TOKEN_TTL_SECONDS),
parameterTier: parseSsmRunnerConfigTier(process.env.SSM_RUNNER_CONFIG_TIER),
parameterStoreTags: loadSsmParameterStoreTagsFromEnvironment(),
maxWritesPerSecond: resolveMaxWritesPerSecond(process.env.SSM_PARAMETER_STORE_MAX_WRITES_PER_SECOND),
});
Expand All @@ -64,6 +67,7 @@ class AwsSsmRunnerConfigStore implements RunnerConfigStore {
try {
await putParameter(parameterName, record.value, true, {
ttlSeconds: this.config.tokenTtlSeconds,
tier: this.config.parameterTier,
tags: [
...(options.metadata ?? []).map(({ key, value }) => ({ Key: key, Value: value })),
...this.config.parameterStoreTags,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest';

import { parseSsmRunnerConfigTier } from './runner-config-tier';

describe('parseSsmRunnerConfigTier', () => {
it.each([
[undefined, undefined],
['', undefined],
[' ', undefined],
['Standard', 'Standard'],
['Advanced', 'Advanced'],
])('parses %j to %j', (input, expected) => {
expect(parseSsmRunnerConfigTier(input)).toBe(expected);
});

it.each([['standard'], ['Intelligent-Tiering'], ['premium']])('throws on invalid value %j', (input) => {
expect(() => parseSsmRunnerConfigTier(input)).toThrow(
'SSM_RUNNER_CONFIG_TIER must be either "Standard" or "Advanced"',
);
});
});
11 changes: 11 additions & 0 deletions lambdas/libs/storage-providers/aws/ssm/runner-config-tier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { SsmParameterTier } from '@aws-github-runner/aws-ssm-util';

export function parseSsmRunnerConfigTier(tier: string | undefined): SsmParameterTier | undefined {
if (!tier || tier.trim() === '') {
return undefined;
}
if (tier !== 'Standard' && tier !== 'Advanced') {
throw new Error(`SSM_RUNNER_CONFIG_TIER must be either "Standard" or "Advanced", got "${tier}"`);
}
return tier;
}
13 changes: 12 additions & 1 deletion lambdas/libs/storage-providers/storage-providers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ describe('createStorageProviders', () => {
RUNNER_CONFIG_STORAGE_PROVIDER: 'AWS_SSM',
SSM_TOKEN_PATH: '/runners/tokens',
SSM_TOKEN_TTL_SECONDS: '3600',
SSM_RUNNER_CONFIG_TIER: 'Advanced',
SSM_CONFIG_PATH: '/runners/config',
SSM_PARAMETER_STORE_TAGS: JSON.stringify([{ Key: 'Environment', Value: 'test' }]),
PARAMETER_GITHUB_APP_ID_NAME: 'app-id',
Expand All @@ -35,7 +36,9 @@ describe('createStorageProviders', () => {

const storage = createStorageProviders(environment);

expect(createAwsSsmRunnerConfigStore).toHaveBeenCalledWith(expect.objectContaining({ tokenTtlSeconds: 3600 }));
expect(createAwsSsmRunnerConfigStore).toHaveBeenCalledWith(
expect.objectContaining({ tokenTtlSeconds: 3600, parameterTier: 'Advanced' }),
);
expect(storage).toEqual({
runnerConfig: expect.any(Object),
runnerGroupCache: expect.any(Object),
Expand Down Expand Up @@ -66,4 +69,12 @@ describe('createStorageProviders', () => {
).toThrow('SSM_TOKEN_TTL_SECONDS must be a positive number');
expect(createAwsSsmRunnerConfigStore).not.toHaveBeenCalled();
});

it('rejects an invalid runner config tier before creating a storage provider', () => {
vi.clearAllMocks();
expect(() =>
createStorageProviders({ SSM_TOKEN_PATH: '/runners/tokens', SSM_RUNNER_CONFIG_TIER: 'Premium' }),
).toThrow('SSM_RUNNER_CONFIG_TIER must be either "Standard" or "Advanced"');
expect(createAwsSsmRunnerConfigStore).not.toHaveBeenCalled();
});
});
3 changes: 3 additions & 0 deletions lambdas/libs/storage-providers/storage-providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { loadRunnerConfigConsumerConfigFromEnvironment } from './runner-config-c
import { loadSsmParameterStoreTagsFromEnvironment } from './aws/ssm/parameter-store-tags';
import { resolveRunnerConfigStorageProvider, runnerConfigStorageProvider } from './provider';

import { parseSsmRunnerConfigTier } from './aws/ssm/runner-config-tier';
import { parseSsmTokenTtlSeconds } from './aws/ssm/token-ttl';

type Environment = Readonly<Record<string, string | undefined>>;
Expand All @@ -22,6 +23,7 @@ export function createStorageProviders(environment: Environment = process.env):

const tokenPath = required(environment.SSM_TOKEN_PATH, 'SSM_TOKEN_PATH');
const tokenTtlSeconds = parseSsmTokenTtlSeconds(environment.SSM_TOKEN_TTL_SECONDS);
const parameterTier = parseSsmRunnerConfigTier(environment.SSM_RUNNER_CONFIG_TIER);
const configPath = required(environment.SSM_CONFIG_PATH, 'SSM_CONFIG_PATH');
const parameterStoreTags = loadSsmParameterStoreTagsFromEnvironment(environment);
const consumerConfig = loadRunnerConfigConsumerConfigFromEnvironment(environment);
Expand All @@ -35,6 +37,7 @@ export function createStorageProviders(environment: Environment = process.env):
runnerConfig: createAwsSsmRunnerConfigStore({
tokenPath,
tokenTtlSeconds,
parameterTier,
parameterStoreTags,
maxWritesPerSecond: resolveMaxWritesPerSecond(environment.SSM_PARAMETER_STORE_MAX_WRITES_PER_SECOND),
}),
Expand Down
3 changes: 2 additions & 1 deletion main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ module "runners" {
tokens = "${var.ssm_paths.runners}/tokens"
config = "${var.ssm_paths.runners}/config"
}
ssm_ttl_seconds = var.ssm_ttl_seconds
ssm_ttl_seconds = var.ssm_ttl_seconds
runner_config_ssm_parameter_tier = var.runner_config_ssm_parameter_tier

s3_runner_binaries = var.enable_runner_binaries_syncer ? {
arn = module.runner_binaries[0].bucket.arn
Expand Down
2 changes: 1 addition & 1 deletion modules/multi-runner/README.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions modules/multi-runner/config.experimental.translation.tf
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,7 @@ locals {
ttl_seconds = {
tokens = v.runner_config.ssm_ttl_seconds.tokens
}
runner_config_tier = v.runner_config.runner_config_ssm_parameter_tier
paths = {
root = null
tokens = null
Expand Down
3 changes: 2 additions & 1 deletion modules/multi-runner/runners.tf
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ module "runners" {
tokens = each.value.storage_provider.aws.ssm.paths.tokens
config = each.value.storage_provider.aws.ssm.paths.config
}
ssm_ttl_seconds = each.value.storage_provider.aws.ssm.ttl_seconds
ssm_ttl_seconds = each.value.storage_provider.aws.ssm.ttl_seconds
runner_config_ssm_parameter_tier = each.value.storage_provider.aws.ssm.runner_config_tier

runner_os = each.value.runner.os
instance_types = each.value.compute_provider.aws.ec2.instance_types
Expand Down
6 changes: 5 additions & 1 deletion modules/multi-runner/tests/config-translation.tftest.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ run "empty_v2_map_translates_stable_inputs" {
ssm_ttl_seconds = {
tokens = 3600
}
runner_config_ssm_parameter_tier = "Advanced"
runner_iam_role_managed_policy_arns = [
"arn:aws:iam::123456789012:policy/stable-runner",
]
Expand Down Expand Up @@ -452,6 +453,7 @@ run "empty_v2_map_translates_stable_inputs" {
condition = (
local.normalized_config.multi_runner_config["stable"].runner.os == "linux"
&& local.effective_config.multi_runner_config["stable"].storage_provider.aws.ssm.ttl_seconds.tokens == 3600
&& local.effective_config.multi_runner_config["stable"].storage_provider.aws.ssm.runner_config_tier == "Advanced"
&& local.normalized_config.multi_runner_config["stable"].runner.architecture == "x64"
&& local.normalized_config.multi_runner_config["stable"].runner.group_name == "stable-group"
&& local.normalized_config.multi_runner_config["stable"].runner.iam.managed_policy_arns["legacy-0"] == "arn:aws:iam::123456789012:policy/stable-runner"
Expand Down Expand Up @@ -508,7 +510,8 @@ run "non_empty_v2_map_is_authoritative" {
storage_provider = {
aws = {
ssm = {
ttl_seconds = { tokens = 7200 }
ttl_seconds = { tokens = 7200 }
runner_config_tier = "Advanced"
}
}
}
Expand Down Expand Up @@ -536,6 +539,7 @@ run "non_empty_v2_map_is_authoritative" {
&& toset(keys(local.normalized_config.multi_runner_config)) == toset(["experimental"])
&& local.normalized_config.tags.source == "experimental"
&& local.effective_config.multi_runner_config["experimental"].storage_provider.aws.ssm.ttl_seconds.tokens == 7200
&& local.effective_config.multi_runner_config["experimental"].storage_provider.aws.ssm.runner_config_tier == "Advanced"
&& toset(local.normalized_config.multi_runner_config["experimental"].compute_provider.aws.ec2.instance_types) == toset(["c7g.large"])
&& flatten(local.normalized_config.multi_runner_config["experimental"].orchestration_provider.webhook.matcherConfig.labelMatchers) == ["experimental"]
)
Expand Down
Loading