I'm trying to piece together some scripts to add CodeQL scanning to a existing build pipeline on Azure DevOps. For compiled languages such as .NET, a pre-compile command is required to create a CodeQL database to watch the compile. I have set this up as follows:
YAML:
parameters:
- name: githubToken
default: ''
- name: buildType
default: ''
- name: codeql_db
default: "codeql-db"
steps:
- script: |
echo "##vso[task.prependpath]/apps/ado/tools/codeql"
displayName: 'Setup codeql'
- task: PythonScript@0
displayName: 'CodeQL setup environment'
inputs:
scriptSource: 'filepath'
scriptPath: '$(Pipeline.Workspace)/utils/codeql_setup.py'
arguments: '--github-token ${{ parameters.githubToken }} --build-type ${{ parameters.buildType }} --repository-name $(Build.Repository.Name) --repository-path $(Build.Repository.LocalPath) --agent-os $(agent.os) --codeql-db ${{ parameters.codeql_db }}'
workingDirectory: $(Pipeline.Workspace)
codeql_setup.py:
if build_type in compiled_buildtypes:
print('Compiled build type identified. Setting up indirect build tracing.', flush=True)
codeql_setup_command = ['codeql', 'database', 'init','--source-root', repository_local_path, '--language', repo_languages_argument, '--begin-tracing', codeql_db_name, '--overwrite']
# Set additional options
if len(repo_languages) > 1 :
print('Multiple languages detected.', flush=True)
codeql_setup_command.append('--db-cluster')
if 'windows' in agent_os.lower():
print('Windows Agent detected.', flush=True)
codeql_setup_command.append(f'--trace-process-level {PROCESS_NUMBER}')
database_init_proc = subprocess.run(codeql_setup_command, env=os.environ.copy())
print('CodeQL database setup for indirect build tracing.', flush=True)
My issue is the second additional argument. For Windows agents, the process number or parent process name is required for codeQL to watch the compile.
Is there a simple way to get the process ID of the build? Similar to how I have retrieved the OS.
Checked the CodeQL scanning code and the Github doc. You need to get the current Agent.Worker.exe process id.
To meet your requirement, you can use the following PowerShell command to get the Process ID.
Get-Process Agent.Worker | Select id
And then you can set the ProcessID as Pipeline variable.
For example:
steps:
- powershell: |
Get-Process Agent.Worker | Select id
$test = Get-Process Agent.Worker | Select id
echo $test.id
echo "##vso[task.setvariable variable=ProcessID]$test.id"
You can use the variable: $(ProcessID)
in the next tasks.