June 19, 2025

Deploying AWS Glue Jobs with the AWS CDK in Python

Creating an AWS Glue job in the console takes a couple of minutes. Creating the same job consistently in dev, staging and production, with the right IAM role, script version, worker settings, job parameters and schedule, and keeping all three in step a year later, is a different problem. Console-built jobs drift: someone changes the worker count in prod to fix an incident, and nobody remembers to change it anywhere else.

For the last few years I've defined Glue jobs and everything around them with the AWS CDK in Python. The CDK generates CloudFormation, so every environment is built from the same code, every change goes through a pull request, and the console becomes read-only in practice. This post shows the patterns I use, with an insurance data pipeline as the example.

Project layout

 1: glue-platform/
 2:   app.py
 3:   cdk.json
 4:   stacks/
 5:     glue_jobs_stack.py
 6:   glue_scripts/
 7:     load_risks.py
 8:     load_claims.py
 9:   tests/
10:     test_glue_jobs_stack.py

Environment settings in context

Settings that differ by environment live in cdk.json, not in the code:

 1: {
 2:   "app": "python app.py",
 3:   "context": {
 4:     "environments": {
 5:       "dev":     { "account": "111111111111", "region": "eu-west-2", "max_workers": 4,  "schedule": null },
 6:       "staging": { "account": "222222222222", "region": "eu-west-2", "max_workers": 10, "schedule": null },
 7:       "prod":    { "account": "333333333333", "region": "eu-west-2", "max_workers": 20, "schedule": "cron(0 5 * * ? *)" }
 8:     }
 9:   }
10: }
 1: # app.py
 2: import aws_cdk as cdk
 3: from stacks.glue_jobs_stack import GlueJobsStack
 4: 
 5: app = cdk.App()
 6: env_name = app.node.try_get_context("env") or "dev"
 7: cfg = app.node.try_get_context("environments")[env_name]
 8: 
 9: GlueJobsStack(
10:     app, f"glue-jobs-{env_name}",
11:     env_name=env_name, cfg=cfg,
12:     env=cdk.Environment(account=cfg["account"], region=cfg["region"]),
13: )
14: app.synth()

Deploying an environment is then cdk deploy -c env=staging.

The stack: buckets, role, scripts and jobs

 1: # stacks/glue_jobs_stack.py
 2: from aws_cdk import Stack, RemovalPolicy, aws_s3 as s3, aws_iam as iam, aws_glue as glue
 3: from aws_cdk.aws_s3_assets import Asset
 4: from constructs import Construct
 5: 
 6: class GlueJobsStack(Stack):
 7:     def __init__(self, scope: Construct, cid: str, *, env_name: str, cfg: dict, **kwargs):
 8:         super().__init__(scope, cid, **kwargs)
 9: 
10:         data_bucket = s3.Bucket(
11:             self, "DataBucket",
12:             bucket_name=f"data-{env_name}-{self.account}",
13:             encryption=s3.BucketEncryption.S3_MANAGED,
14:             block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
15:             enforce_ssl=True,
16:             removal_policy=RemovalPolicy.RETAIN,
17:         )
18: 
19:         role = iam.Role(
20:             self, "GlueJobRole",
21:             assumed_by=iam.ServicePrincipal("glue.amazonaws.com"),
22:             managed_policies=[iam.ManagedPolicy.from_aws_managed_policy_name(
23:                 "service-role/AWSGlueServiceRole")],
24:         )
25:         data_bucket.grant_read_write(role)
26: 
27:         for job_name in ["load_risks", "load_claims"]:
28:             self._glue_job(job_name, role, data_bucket, env_name, cfg)

Two details matter here. RemovalPolicy.RETAIN stops a stack deletion from deleting the data, and grant_read_write creates a least-privilege policy for that one bucket instead of a hand-written wildcard.

A reusable job definition

The scripts are uploaded as CDK assets, so every deployment ships the script version that's in the same commit as the job definition. That rules out the classic mismatch where the job definition changed but someone forgot to upload the new script, or the other way round.

 1:     def _glue_job(self, job_name, role, data_bucket, env_name, cfg):
 2:         script = Asset(self, f"{job_name}Script", path=f"glue_scripts/{job_name}.py")
 3:         script.grant_read(role)
 4: 
 5:         glue.CfnJob(
 6:             self, f"{job_name}Job",
 7:             name=f"{job_name}_{env_name}",
 8:             role=role.role_arn,
 9:             glue_version="5.0",
10:             worker_type="G.1X",
11:             number_of_workers=cfg["max_workers"],
12:             timeout=120,
13:             max_retries=1,
14:             command=glue.CfnJob.JobCommandProperty(
15:                 name="glueetl",
16:                 python_version="3",
17:                 script_location=script.s3_object_url,
18:             ),
19:             default_arguments={
20:                 "--enable-auto-scaling": "true",
21:                 "--enable-metrics": "true",
22:                 "--enable-continuous-cloudwatch-log": "true",
23:                 "--job-bookmark-option": "job-bookmark-disable",
24:                 "--datalake-formats": "iceberg",
25:                 "--data_bucket": data_bucket.bucket_name,
26:                 "--env_name": env_name,
27:             },
28:             tags={"project": "data-platform", "env": env_name},
29:         )

I use the L1 CfnJob construct because it maps one-to-one to CloudFormation and is stable. There's a higher-level Glue construct library too, which is worth a look if you want friendlier defaults.

Job parameters such as --data_bucket and --env_name mean the script never hard-codes an environment. Inside the script they're read with getResolvedOptions.

Orchestration with Step Functions

Risk transactions must load before claims, because claims reference risks. A small Step Functions state machine runs the jobs in order and waits for each to finish:

 1: from aws_cdk import aws_stepfunctions as sfn, aws_stepfunctions_tasks as tasks
 2: from aws_cdk import aws_events as events, aws_events_targets as targets
 3: 
 4: risk = tasks.GlueStartJobRun(
 5:     self, "LoadRisk", glue_job_name=f"load_risk_transactions_{env_name}",
 6:     integration_pattern=sfn.IntegrationPattern.RUN_JOB)
 7: 
 8: claims = tasks.GlueStartJobRun(
 9:     self, "LoadClaims", glue_job_name=f"load_claim_transactions_{env_name}",
10:     integration_pattern=sfn.IntegrationPattern.RUN_JOB)
11: 
12: machine = sfn.StateMachine(
13:     self, "DailyLoad",
14:     definition_body=sfn.DefinitionBody.from_chainable(risk.next(claims)))
15: 
16: if cfg["schedule"]:
17:     events.Rule(self, "DailySchedule",
18:                 schedule=events.Schedule.expression(cfg["schedule"]),
19:                 targets=[targets.SfnStateMachine(machine)])

The schedule only exists in production, because the context sets it to null elsewhere. Dev and staging runs are started by hand or from CI. Add a failure branch that publishes to an SNS topic and you have alerting too.

Testing the stack

CDK's assertions module lets you test the generated template, which catches mistakes before they reach AWS:

 1: # tests/test_glue_jobs_stack.py
 2: import aws_cdk as cdk
 3: from aws_cdk.assertions import Template, Match
 4: from stacks.glue_jobs_stack import GlueJobsStack
 5: 
 6: def test_jobs_use_glue_5_and_auto_scaling():
 7:     app = cdk.App()
 8:     cfg = {"account": "111111111111", "region": "eu-west-2", "max_workers": 4, "schedule": None}
 9:     stack = GlueJobsStack(app, "test", env_name="dev", cfg=cfg,
10:                           env=cdk.Environment(account=cfg["account"], region=cfg["region"]))
11:     template = Template.from_stack(stack)
12: 
13:     template.resource_count_is("AWS::Glue::Job", 2)
14:     template.has_resource_properties("AWS::Glue::Job", {
15:         "GlueVersion": "5.0",
16:         "DefaultArguments": Match.object_like({"--enable-auto-scaling": "true"}),
17:     })

Deploying from GitHub Actions

The pipeline runs the tests, shows a cdk diff on pull requests, and deploys on merge. It authenticates to AWS with OpenID Connect, so there are no long-lived access keys stored in GitHub:

 1: name: deploy
 2: on:
 3:   push:
 4:     branches: [main]
 5: permissions:
 6:   id-token: write
 7:   contents: read
 8: jobs:
 9:   deploy-staging:
10:     runs-on: ubuntu-latest
11:     steps:
12:       - uses: actions/checkout@v4
13:       - uses: actions/setup-python@v5
14:         with: { python-version: '3.11' }
15:       - uses: actions/setup-node@v4
16:         with: { node-version: '20' }
17:       - run: npm install -g aws-cdk && pip install -r requirements.txt
18:       - run: pytest -q
19:       - uses: aws-actions/configure-aws-credentials@v4
20:         with:
21:           role-to-assume: arn:aws:iam::222222222222:role/github-deploy
22:           aws-region: eu-west-2
23:       - run: cdk deploy -c env=staging --require-approval never

Production uses the same workflow behind a GitHub environment with required reviewers, so a person approves each production release.

What I've learned

  • Treat the console as read-only. Any manual change will be overwritten by the next deployment, which is exactly the point.
  • Keep environment differences in context, not in if env == "prod" branches scattered through the code.
  • Ship scripts as assets so the job definition and the script can never get out of step.
  • Retain data buckets and anything else you can't afford to lose if a stack is deleted.
  • Run cdk diff in every pull request. Reviewers see exactly what will change in AWS, not just the code.