DEV Community

Cover image for Turnoff AWS EC2 instance using GitHub Actions
Rishav Mehra
Rishav Mehra

Posted on

Turnoff AWS EC2 instance using GitHub Actions

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

Prerequisites

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
on:
  push:
  # branches: [ main ]
  workflow_dispatch:
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Stop AWS EC2
        run: |
          aws ec2 stop-instances --instance-ids ${{secrets.AWS_EC2_INSTANCE_ID }}
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }}
Enter fullscreen mode Exit fullscreen mode

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_SECRET_ACCESS_KEY= xxxxxxxxxxxx
AWS_REGION = us-east-1
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)