LoginSignup
5
1

More than 1 year has passed since last update.

GitHub ActionsでPersonal Access Tokenを使って他のリポジトリにpushする

Last updated at Posted at 2022-07-14

はじめに

全力で首を縦に振るのですが、その前にGithub Actions自体のテストや、
単純な最小構成でとりあえず他リポジトリにpushしたいと思った時に、
何故かPersonal Access Tokenでのやり方が全然見つからなかったのでこの記事を書きました。
英語はちゃんと読んでいません。

筆者のスキルレベル

Github Actions触り始めて3日。
Githubは半年くらい弄ったけどよく知らない。
Gitコマンドは3年くらい触ってる。

色々と勘違いしている可能性があります。
よろしくお願いします。

Github Actionsで他のパブリックリポジトリ操作(失敗まで)

Github Actionsを動かすリポジトリ「testrep」から、別のリポジトリ「pulltestrep」を操作したい。

clone

ここではactions/checkout@v2を利用します。

wftest.yaml
      - name: Checkout other repo
        uses: actions/checkout@v2
        with:
          repository: ridia/pulltestrep
          path: pulltestrep

commit, push

そのままgitコマンドでコミットユーザを指定し、コミットします。

wftest.yaml
      - name: pull test result
        run: |
          touch newfile.txt
          git config --local user.email "ridia@eario.jp"
          git config --local user.name "ridia"
          git add .
          git commit -m "auto commit test"
          git push

Github Actionsの実行結果でエラーが出る

怒られた。403なので権限がないらしい。つまり権限があればpushできる。

[main e17a5bf] auto commit test
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 newfile.txt
remote: Permission to ridia/pulltestrep.git denied to github-actions[bot].
fatal: unable to access 'https://github.com/ridia/pulltestrep/': The requested URL returned error: 403
Error: Process completed with exit code 128.

Personal Access Tokenで権限を付ける

今回はタイトル通り、Personal Access Tokenを利用します。

発行

ここで Generate new tokenして作ります。
https://github.com/settings/tokens
Settings -> Developer Settings -> Personal access tokens

Noteはトークンの名前、Expirationは有効期限です。
無期限も指定できますが強く推奨されないのでやめておいた方がいいでしょう。

Select scopesは、リポジトリ操作を行うのでrepoにチェックを入れておきます。
※細かい権限設定はきちんと理解していません

登録

作ったトークンはリポジトリに登録します。
登録するのはGithub Actionsを動かすリポジトリ、つまり「testrep」です。
testrepのSettings、Secrets、Actionsと辿ってNew Repository Secretsから登録します。
image.png
image.png
↑画像のValueは適当

トークンの利用

どこで登録したトークンを利用するかというと、Github Actionsで利用します。
簡単なのはactions/checkout@v2の利用時に指定します。

wftest.yaml
      - name: Checkout other repo
        uses: actions/checkout@v2
        with:
          repository: ridia/pulltestrep
          token: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
          path: pulltestrep

パブリックリポジトリへのpushは以上です。

Github Actionsで他のプライベートリポジトリ操作

プライベートだと何が違うのかと言うと、適切な権限を持つPersonal Access Tokenを
利用するのであれば何も変わりません。
ただ、Personal Access Tokenを登録する前に出るエラーが変わります。
プライベートリポジトリなので、アクセストークンがなければリポジトリが見つからず、
Not Foundエラーが出ます。

最後に

これはあくまでPersonal Access Tokenを利用した場合のHow toですので、
初めに書いた通り、Github Appsを利用した方がセキュアであると思われます。
私はこれから試す予定です。

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1