用于自主托管 GitHub Actions 运行程序的 CDK 构建
[][7] [][6] [][8] [][11] [][12] [][20] Use this CDK construct to create ephemeral [self-hosted GitHub runners][1] on-demand inside your AWS account.
Self-hosted runners in AWS are useful when:
Ephemeral (or on-demand) runners are the [recommended way by GitHub][14] for auto-scaling, and they make sure all jobs run with a clean image. Runners are started on-demand. You don't pay unless a job is running.
The best way to browse API documentation is on [Constructs Hub][13]. It is available in all supported programming languages.
A runner provider creates compute resources on-demand and uses [actions/runner][5] to start a runner.
| EC2 | CodeBuild | Fargate | ECS | Lambda | |
|---|---|---|---|---|---|
| Time limit | Unlimited | 36 hours (default 1 hour) | Unlimited | Unlimited | 15 minutes |
| vCPUs | Unlimited | 2, 4, 8, or 72 | 0.25 to 4 | Unlimited | 1 to 6 |
| RAM | Unlimited | 3gb, 7gb, 15gb, or 145gb | 512mb to 30gb | Unlimited | 128mb to 10gb |
| Storage | Unlimited | 50gb to 824gb | 20gb to 200gb | Unlimited | Up to 10gb |
| Architecture | x86_64, ARM64 | x86_64, ARM64 | x86_64, ARM64 | x86_64, ARM64 | x86_64, ARM64 |
| GPU | ✔ | ✔ | ❌ | ✔ | ❌ |
| sudo | ✔ | ✔ | ✔ | ✔ | ❌ |
| Docker | ✔ | ✔ (Linux only) | ❌ | ✔ | ❌ |
| Spot pricing | ✔ | ❌ | ✔ | ✔ | ❌ |
| OS | Linux, Windows | Linux, Windows | Linux, Windows | Linux, Windows | Linux |
The best provider to use mostly depends on your current infrastructure. When in doubt, CodeBuild is always a good choice. Execution history and logs are easy to view, and it has no restrictive limits unless you need to run for more than 8 hours.
Install and use the appropriate package Python
Available on [PyPI][6].
pip install cloudsnorkel.cdk-github-runnersfrom aws_cdk import App, Stack
from cloudsnorkel.cdk_github_runners import GitHubRunners
app = App()
stack = Stack(app, "github-runners")
GitHubRunners(stack, "runners")
app.synth()TypeScript or JavaScript
Available on [npm][7].
npm i @cloudsnorkel/cdk-github-runnersimport { App, Stack } from 'aws-cdk-lib';
import { GitHubRunners } from '@cloudsnorkel/cdk-github-runners';
const app = new App();
const stack = new Stack(app, 'github-runners');
new GitHubRunners(stack, 'runners');
app.synth();Java
Available on [Maven][8].
com.cloudsnorkel
cdk.github.runners
import software.amazon.awscdk.App;
import software.amazon.awscdk.Stack;
import com.cloudsnorkel.cdk.github.runners.GitHubRunners;
public class Example {
public static void main(String[] args){
App app = new App();
Stack stack = new Stack(app, "github-runners");
GitHubRunners.Builder.create(stack, "runners").build();
app.synth();
}
} Go
Available on [GitHub][11].
go get github.com/CloudSnorkel/cdk-github-runners-go/cloudsnorkelcdkgithubrunnerspackage main
import (
"github.com/CloudSnorkel/cdk-github-runners-go/cloudsnorkelcdkgithubrunners"
"github.com/aws/aws-cdk-go/awscdk/v2"
"github.com/aws/jsii-runtime-go"
)
func main() {
app := awscdk.NewApp(nil)
stack := awscdk.NewStack(app, jsii.String("github-runners"), &awscdk.StackProps{})
cloudsnorkelcdkgithubrunners.NewGitHubRunners(stack, jsii.String("runners"), &cloudsnorkelcdkgithubrunners.GitHubRunnersProps{})
app.Synth(nil)
}.NET
Available on [Nuget][12].
dotnet add package CloudSnorkel.Cdk.Github.Runnersusing Amazon.CDK;
using CloudSnorkel;
namespace Example
{
sealed class Program
{
public static void Main(string[] args)
{
var app = new App();
var stack = new Stack(app, "github-runners");
new GitHubRunners(stack, "runners");
app.Synth();
}
}
}Use GitHubRunners construct in your code (starting with default arguments is fine)
Deploy your stack
Look for the status command output similar to aws --region us-east-1 lambda invoke --function-name status-XYZ123 status.json
✅ github-runners-test
✨ Deployment time: 260.01s
Outputs:
github-runners-test.runnersstatuscommand4A30F0F5 = aws --region us-east-1 lambda invoke --function-name github-runners-test-runnersstatus1A5771C0-mvttg8oPQnQS status.jsonExecute the status command (you may need to specify --profile too) and open the resulting status.json file
Open the URL in github.setup.url from status.json or manually setup GitHub integration as an app or with personal access token
Run status command again to confirm github.auth.status and github.webhook.status are OK
Trigger a GitHub action that has a self-hosted label with runs-on: [self-hosted, codebuild] (or non-default labels you set in step 2)
If the action is not successful, see troubleshooting
The default providers configured by GitHubRunners are useful for testing but probably not too much for actual production work. They run in the default VPC or no VPC and have no added IAM permissions. You would usually want to configure the providers yourself.
For example:
let vpc: ec2.Vpc;
let runnerSg: ec2.SecurityGroup;
let dbSg: ec2.SecurityGroup;
let bucket: s3.Bucket;
// create a custom CodeBuild provider
const myProvider = new CodeBuildRunnerProvider(this, 'codebuild runner', {
labels: ['my-codebuild'],
vpc: vpc,
securityGroups: [runnerSg],
});
// grant some permissions to the provider
bucket.grantReadWrite(myProvider);
dbSg.connections.allowFrom(runnerSg, ec2.Port.tcp(3306), 'allow runners to connect to MySQL database');
// create the runner infrastructure
new GitHubRunners(this, 'runners', {
providers: [myProvider],
});Another way to customize runners is by modifying the image used to spin them up. The image contains the [runner][5], any required dependencies, and integration code with the provider. You may choose to customize this image by adding more packages, for example.
const myBuilder = FargateRunnerProvider.imageBuilder(this, 'image builder');
myBuilder.addComponent(
RunnerImageComponent.custom({ commands: ['apt install -y nginx xz-utils'] }),
);
const myProvider = new FargateRunnerProvider(this, 'fargate runner', {
labels: ['customized-fargate'],
imageBuilder: myBuilder,
});
// create the runner infrastructure
new GitHubRunners(this, 'runners', {
providers: [myProvider],
});Your workflow will then look like:
name: self-hosted example
on: push
jobs:
self-hosted:
runs-on: [self-hosted, customized-fargate]
steps:
- run: echo hello worldWindows images can also be customized the same way.
…The runner OS and architecture is determined by the image it is set to use. For example, to create a Fargate runner provider for ARM64 set the architecture property for the image builder to Architecture.ARM64 in the image builder properties.
new GitHubRunners(this, 'runners', {
providers: [
new FargateRunnerProvider(this, 'fargate runner', {
labels: ['arm64', 'fargate'],
imageBuilder: FargateRunnerProvider.imageBuilder(this, 'image builder', {
architecture: Architecture.ARM64,
os: Os.LINUX_UBUNTU,
}),
}),
],
});Composite providers allow you to combine multiple runner providers with different strategies. There are two types:
Fallback Strategy: Try providers in order until one succeeds. Useful for trying spot instances first, then falling back to on-demand if spot capacity is unavailable.
// Try spot instances first, fall back to on-demand if spot is unavailable
const ecsFallback = CompositeProvider.fallback(this, 'ECS Fallback', [
new EcsRunnerProvider(this, 'ECS Spot', {
labels: ['ecs', 'linux', 'x64'],
spot: true,
// ... other config
}),
new EcsRunnerProvider(this, 'ECS On-Demand', {
labels: ['ecs', 'linux', 'x64'],
spot: false,
// ... other config
}),
]);
new GitHubRunners(this, 'runners', {
providers: [ecsFallback],
});Weighted Distribution Strategy: Randomly select a provider based on weights. Useful for distributing load across multiple availability zones or instance types.
…Important: All providers in a composite must have the exact same labels. This ensures any provisioned runner can match the labels requested by the GitHub workflow job.
By default, providers are selected based on label matching: the first provider that has all the labels requested by the job is selected. You can customize this behavior using a provider selector Lambda function to:
The selector function receives the full GitHub webhook payload, a map of all available providers and their labels, and the default provider/labels that would have been selected. It returns the provider to use (or undefined to skip runner creation) and the labels to assign to the runner.
Example: Route jobs to different providers based on repository
…Example: Add dynamic labels based on job metadata
const providerSelector =暂无开放 Issues,或尚未同步最近议题。