normalian blog

I will introduce about Microsoft Azure, ASP.NET or Java EE

How to solve RDP access error "CredSSP Encryption Oracle Remediation"

With the release of the March 2018 Security bulletin, it causes some changes. When you try to connect to updated VMs, you probably get error like below.
f:id:waritohutsu:20180514044358p:plain

[Window Title]
Remote Desktop Connection

[Content]
An authentication error has occurred. The function requested is not supported

Remote computer: 13.93.225.149
This could be due to CredSSP encryption oracle remediation.
For more information, see https://go.microsoft.com/fwlink/?linkid=866660

[OK]

Refer to Unable to RDP to Virtual Machine: CredSSP Encryption Oracle Remediation – Azure Virtual Machines to know detail. In this article, I will describe how to solve this issue simply.

Execute gpedit.msc and go to Computer Configuration / Administrative Templates / System / Credentials Delegation like below.
f:id:waritohutsu:20180514044816p:plain

Change Encryption Oracle Remediation policy to Enabled, and Protection Level to Vulnerable like below.
f:id:waritohutsu:20180514044941p:plain

API Management and Service Fabric Collaboration for Global Scale Applications

As you know, you can achieve Microservice architecture by using Service Fabric, but you might want to need request routing features for your applications for multi languages, cross devices or others. In such a case, you can use API Management for it. In this article, you can learn how to setup API Management with Service Fabric.

Edit ServiceManifest.xml of your Serviec Fabric project

At first, make a REST API application and deploy it into your Service Fabric cluster. Note to edit "ServiceManifest.xml" file in your Service Fabric project not to specify actual port like below. This setup is needed to collaborate API Management and Service Fabric.

<Resources>
  <Endpoints>
    <Endpoint Protocol="http" Name="ServiceEndpoint" Type="Input" />
  </Endpoints>
</Resources>

Download certificate file to access Service Fabric cluster

You probably created the certificate automatically when you made your Service Fabric cluster. Go to your Service Fabric cluster, choose "security" tab and pick up the certificate thumbprint like below.
f:id:waritohutsu:20180415080735p:plain

Next, download the certificate file as pfx into your machine. Go to KeyVault, choose "certificate" tab, select your certificate and choose "Download in PFX/PEM format" like below.
f:id:waritohutsu:20180415081024p:plain

Save thumbprint and pfx file to use ARM Template in later section.

Deploy new API Management instance by using ARM Template

Download apim.json and apim.parameters.json ARM Templates from service-fabric-api-management/apim.json at master · Azure-Samples/service-fabric-api-management · GitHub. And add '"validateCertificateChain": false into apim.json' if you will use self-signed certificate file like below .

            "apiVersion": "2017-03-01",
            "type": "Microsoft.ApiManagement/service/backends",
            "name": "[concat(parameters('apimInstanceName'), '/', parameters('service_fabric_backend_name'))]",
            "dependsOn": [
                "[resourceId('Microsoft.ApiManagement/service', parameters('apimInstanceName'))]",
                "[resourceId('Microsoft.ApiManagement/service/certificates', parameters('apimInstanceName'), parameters('serviceFabricCertificateName'))]"
            ],
            "properties": {
                "description": "My Service Fabric backend",
                "url": "fabric:/fake/service",
                "protocol": "http",
                "resourceId": "[parameters('clusterHttpManagementEndpoint')]",
                "tls":{
                    "validateCertificateChain": false
                },
                "properties": {
                    "serviceFabricCluster": {
                        "managementEndpoints": [
                            "[parameters('clusterHttpManagementEndpoint')]"
                        ],
                        "clientCertificateThumbprint": "[parameters('serviceFabricCertificateThumbprint')]",
                        "serverCertificateThumbprints": [
                            "[parameters('serviceFabricCertificateThumbprint')]"
                        ],
                        "maxPartitionResolutionRetries": 5
                    }
                }
            }
        },

Update apim.parameters.json like below.

{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "apimInstanceName": {
            "value": "sfapim01"
        },
        "subnetName": {
            "value": "API-Subnet"
        },
        "apimPublisherEmail": {
            "value": "mymail@address.com"
        },
        "apimSku": {
            "value": "Developer"
        },
        "serviceFabricCertificateName": {
            "value": "Daichi Isami"
        },
        "serviceFabricCertificate": {
            "value": "base64 encoded string of your pfx file. don't insert breaklines"
        },
        "certificatePassword": {
            "value": ""
        },
        "serviceFabricCertificateThumbprint": {
            "value": "your Cluster certificates thumbprint"
        },
        "url_path": {
            "value": "/api/values"
        },
        "clusterHttpManagementEndpoint": {
            "value": "https://'your cluster name'.westus.cloudapp.azure.com:19080"
        },
        "inbound_policy":{
            "value": "<policies>\r\n  <inbound>\r\n    <base />\r\n    <set-backend-service backend-id=\"servicefabric\" sf-service-instance-name=\"fabric:/SFApiApp/Web1\" sf-resolve-condition=\"@((int)context.Response.StatusCode != 200)\" />\r\n  </inbound>\r\n  <backend>\r\n    <base />\r\n  </backend>\r\n  <outbound>\r\n    <base />\r\n  </outbound>\r\n  <on-error>\r\n    <base />\r\n  </on-error>\r\n</policies>"
        },
        "policies_policy_name": {
            "value": "policy"
        },
        "apis_service_fabric_app_name": {
            "value": "service-fabric-app"
        },
        "apim_service_fabric_product_name": {
            "value": "service-fabric-api-product"
        },
        "service_fabric_backend_name": {
            "value": "servicefabric"
        },
        "apis_service_fabric_app_name_operation": {
            "value": "service-fabric-app-operation"
        },
        "vnetName": {
            "value": "VNet-sf-sample01-1709cluster"
        },
        "vnetVersion": {
            "value": "2017-03-01"
        },
        "networkSecurityGroupName": {
            "value": "apim-vnet-security-03"
        },
        "networkSecurityGroupVersion": {
            "value": "2017-03-01"
        }
    }

You can put blank for certificatePassword value if you created your certificate file automatically. Refer to commands for base64encode for your certificate below if you need.

$bytes = [System.IO.File]::ReadAllBytes("C:\temp\yourpfxfile.pfx")
$b64 = [System.Convert]::ToBase64String($bytes);
$b64 

It should takes 30 or 40 minutes to complete this deployment.

Access your Service Fabric application via API Management

Go to "Developer Portal" of your API Management, choose "Service Fabric App" among APIs and click "Try it" button. Now, you can send requests to your API application via API Management like below.
f:id:waritohutsu:20180415082448p:plain

Tips No.1: Troubleshoot - "Service Fabric exception when trying to resolve partition: A Security error has occurred, failed to verify remote certificate"

You might get error messages below if you use self-signed certificate file.

service-fabric-backend (1371 ms)
{
    "message": "Service Fabric exception when trying to resolve partition: A Security error has occurred, failed to verify remote certificate.",
    "serviceName": {},
    "resourceId": "https://sf-sample01-1709cluster.westus.cloudapp.azure.com:19080",
    "managementEndpoint": [
        "https://sf-sample01-1709cluster.westus.cloudapp.azure.com:19080"
    ]
}

You should forget to update apim.json. Refer to " Deploy new API Management instance by using ARM Template" section in this article.

Tips No.2: Don't use “Client certificates” for API Management

As you know, Service Fabric uses multiple certificates for itself. Note that use "Cluster certificates" not "Client certificates" for API Management.
f:id:waritohutsu:20180415110457p:plain

How to setup CI/CD pipeline with Service Fabric, VSTS and Windows Container

We have tried lots of features to collaborate wtih Service Fabric, VSTS and Docker containers. I have realized it's needed to describe overview of the architecture, so you can learn it following this article.

Overview of Service Fabric, VSTS and Windows Container architecture

At first, refer to the architecture diagram below. Purple lines mean processing flows of the CI/CD pipeline and green lines mean its setting dependencies.
f:id:waritohutsu:20180411082506p:plain

Create below resources to setup this architecture.

  • Service Fabric cluster
  • VSTS Proejct, Build Process and Release Process
  • Azure Container Registry
  • Virtual Machines for VSTS Private Agent

In this article, you can find references to Service Fabric cluster, VSTS and Virtula Machines. But create Azure Container Registry for yourself and it should be quite easy.

a - Setup Private Agent for VSTS Build Definitions

Unfortunately, Windows Docker base image sizes are about 1.5G. It takes much time to download and build Docker images if you don't use Pirvate Agent. By caching the Docker images, its building time can be largely reduced.

3. and 4. Deploy deployment artifacts into Service Fabric cluster and download your Docker images from Azure Container Registry

Create VSTS Release Definitions to deploy Windows Docker images into Service Fabric cluster

This article requires to setup below environment at first. Please refer to them before following this article.

You have to complete all setups of CI/CD cycle using Windows Docker images, Service Fabric cluster and VSTS except for VSTS Release Definitions before following this article. I believe you have already created artifacts using by your VSTS Build definition to deploy into your Service Fabric cluster. Now, you can deploy the artifact by following this article.

Create a Release Definition to use artifacts created by your Build Definition

Choose "Releases" item from the top of VSTS menus, click "+" icon from left side and choose create "Create release definition", so you can find below diagrams.
f:id:waritohutsu:20180411040657p:plain

Next, click "Add artifact", choose "Build" as "Source type" and setup your "Project" and "Source(Build definition)" which you have already created before following this article. Refer to below image if you need.
f:id:waritohutsu:20180411040922p:plain

Next, choose "Add environment" box and choose "Azure Service Fabric Deployment". Note that you need to complete
How to setup Service Fabric connections on VSTS - normalian blog to setup this. Refer to below image and table as you need.
f:id:waritohutsu:20180411041231p:plain

Parameter Name Value note
Application Package $(system.defaultworkingdirectory)/**/drop/applicationpackage -
Cluster Connection sf-sample01-1709cluster You must finish How to setup Service Fabric connections on VSTS - normalian blog to setup this
Publish Profile $(system.defaultworkingdirectory)/**/drop/projectartifacts/**/PublishProfiles/Cloud.xml -

Execute Release definition

After completion to create the Release Definition, click "+Rlease" link on VSTS portal.
f:id:waritohutsu:20180411041901p:plain

Next, you can execute your deployment process by clicking "Deploy" on VSTS portal like below. After execution of the process, you also be able to watch process progress by choosing "Logs" tab on VSTS portal.
f:id:waritohutsu:20180411042038p:plain

This is "Logs" tab on VSTS.
f:id:waritohutsu:20180411042151p:plain

Create Service Fabric Deployment Package with Docker images on VSTS Build Task

This article requires to setup below environment at first. Please refer to them before following this article.

I believe you have already created your own Docker images and pushed them into your Azure Container Registry. Now, you also need to specify the images with Service Fabric setting files to use them by your Service Fabric cluster.

How to setup Build tasks on VSTS

You need to add 5 tasks after your "Push an image" task, but you also need to add "PowerShell Script" task if you might need to use capital letters in your project names or something. Refer to How to override values of environment variables on VSTS tasks - normalian blog to override environment variables.
f:id:waritohutsu:20180410095141p:plain

Now, we will introduce how to setup the tasks.

  • Replace Tokens
  • Build solution
  • Update Service Fabric Manifests
  • Copy Files
  • Publish Build Artifacts
Replace Tokens

You need to update ServiceManifest.xml to specify your Docker image for your Service Fabric cluster.
f:id:waritohutsu:20180410082512p:plain

Parameter Name Value note
Root directory Trunk/SFwithASPNetApp/SFwithASPNetApp Specify as Service Fabric directory
Target files **/*.xml Specify to include ServiceManifest.xml

You need to edit your ServiceManifest.xml like below

<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="GuestContainer1Pkg"
                 Version="1.0.0"
                 xmlns="http://schemas.microsoft.com/2011/01/fabric"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ServiceTypes>
    <!-- This is the name of your ServiceType.
         The UseImplicitHost attribute indicates this is a guest service. -->
    <StatelessServiceType ServiceTypeName="GuestContainer1Type" UseImplicitHost="true" />
  </ServiceTypes>

  <!-- Code package is your service executable. -->
  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <!-- Follow this link for more information about deploying Windows containers to Service Fabric: https://aka.ms/sfguestcontainers -->
      <ContainerHost>
        <ImageName>"your acr account name".azurecr.io/#{Build.Repository.Name}#:#{Build.BuildId}#</ImageName>
      </ContainerHost>
    </EntryPoint>
    <!-- Pass environment variables to your container: -->
    <!--
    <EnvironmentVariables>
      <EnvironmentVariable Name="VariableName" Value="VariableValue"/>
    </EnvironmentVariables>
    -->
  </CodePackage>
  .....
Build solution

You need to specify *.sfproj file to build your Service Fabric application like below.
f:id:waritohutsu:20180410082650p:plain

Parameter Name Value note
Solution Trunk/SFwithASPNetApp/SFwithASPNetApp/SFwithASPNetApp.sfproj Specify your Service Fabric cluster *.sfproj file
MSBuild Arguments /t:Package /p:PackageLocation=$(build.artifactstagingdirectory)\applicationpackage Specify to create Service Fabric package
Platform $(BuildPlatform) -
Configuration $(BuildConfiguration) -
Update Service Fabric Manifests

You need to update your ServiceManifest.xml version number by environment variable.
f:id:waritohutsu:20180410094301p:plain

Parameter Name Value note
Update Type Manifest versions -
Application Package $(build.artifactstagingdirectory)\applicationpackage -
Version Value .$(Build.BuildNumber) -
Copy Files

You also need to copy your application xml files.
f:id:waritohutsu:20180410094327p:plain

Parameter Name Value note
Source Folder $(build.sourcesdirectory) -
Contents **\PublishProfiles\*.xml
**\ApplicationParameters\*.xml
-
Publish Build Artifacts

Finally, you can publish your build artifacts and you can use it in your Release process.

Parameter Name Value note
Path to publish $(build.artifactstagingdirectory) -
Artifact name drop -
Artifact publish location Visual Studio Team Services/TFS -

How to confirm build result

You can watch your build result logs in VSTS Build page like below, and you also can find your build number like below. The number is used for Docker images tags.
f:id:waritohutsu:20180410100246p:plain

Replace configuration files with environment variables on VSTS tasks

I believe you definitely want to replace values of some files in your projects with environments variables when you setup Visual Studio Team Services Build/Release processes. There are some ways to replace the values, and I will introduce to use e "Replace Tokens" published in Marketplace.

How to use "Replace Tokens" on VSTS

Input "Replace Tokens" into search box when you add new tasks in your VSTS Build/Release process and click "Install" to initialize it.
f:id:waritohutsu:20180406070531p:plain

After adding "Replace Tokens" task in your process, change "Root directory" and "Target files" to specify which files you want to change. In below example, I specify *.xml files in my "SFwithASPNetApp" project.
f:id:waritohutsu:20180406070730p:plain

And finally refer below a part of Service Fabric ServiceManifest.xml. This xml file uses "Build.Repository.Name" and "Build.BuildId" environment variables to specify Docker image name.

  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <!-- Follow this link for more information about deploying Windows containers to Service Fabric: https://aka.ms/sfguestcontainers -->
      <ContainerHost>
        <ImageName>mynormalianregister.azurecr.io/#{Build.Repository.Name}#:#{Build.BuildId}#</ImageName>
      </ContainerHost>
    </EntryPoint>

The Docker image name will replace from "mynormalianregister.azurecr.io/#{Build.Repository.Name}#:#{Build.BuildId}#" into "mynormalianregister.azurecr.io/us-customer-demo-projects:111" in this case.

Note that you must put "}#" not "}" as suffix token.

How to override values of environment variables on VSTS tasks

As you know VSTS can use environment variables in VSTS Build and Release tasks. It's really useful to dynamically change values of build and release process like below, but you should sometimes wants to override even in running tasks.
f:id:waritohutsu:20180329072459p:plain

I have built Windows Docker images on with VSTS build tasks by specifying its name as $(Build.Repository.Name), the actual name is "US-XXXXXX-Demo-Projects", and I store them into Azure Container Registry. But unfortunately, Azure Container Registry stores Docker images as lowercase letters like below.
f:id:waritohutsu:20180329092859p:plain

As this result, you need to change Docker image name from $(Build.Repository.Name), change repository name itself or override environment variable. This article shows how to override the value.

How to override environment variable values on VSTS tasks

You need to add "PowerShell" tasks into your build process, specify its "Type" as "Inline Script" and edit "Inline Script" like below.
f:id:waritohutsu:20180329073438p:plain

$LowerBuildRepositoryName = "$(Build.Repository.Name)".ToLower()
Write-Output ("##vso[task.setvariable variable=Build.Repository.Name;]$LowerBuildRepositoryName")

Write-Host "Build.Repository.Name variable updates"

You can override any variables as you like to edit the inline script.