Categories
Automation

GitHub Actions Tutorial Part-3: Code Push

In this section, we will see how to push code with GitHub actions.

We will create a file named example.txt and add some content in it and push it to a new branch that you provide in the workflow.

action-demo/.github/workflows/code_push.yml

on:
  push:
    branches:
      - master

name: Create and push file
jobs:
  create-and-push-file:
    name: Create and push file
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@master
    - name: Create and push file
      uses: './'
      env:
        USER_NAME: example
        USER_EMAIL: example@nouser.(none)
        BRANCH_NAME: code-push-example
        COMMIT_MESSAGE: "Action add file"

Here USER_NAME and USER_EMAIL will be the actor who will push the code in the new branch.

action-demo/entrypoint.sh

#!/bin/bash

# Install git
# Ubuntu container by default do not have git installed.
apt update && apt install git -y

# Add git config
git config --global user.name "$USER_NAME"
git config --global user.email "$USER_EMAIL"

cd $GITHUB_WORKSPACE

# Create example.txt  
touch "example.txt"

# Put some content in example.txt
echo "You are doing awesome !" > example.txt

# Checkout branch name based on Variable provided in workflow
git checkout -b $BRANCH_NAME

# Stage files and changes
git add .

# Commit message
git commit -m "$COMMIT_MESSAGE"

# Push the code
git push origin $BRANCH_NAME

Push the code and when the action completes you will see the results.

File created with GitHub action
Open file created by GitHub action

You can save more time in the action by creating a custom Docker Image for the action. By applying this you will reduce a step where docker image will be built by action. Don’t worry if you did not understand this, you will learn this by creating more and more time-consuming processes.

If you want to know more about GitHub actions and other GitHub tools checkout GitHub lab at https://lab.github.com/

Leave a Reply

Your email address will not be published. Required fields are marked *