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
- AWS account [Free Tier]
- GitHub account
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.
Create GitHub Repository make it Public
Creating your first workflow
Create a .github/workflows directory in your repository on GitHub if this directory does not already exist.
In the .github/workflows directory, create a file named shutdown.yml. For more information, see "Creating new files."
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 }}
Create AWS Keys
- 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
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