Creating a AWS EC2 using Github Actions and Terraform Cloud

Creating a AWS EC2 using Github Actions and Terraform Cloud

Steps I went though to create a AWS EC2 server using IaC GitHub actions and Terraform Cloud

Asrin Dayananda
·Apr 21, 2022·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

These are steps on how I created an AWS EC2 using Github Actions and Terraform.

Create a Terraform Cloud account

Create Terraform Cloud token

Create a new GitHub repo

Pull repo down locally to modify code

Add Terraform files

  • Copy this file to your repo main.tf

Add GitHub Action file

Change main.tf

  • Configure these lines to suit what you have created in terraform cloud
  • Change ADD_TERRAFORM_ORGANISATION_NAME & ADD_TERRAFORM_WORKSPACE_NAME
  cloud {
    organization = "ADD_TERRAFORM_ORGANISATION_NAME"

    workspaces {
      name = "ADD_TERRAFORM_WORKSPACE_NAME"
    }
  }
}
  • Change this line to where you want your EC2 to be created (us-west-2)
    provider "aws" {
    region = "us-west-2"
    }
    

Create a branch and push changes up

git branch NewEC2
git checkout NewEC2
git push NewEC2

Create a in GitHub PR to merge into main

  • Create PR in GitHub Repo
  • GitHub Action Check will kick off and check if everything is ok
  • If you get errors like
    Error: No valid credential sources found for AWS Provider.
    
  • Double check your organization and workspace in terraform or Terraform API key we added into secrets in github
  • If checks succeed you are ready to create your EC2 from Terraform code
  • Merge pull request into main
  • Wait for GitHub action to run image.png

Check if EC2 got provisioned

  • Go to your Github Action in your repo and click under Terraform Apply step you should have a url to check server image.png
  • Copy it and go to the site and check it should respond to hello world.
  • You also could login to your AWS account and find the server

Congrats you have created a server with GitHub Actions and Terraform 🎉

Now delete resources

  • Open your Terraform Cloud
  • Find your workspace
  • Click settings
  • Queue destroy plan image.png
  • You will see triggers running to destroy it
  • You have to confirm you want to accept deleting
  • Check your url before is broken
  • Check your EC2 server is removed in the AWS portal or via AWS CLI command

Credits

Shameless Plugs

Feel free to comment with questions or feedback✌️

Happy coding,

Az 👨🏾‍💻

Did you find this article valuable?

Support Asrin Dayananda by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this