How do I use GitHub Actions to build a Java application and scan its code with CodeQL?
Below is an example of a GitHub Actions workflow that caches Maven dependencies and uses github/codeql-actions/autobuild
in order to to build a Java application and run a CodeQL scan. The example also includes a commented section that provides an example of running your own build commands instead of “Autobuild”. While this example focuses on using Maven as the manager of Java build dependencies, similar steps should work for other build managers such as Ant or Maven.
name: "CodeQL"
on:
push:
branches: {}
pull_request:
branches: {}
schedule:
- cron: '20 12 * * 4'
jobs:
analyze-java:
name: Analyze Java
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
actions: read
contents: read
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: true
- name: Set up JDK 21
uses: actions/setup-java@v2
with:
## either set `java-version` or `java-version-file`
java-version: 21
#java-version-file: .java-version
## distribution is required
distribution: temurin
- name: Cache local Maven repository
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: $-maven-$
restore-keys: |
$-maven-
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: java
## Autobuild for Java supports Ant, Gradle, and Maven build systems
- name: Autobuild
uses: github/codeql-action/autobuild@v2
## If autobuild fails to work for your app, then try providing your own command(s) to run:
#
#- name: Install build dependencies with Maven
# run: maven install
#
#- name: Make a new app build
# run: make build
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:java"
Building Java applications requires you to do some additional work. In particular, you must set up the appropriate JDK distribution / version for your app, which is accomplished in the above example using the actions/setup-java
action. To minimize build times (and actions minutes consumed), you should also setup a local cache for dependencies downloaded via your Java dependency manager of choice, which is shown (for Maven) in the above example using the actions/setup-cache
action.
This example provides a generic approach to building a Java app using the github/codeql-action/autobuild
action – which has support for Ant, Gradle, and Maven build systems.
An alternative approach would be to run
command(s) as replacement(s) for the “Autobuild” step in the example above.
Once the solution is built we can then run the CodeQL analysis using the github/codeql-action/analyze
action.
References: