Rishav Mehra
Rishav Mehra's Blog


Rishav Mehra's Blog

Turnoff AWS EC2 instance using GitHub Actions

Turnoff AWS EC2 instance using GitHub Actions

Rishav Mehra's photo
Rishav Mehra
·Jun 13, 2022·

2 min read

CI/CD GitHub Actions workflow to turn off an Amazon Web Services EC2 instance.

What is GitHub actions? GitHub Actions are an automated process that allows us to build, test, release and deploy any code project on GitHub, but we can also use it to automate any step of our workflow such as merging pull requests, assigning levels, triaging issues etc. In short: GitHub Actions are a custom software development workflow automation tool


Go to AWS Account and Launch an EC2 instance, t2.micro is enough. Now, Click on Review and launch. You need nothing like Security Group for this. Proceed without a key pair.

Image description

Image description

Create GitHub Repository make it Public Image description

Creating your first workflow

  1. Create a .github/workflows directory in your repository on GitHub if this directory does not already exist.

  2. In the .github/workflows directory, create a file named shutdown.yml. For more information, see "Creating new files."

  3. Copy the following YAML contents into the shutdown.yml file:

name: shutdown
  # branches: [ main ]
    runs-on: ubuntu-latest
      - name: Stop AWS EC2
        run: |
          aws ec2 stop-instances --instance-ids ${{secrets.AWS_EC2_INSTANCE_ID }}
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }}

Create AWS Keys

Image description

  • Click on Security credentials
  • then, click on Create access key Download Security credentials

Now, Add this Security credentials in GitHub Secrets [Actions]. Create new repository secret now add this secret like this

AWS_EC2_INSTANCE_ID = i-xxxxxxxx
AWS_ACCESS_KEY_ID = xxxxxxxxxxxxxx
AWS_REGION = us-east-1

Image description For AWS_Region add your running ec2 instance regions for me [us-east-1]

Now, final stage. Go to Actions tab GitHub Repo and select your workflow under your workflow Run workflow

Image description

Socials Website Twitter GitHub LinkedIn

Share this