GitHub Actions with .NET, Part 5 - Build a .NET Application and Upload to S3

Full source code available here.

The Basics

You need a GitHub account, and an AWS account. AWS offers a free tier where you can experiment at no cost. Martin Beeby of AWS, and I chatted about this in a podcast.

GitHub Secrets

The GitHub Action workflow needs a few secrets. In your repository, go to Settings, then Secrets. Add the below secrets.

Strictly speaking, the region and the bucket name might not be real secrets, but it’s an easy way to pass them to the workflow.

The Code

This application is as simple as it gets - the goal is to build a binary, zip it, and upload to S3.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
using System;

namespace GitHubActions_Upload_to_S3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

The Workflow

To run GitHub Actions, a workflow file is needed. Add a .github/workflows directory.

Add the below code and name it with a .yaml extension. This will build the application, zip the contents of the release directory, and upload the zip to S3.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
name: Build and Upload to S3

on:
  push:
    branches: [ main ]

jobs:
  build:
    name: Build the app
    runs-on: ubuntu-latest

    steps:
    - name: Checkout source code
      uses: actions/checkout@v2

    - name: Setup .NET
      uses: actions/setup-dotnet@v1
      with:
        dotnet-version: 5.0.x

    - name: Restore dependencies
      run: dotnet restore

    - name: Build
      run: dotnet build -c release --no-restore

    - name: Install zip
      uses: montudor/action-zip@v1

    - name: Zip output
      run: zip -qq -r helloworld.zip bin/release/net5.0

    # Not needed, but very handy when trying to figure out what the action is doing
    #- name: Local file stuff
    #  run: pwd; ls -al; find .
    
    - name: Upload to S3 
      uses: jakejarvis/s3-sync-action@master
      with:
        args: --acl public-read --follow-symlinks --exclude '*' --include 'helloworld.zip' 
      env:
        AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }}
        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        AWS_REGION: ${{ secrets.AWS_REGION }}

When this code is pushed to GitHub, the Action will start. You should see output that looks like this.

And in AWS, here is the bucket, with the file that was uploaded from GitHub Actions.

Full source code available here.

comments powered by Disqus

Related