Saturday, September 2, 2017

VSTS Deployments Notes

1) Publish file is used in case of in case of two scenarios


  • Build time: Each respective publish files for different environments (Ex: O - Dev publish file, T - Test publish file)
  • Run time: Single publish file and tokenization for different.


2) We can do post deployment script after dacpac deployment and also use SQLCMD variables in SQL project which again can be tokenized for different environments with a single publish file

or

We can create different publish files based on the environment with different SQLCMD variables

3)Windows application installation are two types


  1. MSI : We can generate MSI in different ways
    • Wix opensource installer microsoft
    • Install shield
    • Legacy VDproject in visual studio
    • Thirdy part framework
  2. Click once : Website kind of deployment where there is package which is deployed at central location


4)For running any azure commands we can use any azure powershell command in VSTS

Wednesday, June 21, 2017

Azure CLI Commands to create windows Kubernetes cluster and run windows container using json file


Refer the previous two blogs for details of the Kubernetes and the commands mentioned here



1.    az group create --name=myKubernetesWindowsResourceGroup --location="Southeast Asia"

2.    az acs create --orchestrator-type=kubernetes --resource-group myKubernetesWindowsResourceGroup --name=myKubernetesClusterName --dns-prefix=mydnsPrefix --agent-count=2 --generate-ssh-keys --windows --admin-username girish --admin-password basava123#

3.    az acs kubernetes install-cli

4.    PS C:\Program Files (x86)> az acs kubernetes get-credentials --resource-group=myKubernetesWindowsResourceGroup --name=myKubernetesWindowsCluster

5.    PS C:\Program Files (x86)>  .\kubectl.exe get pods

6.    PS C:\Program Files (x86)> .\kubectl.exe  create secret docker-registry myregistrykey --docker-server=https://acrgirish.
azurecr.io --docker-username=ACRgirish --docker-password=K7/n0/8r9zt9AIg+JCftoC6Dyzrg=4rf --docker-email=ANY_EMAIL_ADDRESS
7.    PS C:\Program Files (x86)> .\kubectl.exe create -f C:\Users\aditi\Desktop\K8\Deployment.json

8.    PS C:\Program Files (x86)> .\kubectl.exe create -f C:\Users\aditi\Desktop\K8\Service.json




Service.json file
{
    "apiVersion": "v1",
    "kind": "Service",
    "metadata": {
        "name": "musicstoreapp"
    },
    "spec": {
        "selector": {
            "app": "musicstoreapp"
        },
"type": "LoadBalancer",
        "ports": [{
            "port": 80
        }]
    }
}

Deployment.json file
{
    "apiVersion": "extensions/v1beta1",
    "kind": "Deployment",
    "metadata": {
        "name": "musicstoreapp"
    },
    "spec": {
        "replicas": 2,
        "template": {
            "metadata": {
                "labels": {
                    "app": "musicstoreapp"
                }
            },
            "spec": {
                "containers": [{
                    "name": "musicstore",
                    
                    "image": "acrgirish.azurecr.io/mvcmusicstore",
                    "ports": [{
                        "containerPort": 80
                    }]
                }],
                "imagePullSecrets": [{
                        "name": "myregistrykey"
                }]
            }
        }
    }

Creating the Kuberenetes cluster on Azure and running dotnet core containers

Install the azure cli 2.0 and run the following commands in prowershell

az login  # login to azure

az group create --name="LinuxACSResource" --location="Southeast Asia" # Create a resource group

az acs create --orchestrator-type=kubernetes --resource-group "LinuxACSResource" --name="cluster
name" --dns-prefix="dnsprefix" --generate-ssh-keys # Create a Kubernetes cluster

az acs kubernetes install-cli # Install kube ctl

az acs kubernetes get-credentials --resource-group="LinuxACSResource" --name="clustername"
#  Get the kubernetes config file

PS C:\Program Files (x86)> .\kubectl.exe get nodes #  Get the kubernetes nodes

PS C:\Program Files (x86)> .\kubectl.exe run nginx --image nginx #  Run the Nginx image

PS C:\Program Files (x86)> .\kubectl.exe get pods #  Get the Pods

PS C:\Program Files (x86)> .\kubectl.exe expose deployments nginx --port=80 --type=LoadBalancer #  Run a service

PS C:\Program Files (x86)> .\kubectl.exe get svc #  Get a service

Run the dotnet core container

docker login

docker login acrgirish.azurecr.io -u ACRgirish -p K7/n0/8r9zt9AIg+JCftoC6Dyzrg=4rf

docker tag corewebapp:dev acrgirish.azurecr.io/app

docker push acrgirish.azurecr.io/app

PS C:\Program Files (x86)> .\kubectl.exe create -f C:\Users\aditi\Desktop\K8\Deployment.yaml

PS C:\Program Files (x86)> .\kubectl.exe get pods

PS C:\Program Files (x86)> .\kubectl.exe create -f C:\Users\aditi\Desktop\K8\Service.yaml


//dockerfile

FROM microsoft/aspnetcore:1.1
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-/bin/Release/netcoreapp1.1/publish} .
ENTRYPOINT ["dotnet", "corewebapp.dll"]


//deployment.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: dotnetcoreapp
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: dotnetcoreapp
    spec:
      containers:
      - name: coreapp
        image: acrgirish.azurecr.io/app
        ports:
        - containerPort: 8080
      imagePullSecrets:
      - name: myregistrykey


//service.yaml

apiVersion: v1
kind: Service
metadata:
   namedotnetcoreapp
spec:
  selector:
    appdotnetcoreapp
  typeLoadBalancer
  ports:
    - port: 80

kubectl create secret docker-registry myregistrykey --docker-server=https://myregistry.azurecr.io --docker-username=ACR_USERNAME --docker-password=ACR_PASSWORD --docker-email=ANY_EMAIL_ADDRESS

Tuesday, June 20, 2017

Powershell script to perform action on remote computer

Powershell script to stop-website on a remote computer


$securepassword=Convertto-SecureString –String $(adminpassword) –AsPlainText –force
$mycredentials=New-object System.Management.Automation.PSCredential $(adminuser),$securepassword
Invoke-Command -ComputerName "computername" -ScriptBlock {
            Import-module WebAdministration;
            Stop-Website "TestCD"
} -Credential $mycredentials

Sunday, May 14, 2017

Kubernetes basics : windows cluster in azure

Kubernetes:Container orchestration engine 


1.     Pods: Its a collection of containers or processes. Containers within a pod share an IP address and port space and can talk to each other through localhost. Its the basic unit of deployment in kubernetes as in a container is the basic unit of deployment in Docker. Each Pod as unique IP Address
a.      Ex: Container for sync files and another container for serving the files can be part of single pod
b.     It can contain only container

2.     Replication controller or Replication Sets: This make sure the specified number of pods are running at any one time and also make sure the system is in the desired state.

Ex: if one of the pod is down. controller will create a new pod and the pods are load balanced  

3.     Deployments: It contains the details of the pods and the replication controller It will deploy the replica sets which will deploy pods and in turn deploy container.

4.     Services: Its a group of pods that can be accessed as a single unit. If one of the pod goes down. a new a pod is created and user has to contact only the service and not to the pods directly

5.     Persistent Volumes: for users and administrators that abstracts details of how storage is provided from how it is consumed

6.     Config Maps: Applications require configuration via some combination of config files, command line arguments and environment variables


Creating kubernetes windows cluster in azure 

Install AzureCLI-2.0

Create a resource group
az group create --name=myKubernetesResourceGroup --location=westus

Create the Cluster
az acs create --orchestrator-type=kubernetes --resource-group myKubernetesResourceGroup --name=myKubernetesClusterName --dns-prefix=myPrefix --agent-count=2 --generate-ssh-keys --windows --admin-
username girish --admin-password basava123#

Install kubectl 
az acs kubernetes install-cli

Get the config file
az acs kubernetes get-credentials --resource-group=myKubernetesResourceGroup --name=myKubernetesClusterName



Create a Json file for creating a Pod

{

 "apiVersion": "v1",

 "kind": "Pod",

 "metadata": {

   "name": "iis",

   "labels": {

     "name": "iis"

   }

 },

 "spec": {

   "containers": [

     {

       "name": "iis",

       "image": "microsoft/iis",

       "ports": [

         {

         "containerPort": 80

         }

       ]

     }

   ],

   "nodeSelector": {

     "beta.kubernetes.io/os": "windows"

   }

 }

}


Create a pods

   kubectl apply -f C:\Users\girish\Desktop\iis.json


Get the Pods

kubectl get pods

To expose the container to the world,Run the below command which will create a service and a azure load balancer

kubectl expose pods iis --port=80 --type=LoadBalancer

To see the service

kubectl get svc

Sunday, May 7, 2017

VSTS: Get the team current sprint name from REST API

The following powershell script will get the current sprint name of the team in a project, we can use the same or other REST API in VSTS pipeline.



Param
(
   [string] $vstsAccount = "girishgoudar",
   [string] $projectName = "PritiX.Assignment.Exam.Demo",
   [string] $teamName = "PritiX.Assignment.Exam.Demo%20Team",
   [string] $token = "icww3qhmyrcbdgs3zeuwgcss24pk5tbsuni3zmkfhxugdkv3i63q" #personal Access token PAT
 
)

$results = @{}

if(!$vstsAccount.ToLower().Contains(".visualstudio.com")) {$vstsAccount+=".visualstudio.com"}
if(!$vstsAccount.ToLower().StartsWith("https://")) {$vstsAccount = "https://"+$vstsAccount}
if(!$vstsAccount.EndsWith("/")) {$vstsAccount+="/"}

# Only current iteration of the team

$uri = "$($vstsAccount)DefaultCollection/$($projectName)/$($teamName)/_apis/work/TeamSettings/Iterations?`$timeframe=current&api-version=2.0"

# Calls VSTS REST API

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$results = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

# Test for results
if ($results.count -eq 0)
{
     throw "Results not found"
}

Write-Host $results.value[0].name
Write-Host $results.value[0].url

Saturday, May 6, 2017

Create pester test to check the status of the web site

The following powershell script will run the pester test and the test will pass when the website is up and running and fail when the web site state is other than started

We can also include this test as part of the pipeline in VSTS and publish the test results 


Param(
        [string]$computerName,
        [string]$webSiteName
    )
    describe ‘Check Web Site Status’ {
    
    #$secpasswd = ConvertTo-SecureString “PlainTextPassword” -AsPlainText -Force
    #$mycreds = New-Object System.Management.Automation.PSCredential (“username”, $secpasswd)
    $credentials = Get-Credential
     it ‘Checks if the web site is in started state after deployment’ {
        
        Invoke-Command -ComputerName $computerName -ScriptBlock {
            Import-Module WebAdministration;
            $webSite = Get-Website -Name $webSiteName
            if($webSite.state -eq "Started")
            {
                return $true
            }
            else
            {
                return $false
            }
        } -Credential $credentials | Should Be $true

     }
    
 }