Showing posts with label Continuous Delivery. Show all posts
Showing posts with label Continuous Delivery. Show all posts

Monday, May 11, 2020

CI/CD pipelines with ASP.NET MVC 3.1, GitHub Actions and Docker Hub

Overview

In this post I will show you how easy it is to implement a CI/CD DevOps pipeline using GitHub Actions. The sample web application I will use is an ASP.NET Core 3.1 MVC application and I will deploy it to Docker Hub. 
Before proceeding, It is assumed that you have the following pre-requisites: 
  • You already have a Docker Hub account
  • You already have a GitHub account
  • You have .NET Core 3.1 (or later) installed on your computer

Creating a simple ASP.NET Core 3.1 application

In a working directory, execute the following command from within a terminal window:

dotnet new mvc -o GithubActions2DockerHub

Change directory to the newly created app:

cd GithubActions2DockerHub

Add a .gitignore file to the application:

dotnet new gitignore

Let us make the application our own by, perhaps, changing the title of the app and the background color.

1) Add the following CSS to wwwroot/css/site.css:
body {
   background-color: tomato;
}

2) In Views/Home/Index.cshtml, change the main heading from:

<h1 class="display-4">Welcome</h1>

TO

<h1 class="display-4">Welcome to our MVC Core 3.1 App</h1>

Let us now run the application and see what it looks like. In the terminal window run the following command:

dotnet run

Point your browser to https://localhost:5001. You will see a strangely colored web page that looks like this:



Stop the server by hitting CTRL + C in the terminal window.

Dockerfile

In the root folder of your project, add a file named Dockerfile (no extension) with the following content:
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "GithubActions2DockerHub.dll"]

Push your code to GitHub.

We are now ready to push this application to GitGub. Go to GitHub and create a repository. I created a repository named GithubActions2DockerHub. Copy the commands that are shown on the GitHub page, under “…or push an existing repository from the command line”, that looks like this:


Back in your application’s terminal window, type the following commands to initialize a git repo, add files to the repo and commit your changes:

git init
git add .
git commit -m "1st commit"

Next, we will push the code to GitHub. Paste the git commands that you copied from GitHub. This is what it looked like for me:

git remote add origin https://github.com/medhatelmasry/GithubActions2DockerHub.gitgit push -u origin master

If you refresh the GitHub page, you will see that your code is in GitHub. It looks like this:

Click on Secrets on the left-side:

Build & Deploy using GitHub Actions

 Back it GitHub, click on the Settings tab of your application’s repo:
 
Click on Secrets on the left-side:
Click on “Add a new secret”:
 You will enter your Docker Hub username and password as GitHub secrets. Enter secrets DOCKER_USERNAME & DOCKER_PASSWORD together with their respectivev values:
    
Click on Actions on the top navigation bar in GitHub:
You will see a multitude of templates for a multitude of technologies and programming languages. Scroll down to the “Continuous integration workflows” and select “Docker image”.
This will create a .github/Workflows folder in your application. Name the file deploy_to_docker_hub.yml. 
Your deploy_to_docker_hub.yml looks like this:
name: Docker Image CI

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

  jobs:

    build:

      runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - name: Build the Docker image
        run: docker build . --file Dockerfile --tag my-image-name:$(date +%s)

Unfortunately, the above instructions only build the docker file but do not deploy to docker hub. We will replace the instructions (under steps:) with instructions that checkout, build and deploy.

Therefore delete the following lines at the bottom of the deploy_to_docker_hub.yml file:

- name: Build the Docker image
run: docker build . --file Dockerfile --tag my-image-name:$(date +%s)

Replace the above code with the following:

- uses: docker/build-push-action@v1
  with:
    username: ${{ secrets.DOCKER_USERNAME }}
    password: ${{ secrets.DOCKER_PASSWORD }}
    repository: melmasry/aspnetmvc
    tags: v1

The image will be named melmasry/aspnetmvc and the tag (version) will be v1.
Make sure tab the instructions in deploy_to_docker_hub.yml so that it is indented as shown below:

name: Docker Image CI

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:

  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - uses: docker/build-push-action@v1
      with:
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_PASSWORD }}
        repository: melmasry/aspnetmvc
        tags: latest

NOTE: replace melmasry with your Docker Hub username.

Click on the green “Start commit” button:
Enter a comment and description for the commit then click on the “Commit new file” button:
 Click on “Actions” >> “All Workflows” >> your workflow.  
Then click on build:
The build and deploy should be succcessfully completed. The real test comes with pulling the image from DockerHub and running it locally on your computer. Run the following command from a terminal window on your computer:

docker run -d -p 8888:80 melmasry/aspnetmvc:latest

NOTE: replace melmasry with your Docker Hub username.
Point your browser to http://localhost:8888. You will see the same ugly tomato colored web page:
 
Happy coding!!

Wednesday, March 25, 2020

Implementing CI/CD DevOps pipelines using a simple ASP.NET Core 3.1 MVC application with GitHub Actions and Azure App Services


In this post I will show you how easy it is to implement a CI/CD DevOps pipeline using GitHb Actions. The sample web application I will use is an ASP.NET Core 3.1 MVC application and I will deploy it to Azure App Services. 

Before proceeding, It is assumed that you have the following pre-requisites:
- You already have an Azure Account
- You already have a GitHub account
- You have .NET Core 3.1 (or later) installed on your computer
Creating a simple ASP.NET Core 3.1 application
In a working directory, execute the following command from within a terminal window:

dotnet new mvc -o GithubActions2Azure

Change directory to the newly created app:

cd GithubActions2Azure

Add a .gitignore file to the application:

dotnet new gitignore

Let us make the application our own by, perhaps, changing the title of the app and the background color.

1) Add the following CSS to wwwroot/css/site.css


body {   background-color: tomato;}


2) In Views/Home/Index.cshtml, change the main heading from:

<h1 class="display-4">Welcome</h1>

           TO

<h1 class="display-4">Welcome to our MVC Core 3.1 App</h1>

Let us now run the application and see what it looks like. In the terminal window run the following command:

dotnet run

Point your browser to https://localhost:5001. You will see a strangely colored web page that looks like this:


Stop the server by hitting CTRL + C in the terminal window.

Push code to GitHub

We are now ready to push this application to GitGub. Go to GitHub and create a repository. I created a repository named GithubActions2Azure. Copy the commands that are shown on the GitHub page that looks like this:

Back in your application’s terminal window, type the following commands to initialize a git repo, add files to the repo and commit the changes:

git init
git add .
git commit -m "1st commit"

Next, we will push the code to GitHub. Paste the git commands that you copied from GitHub. This is what it looked like for me:

git remote add origin https://github.com/medhatelmasry/GithubActions2Azure.git
git push -u origin master

If you refresh the GitHub page, you will see that the code is in GitHub. It looks like this:

























Azure

The next step is to create a web app in Azure. Login to the Azure portal at https://portal.azure.com/. Click on Create a resource:

Enter “web" in the filter then choose "Web App”:


On the next page, click on the blue Create button:

 

Choose a subscription then create a new Resource Group:


In named my new resource group GithubActions2Azure. Here are all the choices I made:


Click on Create on the next page:


Creation of a new Azure web service takes less than three minutes. When it is completed, a message appears declaring that “Your deployment is complete”. Click on the blue “Go to resource” button:


We need the publish profile. Click on “Get publish profile” to download your publish profile XML file:


Build & Deploy using GitHub Actions
 Back it GitHub, click on the Settings tab of your application’s repo:


Click on Secrets on the left-side:


Click on “Add a new secret”:


Give the secret the name AZURE_WEBAPP_PUBLISH_PROFILE and paste the contents of the publish profile file that you earlier downloaded from the Azure portal for your web app:

 
Click on Actions on the top navigation bar in GitHub:


You will see a multitude of templates for a multitude of technologies and programming languages. We will paste our own template, therefore, click on the “Set up a workflow yourself” link on the right-side:


This will create a .github/Workflows folder in your application. Name the file deploy_to_azure.yml then click on the green “Start commit” button:


Enter a comment and description for the commit then click on the “Commit new file” button:


Go to this site to get an appropriate template for our web app: https://github.com/Azure/webapps-deploy. Scroll down until you find this section then click on dotnet.yml:


Copy the contents of the asp.net-core-webapp-on-azure.yml. Return to the GitHub repo of our application, edit the deploy_to_azure.yml file, and replace the contents by pasting the clipboard. This is what it looks like for me:


On line 18, set the value of AZURE_WEBAPP_NAME to the name of your app. In my case it is GithubActions2Azure.

On line 20, set the value of DOTNET_VERSION with the exact version of .NET Core with which you created your app. You can find out by running the following command in a terminal window:

dotnet --version

In my case, the .NET Core version is 3.1.200.

Click on the green “Start commit” button, give it a title then click on “Commit changes”.

Click on Actions on the top navigation bar:


Click on “Deploy ASP.NET Are all to ..”. If all goes well, there should be a green check mark beside the workflow, which was responsible for building and deploying the app to Azure. Click on “Updated deploy_to_azure.yml”.


Click on “build-and-deploy” on the left-side:


You will be comforted by the fact that all tasks completed successfully:


To make sure all is well, go to the Azure portal and click on the URL of your website:


Our ugly looking tomato-colored website appears:


Note that if you make any changes to your source code and push it to GitHub, it will automatically get deployed to Azure. This is what CI/CD is all about. Let's try that.

CI/CD
In a terminal window at your project folder, do a pull in order to get all the changes we made in GitHub when we added the .yml file:

git pull

In wwwroot/css/site.css, change the background-color to wheat. Let us push our changes to Github with these commands:

git add .
git commit -m "changed background color to wheat"
git push origin master

Back in GitHub, you will find that the deployment is running:


Upon completion it will display a green check mark:

Refresh the website in your browser and you will find that it has changed background color to something nicer:


Thanks for coming this far in my tutorial and I hope you found it useful.

Saturday, January 19, 2019

Continuous Integration and deployment of Angular App with Azure DevOps


Background

This document describes processes and best practices for an end-to-end continuous integration and deployment of an Angular Application.
Assumptions:
  •     Node.js, npm and angular-cli are installed on dev computer
  •      Angular is installed on your computer: npm install -g @angular/cli
  •      GIT is installed on the dev computer
  •      Developer has access to an account on Azure DevOps at http://dev.azure.com.
  •      Developer has an account on Azure (http://portal.azure.com)

Note: It is best if both your DevOps & Azure accounts use the same Microsoft account credentials.

Creating a simple Angular CLI app on dev computer:

Create an angular app using angular-cli:
ng new ngware
cd ngware
ng serve
Point your browser to http://localhost:4200 and you should see the following:

Web.config file

For Angular’s routing to work smoothly on Azure, it is necessary to have a web.config file. Therefore, stop the server and create a web.config file in the src directory and add to it the following markup:
<?xml version="1.0"?>
<configuration>
   <system.webServer>
      <rewrite>
         <rules>
         <rule name="Angular Routes" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
               <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
               <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
               <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
         </rule>
         </rules>
      </rewrite>
   </system.webServer>
</configuration>
To enable the web.config file to be packaged with production code, edit the angular.json file and add ‘web.config’ to assets, as follows:
. . . . .
"assets": [
  "src/assets",
  "src/favicon.ico",
  "src/web.config"
],
. . . . .

Build app

Build the app using the following command:
ng build --prod
This produces the production version of the application in the dist/ngware folder. To test the trans-piled version of the app, start the server then point your browser to http://localhost:4200/dist/ngware. You should see the same app as before, this time it is being served from production code.

Azure DevOps

Azure-DevOps is Microsoft’s DevOps platform. Login into Azure-DevOps and create a new project. In my case I created a new project named ngware.

Once the project is created in Azure-DevOps, it is time for us to push our code using Git. Copy the address of the Git repo so that we can use it to sync our code. Click on Repos on the left-side then note the Git commands.
Back at your computer, stop the server and run the following commands from your command prompt to push the code into your projects Azure-DevOps git repository:
git init
git add .
git commit -m "first commit"
git remote add origin {your-git-url-here}
git push -u origin master
You may be asked to login into Azure-DevOps.
Once your code has uploaded to Azure-DevOps, Click on Repos on the left-side in Azure-DevOps to verify that your code has indeed uploaded to Azure-DevOps:
The code will look like this:

Building the code in Azure-DevOps

The same steps that we carried out to build our app in the development computer will be translated into tasks in Azure-DevOps. To build our app, choose: Pipelines >> Builds on the left side:
Click on the blue “New pipeline” button:

On the “Select a source” dialog, accept the defaults and click on the Continue button at the bottom:

On the “Select a template” dialog, scroll to the very bottom and click on “Empty pipeline” then click on the blue Apply button.

Give the build a proper name (like: Build Angular App) then select “Hosted” under Agent pool:


Next, click the “+” to add a task:

In the filter, enter npm. Highlight the npm task then click on Add. Add the following five tasks:
Node Tool Installer
npm
npm
Archive Files
Publish Build Artifacts
This is what the series of tasks will look like:

Customize each task as follows:

1) Use Node 6.x

Display name
Use Node 10.x
Version Spec
10.x

2) npm install

This task runs the command “npm install” to install node packages. You do not need to make any changes to this task as it does exactly what we want it to do.

3) npm install

This task will run “npm run build” command, which is essentially a script in our package.json file:
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
Configure the npm  task like this:
Display name
Build angular app
Command
custom
Command and arguments
Run build --prod

4) Archive $(Build.BinariesDirectory)

This task is responsible for creating a zip file containing all the files, created by the previous task, that reside in the dist/ngware directory.
Display name
Archive production files
Root folder or file to archive
dist/ngware
Prepend root folder name to archive paths
Uncheck

Note: Copy the value of the ‘Archive file to create’ into the clipboard because we will be using it in the next task.
5) Publish Artifact: drop
Next, we will publish the zip we created in the last step.
Path to publish
$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
Paste this from the value you copied into the clipboard in the previous task.

That’s it for all our steps. Let’s run the build! Click on Save & Queue >> Save & Queue in the top menu.

On the next dialog, click on “Save & Queue”

Click on the build number link in the in the top left-side corner.

This will allow you to see progress of the build. When the build is completed without any errors, you will see a green “Build Succeeded” messages as shown below:

Artifacts

You can see the package that was created by selecting the blue Artifacts button on the top-right.

Download the drop folder to see what was created inside that directory.  Click on the three dots beside drop to download the zip file.

The drop.zip file contains another numbered zip file that has the production files.

Continuous Integration

We will need to setup continuous integration so that whenever new code is committed, the build process is automatically kicked off. In the navigation at the top of the page, click on the build as shown:

Click “Edit” beside the bluer Queue button:

On the next page, click on “Triggers”:

Enable continuous integration by enabling the switch:

Click: Save & Queue >> Save:

On the next dialog, add a comment then click Save:

Creating Release

Log into Azure and create a web app.

Back in Azure-DevOps, create a release definition by clicking on Pipelines >> Releases on the left side. Click on the blue “New pipeline” button in the middle of the page.

In the sliding “Select a template” dialog on the right-side, select “Azure App Service deployment” and click on the blue Apply button.

Click on the X in the corner of the right-side dialog to close it.

Select the first “Add an artifact” box.

On the right-side dialog, select the build we just created for “Source (build pipeline)”. Accept all other default values. Then click on the Add button.

In order to enable continuous deployment, click on the thunderbolt icon in the top-right corner of the first box.

A dialog opens on the right side. Enable the “Continuous deployment trigger”.

Click on the second box’s “1 job 1 task” link.

Select your Azure subscription then click on the blue Authorize button.

NOTE: You may need to enable popup windows for azure.com in your browser.
Once you are authorized with azure.com, select App type to be Web App. Under App service name, choose the web app that you created earlier on the Azure portal. The final state of the dialog would look similar top the following:

Click Save at the top:

You can enter a comment in the following dialog then click on OK.

When the “+ Release” link at the top lights up, click on Release >> Create a release.

Choose the stage and build version on the next dialog then click on Create.


The release process is about to start. Click on the release link on the top side.

When you click on the second box, you will see a Deploy button. Click on the Deploy button to start the deployment.

Click on the Deploy button again when you experience the following dialog.

Wait until you see an “In progress” message in that box. Click on it when it appears to see progress of the deployment. If all goes well, all tasks will show succeeded in green.

What is left is for us to prove that the application has indeed deployed to azure. In my case, I pointed my browser to http://ngware.azurewebsites.net and hit the following website.


Make a change to your source code, like change the background color, and push your code to the Git repo on Azure-DevOps. The build and release processes will be automatically triggered and you should find your changes deployed in less than five minutes.