CyberShark
CyberShark

Reputation: 440

How to replace a API key with a Secret in code during Github Actions Job?

I usually hide my API key in an XML file and use .gitignore along with getString() to retrieve my API key.

I'm trying to use Github Actions to automate Gradle build and Release of debug apk's. Due to the XML file not being uploaded to the repo, it obviously fails.

Is there any way to store my key in Github Secrets and then replace the code with the secret?

Current code: headers["token"]= getString(R.string.token)
Replaced code in Github actions server : headers["token"]="MY_API_KEY_FROM_SECRETS"

Here's my YAML file that I was using:

name: Gradle build test and release
on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: set up JDK 1.8
      uses: actions/setup-java@v1
      with:
        java-version: 1.8
   #I'd like to replace the api key here in code from secrets
    - name: Make Gradle executable
      run: chmod +x ./gradlew
    - name: Build with Gradle
      run: ./gradlew build
    - name: Build Debug APK
      run: ./gradlew assembleDebug
    - name: Releasing using Hub
      uses: ShaunLWM/action-release-debugapk@master
      env:
       GITHUB_TOKEN: ${{ secrets.TOKEN }}
       APP_FOLDER: app
       RELEASE_TITLE: New Build
       BODY: github.event.head_commit.message
       prerelease: true

Upvotes: 3

Views: 4203

Answers (1)

bk2204
bk2204

Reputation: 76994

Sure, this is possible. You haven't said what file you'd like modified, but this should be easy enough to do with a one-liner (replacing FILENAME with your config file name):

- run: perl -pi -e 's/getString\(R\.string\.token\)/"$ENV{TOKEN}"/' FILENAME
  env:
    TOKEN: ${{ secrets.TOKEN }}

If you prefer Ruby or some other scripting language, you can use that instead. You could also use sed, but I prefer this approach because it means that the value is never available in ps output (even if this is a locked down VM).

Upvotes: 4

Related Questions