feat: add passing of Renovate environment variables (#534)

Inputs may now be provided using environment variables, as well as the existing inputs. None of the
inputs are required any more, so it is possible to use only environment variables. Nevertheless all
inputs must be provided in some way, either using the input or their corresponding environment
variables.

BREAKING CHANGE: The `configurationFile` input no longer has a default value. This means that a
value for it is now required using the `configurationFile` input or the `RENOVATE_CONFIG_FILE`
environment variable.

Co-authored-by: Michael Kriese <michael.kriese@visualon.de>
This commit is contained in:
Jeroen de Bruijn 2021-03-08 09:42:52 +01:00 committed by GitHub
parent 525abe5975
commit 9c8a784d88
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 139 additions and 48 deletions

View file

@ -48,6 +48,8 @@ jobs:
run: npm run build run: npm run build
- name: Renovate test - name: Renovate test
uses: ./ uses: ./
env:
LOG_LEVEL: debug
with: with:
configurationFile: ${{ matrix.configurationFile }} configurationFile: ${{ matrix.configurationFile }}
token: ${{ secrets.RENOVATE_TOKEN }} token: ${{ secrets.RENOVATE_TOKEN }}

View file

@ -25,6 +25,8 @@ GitHub Action to run Renovate self-hosted.
## Options ## Options
Options can be passed using the inputs of this action or the corresponding environment variables. When both are passed, the input takes precedence over the environment variable. For the available environment variables see the Renovate [Self-Hosted Configuration](https://docs.renovatebot.com/self-hosted-configuration/) and [Self-Hosting](https://docs.renovatebot.com/self-hosting/) docs.
## `configurationFile` ## `configurationFile`
Configuration file to configure Renovate. The supported configurations files can be one of the configuration files listed in the Renovate Docs for [Configuration Options](https://docs.renovatebot.com/configuration-options/) or a JavaScript file that exports a configuration object. For both of these options, an example can be found in the [example](./example) directory. Configuration file to configure Renovate. The supported configurations files can be one of the configuration files listed in the Renovate Docs for [Configuration Options](https://docs.renovatebot.com/configuration-options/) or a JavaScript file that exports a configuration object. For both of these options, an example can be found in the [example](./example) directory.
@ -80,11 +82,11 @@ jobs:
Instead of using a Personal Access Token (PAT) that is tied to a particular user you can use a [GitHub App](https://docs.github.com/en/developers/apps/building-github-apps) where permissions can be even better tuned. [Create a new app](https://docs.github.com/en/developers/apps/creating-a-github-app) and give it the following permissions: Instead of using a Personal Access Token (PAT) that is tied to a particular user you can use a [GitHub App](https://docs.github.com/en/developers/apps/building-github-apps) where permissions can be even better tuned. [Create a new app](https://docs.github.com/en/developers/apps/creating-a-github-app) and give it the following permissions:
| Permission | Level | | Permission | Level |
|-----------------|---------------------| | --------------- | -------------- |
| `Contents` | `Read & write` | | `Contents` | `Read & write` |
| `Metadata` | `Read-only` | | `Metadata` | `Read-only` |
| `Pull requests` | `Read & write` | | `Pull requests` | `Read & write` |
Store the app ID as a secret with name `APP_ID` and generate a new private key for the app and add it as a secret to the repository as `APP_PEM` in the repository where the action will run from. Note that `APP_PEM` needs to be base64 encoded. You can encode your private key file like this from the terminal: Store the app ID as a secret with name `APP_ID` and generate a new private key for the app and add it as a secret to the repository as `APP_PEM` in the repository where the action will run from. Note that `APP_PEM` needs to be base64 encoded. You can encode your private key file like this from the terminal:
@ -121,5 +123,5 @@ jobs:
uses: renovatebot/github-action@v21.30.0 uses: renovatebot/github-action@v21.30.0
with: with:
configurationFile: example/renovate-config.js configurationFile: example/renovate-config.js
token: "x-access-token:${{ steps.get_token.outputs.app_token }}" token: 'x-access-token:${{ steps.get_token.outputs.app_token }}'
``` ```

View file

@ -6,14 +6,16 @@ branding:
color: blue color: blue
inputs: inputs:
configurationFile: configurationFile:
description: 'Configuration file to configure Renovate' description: |
Configuration file to configure Renovate. Either use this input or the
'RENOVATE_CONFIG_FILE' environment variable.
required: false required: false
default: src/config.js
token: token:
description: | description: |
GitHub personal access token that Renovate should use. This should be GitHub personal access token that Renovate should use. This should be
configured using a Secret. configured using a Secret. Either use this input or the 'RENOVATE_TOKEN'
required: true environment variable.
required: false
runs: runs:
using: node12 using: node12
main: dist/index.js main: dist/index.js

View file

@ -2,7 +2,6 @@ module.exports = {
branchPrefix: 'test-renovate/', branchPrefix: 'test-renovate/',
dryRun: true, dryRun: true,
gitAuthor: 'Renovate Bot <bot@renovateapp.com>', gitAuthor: 'Renovate Bot <bot@renovateapp.com>',
logLevel: 'debug',
onboarding: false, onboarding: false,
platform: 'github', platform: 'github',
includeForks: true, includeForks: true,

View file

@ -2,7 +2,6 @@
"branchPrefix": "test-renovate/", "branchPrefix": "test-renovate/",
"dryRun": true, "dryRun": true,
"gitAuthor": "Renovate Bot <bot@renovateapp.com>", "gitAuthor": "Renovate Bot <bot@renovateapp.com>",
"logLevel": "debug",
"onboarding": false, "onboarding": false,
"platform": "github", "platform": "github",
"includeForks": true, "includeForks": true,

View file

@ -5,7 +5,7 @@ import Renovate from './renovate';
async function run(): Promise<void> { async function run(): Promise<void> {
try { try {
const input = new Input(); const input = new Input();
const renovate = new Renovate(input.configurationFile, input.token); const renovate = new Renovate(input);
await renovate.runDockerContainer(); await renovate.runDockerContainer();
} catch (error) { } catch (error) {

View file

@ -1,20 +1,98 @@
import * as core from '@actions/core'; import * as core from '@actions/core';
import path from 'path';
interface EnvironmentVariable {
key: string;
value: string;
}
class Input { class Input {
readonly configurationFile = core.getInput('configurationFile', { readonly options = {
required: true, envRegex: /^(?:RENOVATE_\w+|LOG_LEVEL)$/,
}); configurationFile: {
readonly token = core.getInput('token', { required: true }); input: 'configurationFile',
env: 'RENOVATE_CONFIG_FILE',
optional: true,
},
token: {
input: 'token',
env: 'RENOVATE_TOKEN',
optional: false,
},
} as const;
readonly token: Readonly<EnvironmentVariable>;
private readonly _environmentVariables: Map<string, string>;
private readonly _configurationFile: Readonly<EnvironmentVariable>;
constructor() { constructor() {
this.validate(); this._environmentVariables = new Map(
Object.entries(process.env).filter(([key]) =>
this.options.envRegex.test(key)
)
);
this.token = this.get(
this.options.token.input,
this.options.token.env,
this.options.token.optional
);
this._configurationFile = this.get(
this.options.configurationFile.input,
this.options.configurationFile.env,
this.options.configurationFile.optional
);
} }
validate(): void { configurationFile(): EnvironmentVariable | null {
if (this.token === '') { if (this._configurationFile.value !== '') {
throw new Error('input.token MUST NOT be empty'); return {
key: this._configurationFile.key,
value: path.resolve(this._configurationFile.value),
};
} }
return null;
}
/**
* Convert to environment variables.
*
* @note The environment variables listed below are filtered out.
* - Token, available with the `token` property.
* - Configuration file, available with the `configurationFile()` method.
*/
toEnvironmentVariables(): EnvironmentVariable[] {
return [...this._environmentVariables].map(([key, value]) => ({
key,
value,
}));
}
private get(
input: string,
env: string,
optional: boolean
): EnvironmentVariable {
const fromInput = core.getInput(input);
const fromEnv = this._environmentVariables.get(env);
if (fromInput === '' && fromEnv === undefined && !optional) {
throw new Error(
[
`'${input}' MUST be passed using its input or the '${env}'`,
'environment variable',
].join(' ')
);
}
this._environmentVariables.delete(env);
if (fromInput !== '') {
return { key: env, value: fromInput };
}
return { key: env, value: fromEnv !== undefined ? fromEnv : '' };
} }
} }
export default Input; export default Input;
export { EnvironmentVariable, Input };

View file

@ -1,20 +1,16 @@
import Docker from './docker'; import Docker from './docker';
import { Input } from './input';
import { exec } from '@actions/exec'; import { exec } from '@actions/exec';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
class Renovate { class Renovate {
private configFileEnv = 'RENOVATE_CONFIG_FILE';
private tokenEnv = 'RENOVATE_TOKEN';
private dockerGroupName = 'docker'; private dockerGroupName = 'docker';
private configFileMountDir = '/github-action'; private configFileMountDir = '/github-action';
private configFile: string;
private docker: Docker; private docker: Docker;
constructor(configFile: string, private token: string) { constructor(private input: Input) {
this.configFile = path.resolve(configFile);
this.validateArguments(); this.validateArguments();
this.docker = new Docker(); this.docker = new Docker();
@ -22,18 +18,30 @@ class Renovate {
async runDockerContainer(): Promise<void> { async runDockerContainer(): Promise<void> {
const renovateDockerUser = 'ubuntu'; const renovateDockerUser = 'ubuntu';
const githubActionsDockerGroupId = this.getDockerGroupId();
const commandArguments = [ const dockerArguments = this.input
.toEnvironmentVariables()
.map((e) => `--env ${e.key}`)
.concat([`--env ${this.input.token.key}=${this.input.token.value}`]);
if (this.input.configurationFile() !== null) {
const baseName = path.basename(this.input.configurationFile().value);
const mountPath = path.join(this.configFileMountDir, baseName);
dockerArguments.push(
`--env ${this.input.configurationFile().key}=${mountPath}`,
`--volume ${this.input.configurationFile().value}:${mountPath}`
);
}
dockerArguments.push(
'--volume /var/run/docker.sock:/var/run/docker.sock',
'--volume /tmp:/tmp',
`--user ${renovateDockerUser}:${this.getDockerGroupId()}`,
'--rm', '--rm',
`--env ${this.configFileEnv}=${this.configFileMountPath()}`, this.docker.image()
`--env ${this.tokenEnv}=${this.token}`, );
`--volume ${this.configFile}:${this.configFileMountPath()}`,
`--volume /var/run/docker.sock:/var/run/docker.sock`, const command = `docker run ${dockerArguments.join(' ')}`;
`--volume /tmp:/tmp`,
`--user ${renovateDockerUser}:${githubActionsDockerGroupId}`,
this.docker.image(),
];
const command = `docker run ${commandArguments.join(' ')}`;
const code = await exec(command); const code = await exec(command);
if (code !== 0) { if (code !== 0) {
@ -71,20 +79,21 @@ class Renovate {
} }
private validateArguments(): void { private validateArguments(): void {
if (!fs.existsSync(this.configFile)) { if (/\s/.test(this.input.token.value)) {
throw new Error('Token MUST NOT contain whitespace');
}
const configurationFile = this.input.configurationFile();
if (
configurationFile !== null &&
(!fs.existsSync(configurationFile.value) ||
!fs.statSync(configurationFile.value).isFile())
) {
throw new Error( throw new Error(
`Could not locate configuration file '${this.configFile}'.` `configuration file '${configurationFile.value}' MUST be an existing file`
); );
} }
} }
private configFileName(): string {
return path.basename(this.configFile);
}
private configFileMountPath(): string {
return path.join(this.configFileMountDir, this.configFileName());
}
} }
export default Renovate; export default Renovate;