Pushing to GitHub repo from Travis CI [WIP]

A guide to pushing changes to a GitHub repo from TravisCI

Posted by Aman Abhishek Tiwari on April 09, 2019 · 3 mins read Categories: | Tech |

Sometimes we may need to make some changes in a repository and push it to the GitHub repository from TravisCI. An example would be to use TravisCI to deploy a Jekyll website to github for which we can build the website in TravisCI and push the _site data in the GitHub branch.
The issue comes when we try to push the changes in the git repository, which requires authorisation, which can't be entered manually in TravisCI.
We can solve this issue with something called GitHub's Personal Access Tokens. Generate a Pesonal Access Token by following this article by GitHub.
While generating the token, we need to give access to the github repository. For this, check the options shown in the image below (in black border) on the Token generator page. This will allow the service with this token to make changes to a repository in GitHub.
GitHub Token Generator

Now we need to tell TravisCI about the token. But this GitHub token has to be encrypted before we give it to TravisCI. To do this first install travis in your local linux machine and login to travis by using these commands:

  
      sudo gem install travis
      travis login
  
After this, add these lines in the after_script part of your .travis.yml file.
  
 after_script:
   - git config credential.helper "store --file=.git/credentials"
   - echo "https://${GH_TOKEN}:@github.com" > .git/credentials
   - node ./node_modules/grunt-cli/bin/grunt release
  
Now, while staying in the directory where .travis.yml is, run,
  
    travis encrypt 'GITHUB_TOKEN=<REPLACE-WITH-YOUR-GITHUB-PERSONAL-ACCESS-TOKEN>' --add
  
This will add the encrypted Personal Access Token in your .travis.yml file.
When TravisCI builds on your repo, it stores this token in the global variable GITHUB_TOKEN, which you can use to push to a particular github repository via a command which looks something like this
  
    git push -f -q https://${GITHUB_TOKEN}@github.com/<GITHUB-USERNAME>/<GITHUB-REPO-NAME>.git <DEPLOY_BRANCH>
  
Note however that the command git push can only be used after the variable GITHUB_TOKEN has been initialised, which only happens after the commands shown in after_script section of the .travis.yml has been executed. So, any script using git push should be put after those three commands in after_script.