Allan Xu
Allan Xu

Reputation: 9368

How can a Github workflow read a file on another private repository hosted on the same GitHub account?

I have a private git repository like:

Github.com/acct/repo1

I have a test.json file in another private repository in the same GitHub subscription and account like:

Github.com/acct/repo2/test.json

How can a workflow in repo1 have http get access to the url Github.com/acct/repo2/test.json?

All I need is a simple way to read the content of test.json in a workflow running on repo2.

It works the best for me to read the file using a curl get request.

Upvotes: 0

Views: 2418

Answers (1)

xom9ikk
xom9ikk

Reputation: 2299

First of all, you need to get an access token from GitHub. This is described here.

And add it to the secrets for the repository in which the Github Action will run. In your case, this is repo1. Read more about setting secrets.

After that, you can execute the request using curl. To do this, run the following command:

  curl -H 'Authorization: token ${{ secrets.GITHUB_TOKEN }}' \
  -H 'Accept: application/vnd.github.v4.raw' \
  -L https://api.github.com/repos/OWNER_HERE/REPO_NAME_HERE/contents/FOLDER_OR_FILE_HERE

After execution, the contents of the file will be displayed on the console.

If the contents of the file need to be saved to a variable, then use the following syntax:

  VARIABLE_NAME="$(curl -H 'Authorization: token ${{ secrets.GITHUB_TOKEN }}' \
  -H 'Accept: application/vnd.github.v4.raw' \
  -L https://api.github.com/repos/OWNER_HERE/REPO_NAME_HERE/contents/FOLDER_OR_FILE_HERE)"

Add the -O flag to save the content to a file

  curl -H 'Authorization: token ${{ secrets.GITHUB_TOKEN }}' \
  -H 'Accept: application/vnd.github.v4.raw' \
  -O \
  -L https://api.github.com/repos/OWNER_HERE/REPO_NAME_HERE/contents/FOLDER_OR_FILE_HERE

In your case, the step in the .yml file to get the content would look like this:

#...
-name: Get file test.json
 run: |
   curl -H 'Authorization: token ${{ secrets.GITHUB_TOKEN }}' \
   -H 'Accept: application/vnd.github.v4.raw' \
   -O \
   -L https://api.github.com/repos/acct/repo2/contents/test.json
#...

Please note that the path /contents/ must remain after REPO_NAME_HERE in the request, and after that you can specify the path to the FOLDER_OR_FILE_HERE file.

Upvotes: 4

Related Questions