Frecuentemente publicamos actualizaciones de nuestra documentación. Es posible que la traducción de esta página esté en curso. Para conocer la información más actual, visita la documentación en inglés. Si existe un problema con las traducciones en esta página, por favor infórmanos.

Configuring code scanning

You can configure how GitHub scans the code in your project for vulnerabilities and errors.

People with write permissions to a repository can configure escaneo de código for the repository.

Escaneo de código is available if you have a license for GitHub Advanced Security. For more information, see "About GitHub Advanced Security."

En este artículo

Nota: Escaneo de código se encuentra acutalmente en beta y está sujeto a cambios. If your organization has an Advanced Security license, you can join the beta program.

Note: Your site administrator must enable escaneo de código for tu instancia de servidor de GitHub Enterprise before you can use this feature. If you want to use GitHub Actions to scan your code, the site administrator must also enable GitHub Actions and set up the infrastructure required. For more information, see "Configuring escaneo de código for your appliance."

About escaneo de código configuration

You can run escaneo de código on GitHub Enterprise, using GitHub Actions, or from your continuous integration (CI) system. For more information, see "About GitHub Actions" or "Running CodeQL runner in your CI system."

This article is about running escaneo de código on GitHub Enterprise using actions.

Before you can configure escaneo de código for a repository, you must set up escaneo de código by adding a GitHub Actions workflow to the repository. For more information, see "Setting up escaneo de código for a repository."

Habitualmente, no necesitas editar el flujo de trabajo predeterminado para escaneo de código. However, if required, you can edit the workflow to customize some of the settings. For example, you can edit GitHub's CodeQL Analysis workflow to specify the frequency of scans, the languages or directories to scan, and what CodeQL escaneo de código looks for in your code. You might also need to edit the workflow if you use a specific set of commands to compile your code or if there is more than one compiled language in your repository.

CodeQL analysis is just one type of escaneo de código you can do in GitHub. Mercado GitHub on contains other escaneo de código workflows you can use. The specific examples given in this article relate to the CodeQL Analysis workflow file.

Editing a escaneo de código workflow

GitHub saves workflow files in the .github/workflows directory of your repository. You can find a workflow you have added by searching for its file name. For example, by default, the workflow file for CodeQL escaneo de código is called codeql-analysis.yml.

  1. In your repository, browse to the workflow file you want to edit.
  2. In the upper right corner of the file view, to open the workflow editor, click . Edit workflow file button
  3. After you have edited the file, click Start commit and complete the "Commit changes" form. You can choose to commit directly to the current branch, or create a new branch and start a pull request. Commit update to codeql.yml workflow

For more information about editing workflow files, see "Learn GitHub Actions."

Configuring frequency

You can configure the CodeQL Analysis workflow to scan code on a schedule or when specific events occur in a repository.

Scanning code when someone pushes a change, and whenever a pull request is created, prevents developers from introducing new vulnerabilities and errors into the code. Scanning code on a schedule informs you about the latest vulnerabilities and errors that GitHub, security researchers, and the community discover, even when developers aren't actively maintaining the repository.

Scanning on push

By default, the CodeQL Analysis workflow uses the on.push event to trigger a code scan on every push to the default branch of the repository and any protected branches. For escaneo de código to be triggered on a specified branch, the workflow must exist in that branch. For more information, see "Workflow syntax for GitHub Actions."

If you scan on push, then the results appear in the Security tab for your repository. For more information, see "Managing code scanning alerts for your repository."

Note: If you want escaneo de código alerts to appear as pull request checks, you must use the pull_request event, described below.

Scanning pull requests

The default CodeQL Analysis workflow uses the pull_request event to trigger a code scan on pull requests targeted against the default branch. The pull_request event is not triggered if the pull request was opened from a private fork.

For more information about the pull_request event, see "Workflow syntax for GitHub Actions."

If you scan pull requests, then the results appear as alerts in a pull request check. For more information, see "Triaging code scanning alerts in pull requests."

Avoiding unnecessary scans of pull requests

You might want to avoid a code scan being triggered on specific pull requests targeted against the default branch, irrespective of which files have been changed. You can configure this by specifying on:pull_request:paths-ignore or on:pull_request:paths in the escaneo de código workflow. For example, if the only changes in a pull request are to files with the file extensions .md or .txt you can use the following paths-ignore array.

    branches: [main, protected]
    branches: [main]
      - '**/*.md'
      - '**/*.txt'


  • on:pull_request:paths-ignore and on:pull_request:paths set conditions that determine whether the actions in the workflow will run on a pull request. They don't determine what files will be analyzed when the actions are run. When a pull request contains any files that are not matched by on:pull_request:paths-ignore or on:pull_request:paths, the workflow runs the actions and scans all of the files changed in the pull request, including those matched by on:pull_request:paths-ignore or on:pull_request:paths, unless the files have been excluded. For information on how to exclude files from analysis, see "Specifying directories to scan."
  • For CodeQL escaneo de código workflow files, don't use the paths-ignore or paths keywords with the on:push event as this is likely to cause missing analyses. For accurate results, CodeQL escaneo de código needs to be able to compare new changes with the analysis of the previous commit.

For more information about using on:pull_request:paths-ignore and on:pull_request:paths to determine when a workflow will run for a pull request, see "Workflow syntax for GitHub Actions."

Scanning on a schedule

If you use the default CodeQL Analysis workflow, the workflow will scan the code in your repository once a week, in addition to the scans triggered by events. To adjust this schedule, edit the cron value in the workflow. For more information, see "Workflow syntax for GitHub Actions."

Note: GitHub only runs scheduled jobs that are in workflows on the default branch. Changing the schedule in a workflow on any other branch has no effect until you merge the branch into the default branch.


The following example shows a CodeQL Analysis workflow for a particular repository that has a default branch called main and one protected branch called protected.

    branches: [main, protected]
    branches: [main]
    - cron: '20 14 * * 1'

This workflow scans:

  • Every push to the default branch and the protected branch
  • Every pull request to the default branch
  • The default branch every Monday at 14:20 UTC

Specifying an operating system

If your code requires a specific operating system to compile, you can configure the operating system in your CodeQL Analysis workflow. Edit the value of jobs.analyze.runs-on to specify the operating system for the machine that runs your escaneo de código actions. You specify the operating system by using an appropriate label as the second element in a two-element array, after self-hosted.

    name: Analyze
    runs-on: [self-hosted, ubuntu-latest]

CodeQL escaneo de código supports the latest versions of Ubuntu, Windows, and macOS. Typical values for this setting are therefore: ubuntu-latest, windows-latest, and macos-latest. For more information, see "Workflow syntax for GitHub Actions" and "Using labels with self-hosted runners."

You must ensure that Git is in the PATH variable on your self-hosted runners.

Changing the languages that are analyzed

CodeQL escaneo de código automatically detects code written in the supported languages.

  • C/C++
  • C#
  • Go
  • Java
  • JavaScript/TypeScript
  • Python

The default CodeQL Analysis workflow file contains a build matrix called language which lists the languages in your repository that are analyzed. CodeQL automatically populates this matrix when you add escaneo de código to a repository. Using the language matrix optimizes CodeQL to run each analysis in parallel. We recommend that all workflows adopt this configuration due to the performance benefits of parallelizing builds. For more information about build matrices, see "Managing complex workflows."

Si tu repositorio contiene código en varios lenguajes, puedes especificar aquellos que quieras analizar. Hay varias razones que por las cuales querrías prevenir que un lenguaje se analice. Por ejemplo, el proyecto puede tener dependencias en un lenguaje distinto al del cuerpo principal de tu código, y tal vez prefieras no ver las alertas para esas dependencias.

If your workflow uses the language matrix then CodeQL is hardcoded to analyze only the languages in the matrix. To change the languages you want to analyze, edit the value of the matrix variable. You can remove a language to prevent it being analyzed or you can add a language that was not present in the repository when escaneo de código was set up. For example, if the repository initially only contained JavaScript when escaneo de código was set up, and you later added Python code, you will need to add python to the matrix.

    name: Analyze
      fail-fast: false
        language: ['javascript', 'python']

If your workflow does not contain a matrix called language, then CodeQL is configured to run analysis sequentially. If you don't specify languages in the workflow, CodeQL automatically detects, and attempts to analyze, any supported languages in the repository. If you want to choose which languages to analyze, without using a matrix, you can use the languages parameter under the init action.

- uses: github/codeql-action/init@v1
    languages: cpp, csharp, python

Running additional queries

When you use CodeQL to scan code, the CodeQL analysis engine generates a database from the code and runs queries on it. Para obtener más información, consulta la sección "Acerca deescaneo de código".

CodeQL analysis uses a default set of queries, but you can specify more queries to run, in addition to the default queries. Las consultas que quieras ejecutar deberán pertenecer a un paquete de QL y pueden estar en tu propio repositorio o en cualquier repositorio público. Para obtener más información, consulta la sección "Acerca de los paquetes de QL".

Las consultas solo deberán depender de las bibliotecas estándar (es decir, aquellas referenciadas por una declaración import LANGUAGE en tu consulta), o de aquellas en el mismo paquete de QL que la consulta. Las bibliotecas estándar se ubican en el repositorio github/codeql. For more information, see "About CodeQL queries."

Puedes especificar un solo archivo .ql, un directorio que contenga varios archivos .ql, un archivo de definición de suite de consulta .qls, o cualquier combinación de éstos. For more information about query suite definitions, see "Creating CodeQL query suites."

To add one or more queries, add a with: queries: entry within the uses: github/codeql-action/init@v1 section of the workflow. If the queries are in a private repository, use the external-repository-token parameter to specify a token that has access to the private repository.

- uses: github/codeql-action/init@v1
    # Optional. Provide a token to access private repositories.
    external-repository-token: ${{ secrets.ACCESS_TOKEN }}

You can also specify query suites in the value of queries. Query suites are collections of queries, usually grouped by purpose or language.

The following query suites are built into CodeQL escaneo de código and are available for use.

Conjunto de consultasDescripción
security-extendedLas consultas de severidad y precisión más baja que aquellas predeterminadas
security-and-qualityLas consultas de security-extended, mas aquellas de mantenibilidad y confiabilidad

When you specify a query suite, the CodeQL analysis engine will run the queries contained within the suite for you, in addition to the default set of queries.

If you are also using a configuration file for custom settings, any additional queries specified in your workflow are used instead of any specified in the configuration file. If you want to run the combined set of additional queries specified here and in the configuration file, prefix the value of queries in the workflow with the + symbol. For more information, see "Using a custom configuration file."

In the following example, the + symbol ensures that the specified additional queries are used together with any queries specified in the referenced configuration file.

- uses: github/codeql-action/init@v1
    config-file: ./.github/codeql/codeql-config.yml
    queries: +security-and-quality,octo-org/python-qlpack/show_ifs.ql@main
    external-repository-token: ${{ secrets.ACCESS_TOKEN }}

Using a custom configuration file

As an alternative to specifying which queries to run in the workflow file, you can do this in a separate configuration file. You can also use a configuration file to disable the default queries and to specify which directories to scan during analysis.

In the workflow file, use the config-file parameter of the init action to specify the path to the configuration file you want to use. This example loads the configuration file ./.github/codeql/codeql-config.yml.

- uses: github/codeql-action/init@v1
    config-file: ./.github/codeql/codeql-config.yml

The configuration file can be located within the repository you are analyzing, or in an external repository. Using an external repository allows you to specify configuration options for multiple repositories in a single place. When you reference a configuration file located in an external repository, you can use the OWNER/REPOSITORY/FILENAME@BRANCH syntax. For example, monacorp/shared/codeql-config.yml@main.

If the configuration file is located in an external private repository, use the external-repository-token parameter of the init action to specify a token that has access to the private repository.

uses: github/codeql-action/init@v1
  external-repository-token: ${{ secrets.ACCESS_TOKEN }}

The settings in the configuration file are written in YAML format.

Specifying additional queries

You specify additional queries in a queries array. Each element of the array contains a uses parameter with a value that identifies a single query file, a directory containing query files, or a query suite definition file.

  - uses: ./my-basic-queries/example-query.ql
  - uses: ./my-advanced-queries
  - uses: ./codeql-qlpacks/complex-python-qlpack/rootAndBar.qls

Optionally, you can give each array element a name, as shown in the example configuration files below.

For more information about additional queries, see "Running additional queries" above.

Disabling the default queries

If you only want to run custom queries, you can disable the default security queries by using disable-default-queries: true.

Specifying directories to scan

For the interpreted languages that CodeQL supports (Python and JavaScript/TypeScript), you can restrict escaneo de código to files in specific directories by adding a paths array to the configuration file. You can exclude the files in specific directories from analysis by adding a paths-ignore array.

  - src
  - src/node_modules
  - '**/*.test.js'


  • The paths and paths-ignore keywords, used in the context of the escaneo de código configuration file, should not be confused with the same keywords when used for on.<push|pull_request>.paths in a workflow. When they are used to modify on.<push|pull_request> in a workflow, they determine whether the actions will be run when someone modifies code in the specified directories. For more information, see "Workflow syntax for GitHub Actions."
  • The filter pattern characters ?, +, [, ], and ! are not supported and will be matched literally.
  • ** characters can only be at the start or end of a line, or surrounded by slashes, and you can't mix ** and other characters. For example, foo/**, **/foo, and foo/**/bar are all allowed syntax, but **foo isn't. However you can use single stars along with other characters, as shown in the example. You'll need to quote anything that contains a * character.

For compiled languages, if you want to limit escaneo de código to specific directories in your project, you must specify appropriate build steps in the workflow. The commands you need to use to exclude a directory from the build will depend on your build system. For more information, see "Configuring the CodeQL workflow for compiled languages."

You can quickly analyze small portions of a monorepo when you modify code in specific directories. You'll need to both exclude directories in your build steps and use the paths-ignore and paths keywords for on.<push|pull_request> in your workflow.

Example configuration files

Este archivo de configuración agrega el conjunto de consultas security-and-quality a la lista de consultas que se ejecutan con CodeQL cuando se escanea tu código. Para obtener más información acerca de los conjuntos de consultas que están disponibles para utilizarse, consulta la sección "Ejecutar consultas adicionales".

name: "My CodeQL config"

  - uses: security-and-quality

The following configuration file disables the default queries and specifies a set of custom queries to run instead. It also configures CodeQL to scan files in the src directory (relative to the root), and to exclude the node_modules directory (also relative to the root), as well as any file whose name ends in .test.js.

name: "My CodeQL config"

disable-default-queries: true

  - name: Use an in-repository QL pack (run queries in the my-queries directory)
    uses: ./my-queries
  - name: Use an external JavaScript QL pack (run queries from an external repo)
    uses: octo-org/javascript-qlpack@main
  - name: Use an external query (run a single query from an external QL pack)
    uses: octo-org/python-qlpack/show_ifs.ql@main
  - name: Use a query suite file (run queries from a query suite in this repo)
    uses: ./codeql-qlpacks/complex-python-qlpack/rootAndBar.qls

  - node_modules
  - '**/*.test.js'
  - src 

Configuring escaneo de código for compiled languages

For compiled languages like C/C++, C#, and Java, the autobuild step in the default workflow attempts to build code before the action performs CodeQL analysis. En contraste con los otros lenguajes compilados, CodeQL analiza Go sin compilar el código.

El proceso de autobuild solo intenta siempre compilar un solo lenguaje compilado para un repositorio. El lenguaje que se selecciona automáticamente para el análisis es aquél con más archivos. CodeQL also runs a build for Go projects to set up the project. However, in contrast to the other compiled languages, all Go files in the repository are extracted, not just those that are built. Custom build commands are not supported for Go.

Si el código de C/C++, C# o Java de tu repositorio tiene un proceso de compilación no estándar o si está escrito en más de un lenguaje compilado, el autobuild podría fallar. Necesitarás eliminar el paso de autobuild del flujo de trabajo y agregar los pasos de compilación manualmente. For more information about how to configure CodeQL escaneo de código for compiled languages, see "Configuring the CodeQL workflow for compiled languages."

Uploading escaneo de código data to GitHub

GitHub can display code analysis data generated externally by a third-party tool. You can upload code analysis data with the upload-sarif action. For more information, see "Uploading a SARIF file to GitHub."

¿Te ayudó este documento?

Privacy policy

Help us make these docs great!

All GitHub docs are open source. See something that's wrong or unclear? Submit a pull request.

Make a contribution

O, learn how to contribute.