Setting up HTTPS on an AKS Cluster

Pre-Reqs

The following is required:

  • An ingress controller should already be installed.
  • The public IP of the Ingress controller should have a DNS name.
  • Helm needs to be running at 2.13.1.
  • The Kubernetes cluster should be publicly accessible (to allow cert creation)

To check if Helm is running with version 2.13.1 (there is a bug that doesn’t allow 2.14+ to work). To check, run the following:

helm version

Client: &version.Version{SemVer:"v2.13.1", GitCommit:"618447cbf203d147601b4b9bd7f8c37a5d39fbb4", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.13.1", GitCommit:"618447cbf203d147601b4b9bd7f8c37a5d39fbb4", GitTreeState:"clean"}

If the output doesn’t match as below, you need to downgrade Helm. Install:

# only needed if Client above is not 2.13.1
choco uninstall kubernetes-helm
choco install kubernetes-helm --version 2.13.1

helm init --upgrade --force-upgrade

Procedure

Run the following commands:

# Install the CustomResourceDefinition resources separately
kubectl apply -f https://raw.githubusercontent.com/jetstack/cert-manager/release-0.8/deploy/manifests/00-crds.yaml

# Create the namespace for cert-manager
kubectl create namespace cert-manager

# Label the cert-manager namespace to disable resource validation
kubectl label namespace cert-manager certmanager.k8s.io/disable-validation=true

# Add the Jetstack Helm repository
helm repo add jetstack https://charts.jetstack.io

# Update your local Helm chart repository cache
helm repo update

# Install the cert-manager Helm chart
helm install --name cert-manager --namespace cert-manager --version v0.8.0 jetstack/cert-manager

Create the following YAML file `cluster-issuer.yml’:

apiVersion: certmanager.k8s.io/v1alpha1
kind: ClusterIssuer
metadata:
  name: letsencrypt-staging
  namespace: ingress-nginx
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: UPDATE_THIS_EMAIL
    privateKeySecretRef:
      name: letsencrypt-staging
    http01: {}

Apply the changes to the cluster:

kubectl apply -f ../shared/cluster-issuer.yml

Create the certificate.yml file:

apiVersion: certmanager.k8s.io/v1alpha1
kind: Certificate
metadata:
  name: tls-secret
  namespace: ingress-nginx
spec:
  secretName: tls-secret-staging
  dnsNames:
  - YOUR_DOMAIN
  acme:
    config:
    - http01:
        ingressClass: nginx
      domains:
      - YOUR_DOMAIN
  issuerRef:
    name: letsencrypt-staging
    kind: ClusterIssuer

Apply those changes:

kubectl apply -f certificate.yml

Verification

Confirm creation of the certificate:

kubectl describe certificate tls-secret --namespace ingress-nginx

You should see the following:

...
Normal   OrderCreated        27s                cert-manager  Created Order resource "tls-secret-3300974441"
Normal   CertIssued          3s (x2 over 20m)   cert-manager  Certificate issued successfully
Normal   OrderComplete       3s                 cert-manager  Order "tls-secret-3300974441" completed successfully

Verify HTTPS can be accessed.

Applying IP Restrictions to a Large Set of Azure Resources

To do this, use PowerShell and Azure CLI to collect all of the NSGs and get all of the NSGs in the subscription:

az account set -s <SUB_ID>
$nsgs = az network nsg list | ConvertFrom-Json

Then go through every NSG and create the rule:

$nsgs | ForEach-Object -Process { az network nsg rule create --name NAME --nsg-name $_.name --priority PRIORITY --resource-group $_.resourceGroup <ANY OTHER FIELDS> }

Next, get a list of the App Services:

$webapps = az webapp list | ConvertFrom-Json

And go through and add the list of IPs required (must use individual IPs):

$webapps | ForEach-Object -Process { $WebAppConfig = Get-AzResource -ResourceName $_.name -ResourceType Microsoft.Web/sites/config -ResourceGroupName $_.resourceGroup -ApiVersion 2018-11-01; $WebAppConfig.Properties.ipSecurityRestrictions = @([PSCustomObject] @{ ipAddress = '127.0.0.1/32' },@{ ipAddress = '127.0.0.1/32' });  Set-AzResource -ResourceId $WebAppConfig.ResourceId -Properties $WebAppConfig.Properties -ApiVersion 2018-11-01 }

Removing Access

To delete the same list of rules from the NSGs, use the same name:

$nsgs | ForEach-Object -Process { az network nsg rule delete -g resourceGroup --nsg-name $_.name -n NAME }

Reference:

https://docs.microsoft.com/en-us/cli/azure/network/nsg?view=azure-cli-latest#az-network-nsg-list

https://docs.microsoft.com/en-us/cli/azure/network/nsg/rule?view=azure-cli-latest#az-network-nsg-rule-create

https://docs.microsoft.com/en-us/cli/azure/network/nsg/rule?view=azure-cli-latest#az-network-nsg-rule-delete

Creating a Buy One Get One Half Off Discount In NopCommerce

I recently worked with a client on trying to set up a Buy One Get One Half Off deal on NopCommerce – here’s what I did to get it working:

Requirements

Before starting, you should have the following:

Process

Go to the Discounts page and create a new Discount with the following information:

Next, go to the ‘Restrictions’ tab and add a restriction for the Product, using the ‘Add Product’ functionality Make sure you add the :2 to the end to force purchase of two:

Deploying web.config with an Angular Project

When deploying an Angular project out to Azure, you’ll need to include a web.config file to allow for things such as the following:

  • Getting routing to work.
  • Serving static content.

First, create a web.config file in src/. Here’s an example of what it might look like:

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Angular Routing" stopProcessing="true">
                <match url=".*" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile"
                         negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory"
                         negate="true" />
                </conditions>
                <action type="Rewrite" url="/" />
                </rule>
            </rules>
        </rewrite>
        <staticContent>
            <mimeMap fileExtension="woff" mimeType="application/font-woff" />
            <mimeMap fileExtension="json" mimeType="application/json" />
        </staticContent>
    </system.webServer>
</configuration>

After this is done, make a change to angular.json to bundle the web.config file in the build:

...
"assets": [
    /src/favicon.ico",
    /src/assets",
    /src/web.config"
],
...

Now let’s verify by running ng build --prod:

Adding Bootstrap To An Angular CLI Project

Pre-Reqs

Before setting this up, you’ll need to have an Angular project to add Bootstrap to. If you’re starting fresh, you can create one easily with ng new <name>.

Procedure

First, install bootstrap from npm:

npm install bootstrap

Then add the following to the top of your styles.css file:

@import '~bootstrap/dist/css/bootstrap.min.css';

That’s it! Bootstrap is now enabled for your Angular CLI application.

Setting up WordPress in Azure with AKS and Helm

To get started, you’ll need the following:

  • kubectl
  • helm
  • Azure subscription

Installing WordPress in AKS with Helm

Set up an Azure Kubernetes Service with the following:

  • Node size – desired VM size (cheapest available is B2s)
  • Node count – need to use at least a minimum of 1.

After AKS is set up, connect to it with the following:

az aks get-credentials --resource-group AKS_RG --name AKS_NAME

Install Helm:

helm init

Create a values.yml file:

wordpressUsername: sammy
wordpressEmail: sammy@example.com
wordpressFirstName: Sammy
wordpressLastName: the Shark
wordpressBlogName: Sammy's Blog!

Create a second file values.secret.yml:

wordpressPassword: password

Now install WordPress with the following commands:

helm install --name blog -f values.yml -f values.secrets.yml stable/wordpress

After installation, run the following command to get the external IP:

kubectl get svc --namespace default -w blog-wordpress

Once the IP is ready, you’ll likely need to wait for the pods to finish loading. You can check their status with:

kubectl get pods

Once ready, try accessing the IP address to get the WordPress installation.

Reference: https://www.digitalocean.com/community/tutorials/how-to-set-up-wordpress-with-mysql-on-kubernetes-using-helm

Setting Up SonarQube in Azure with Azure AD Integration

Installing SonarQube

Go to the marketplace and install SonarQube from Bitnami – https://bitnami.com/stack/sonarqube/cloud/azure with the following:

  • resize to D1_v2
  • if desired, configure any NSG restrictions

After creation, set a DNS name label for the IP address.

Access using the domain name, and follow the directions in the link above to log in.

Setting up Azure AD Integration

Setting up HTTPS

To be able to use Azure AD, you have to use HTTPS.

Set up the Server base URL to be the configured HTTPS address in Administration → Configuration → General → Server base URL:

SSH into the server and set up a Let’s Encrypt script and enforce redirection to HTTPS here (make sure you aren’t behind a firewall to allow for Let’s Encrypt).

Restart Apache:

sudo /opt/bitnami/ctlscript.sh restart apache

Verify that trying to access the HTTP version of SonarQube automatically redirects you to the HTTPS version.

Creating App Registration in Azure

Run the following command in CLI to generate a service principal:

az ad sp create-for-rbac --name="{NAME}" --role="Contributor" --scope="/subscriptions/{SUBSCRIPTION_ID}" --years=100

You should receive some output data, which you will use when filling out info in SonarQube:

Set the Reply URL of the application to https://<URL>/oauth2/callback/aad:

Set the required permissions:

  • Sign in and read user profile
  • Read all users’ basic profiles

Installing Plug-in

Install the Azure Active Directory (AAD) Authentication Plug-in for SonarQube (restarting when requested):

Configure in Administration → General Settings → Azure Active Directory:

  1. Activate Azure AD
  2. Use the value in “appId”
  3. Use the value in “password”
  4. Use the value in “tenant”
  5. Allow users to sign-up.

Log out as admin, and verify the ability to log in as an Azure AD user.

Create Multiple Terraform Resources with a Map

I recently worked through a case in Terraform where I wanted to be able to pass in a map for Terraform to allow creating secrets in an Azure Key Vault. We’ll use the count, keys(, and values( helpers to iterate through the map.

This code sample will show a way to dynamically determine the amount of resources needed. In this case, this will create secrets based on the map provided in the Terraform variable:

variable "vault_secrets" {
  secret_name_1 = "secret_value_1"
  secret_name_2 = "secret_value_2"
  secret_name_3 = "secret_value_3"
}

resource "azurerm_key_vault" "vault" {
  name                = "example-vault"
  location            = "${var.rg_location}"
  resource_group_name = "${var.rg_name}"
  tenant_id           = "00000000-0000-0000-0000-000000000000"

  sku {
    name = "standard"
  }
}

resource "azurerm_key_vault_secret" "secret" {
  count = "${length(keys(var.vault_secrets))}"

  name         = "${element(keys(var.vault_secrets), count.index)}"
  value        = "${element(values(var.vault_secrets), count.index)}"
  key_vault_id = "${azurerm_key_vault.vault.id}"
}

Setting up WordPress in Azure with SSL for ~$8 a Month

  • Basic plan (allowing for Always on and SSL): ~$50/month
  • MySQL for Azure: ~$25
  • With this solution, you will create everything on one virtual machine, allowing for dynamic scaling as needed for the machine. This does of course come with some downside:

    • You will need to handle backing up of both the files on the server and the data in the database.

    Creating the VM

    First, create the VM and Resource Group:

    • RG name: <app>-<env>-<location>-rg
    • VM name: <app>-<env>-<location>-vm
    • Image: Ubuntu 18.04 LTS
    • VM size: B1s
    • VNet name: <app>-<env>-<location>-vnet
    • Diagnostics Storage Account: <app><env><location>vmdiag
    • Allow Inbound Port Access for HTTP, HTTPS, SSH
    • Login access through Azure Active Directory

    Once the VM is created, access the NSG and add a restriction to IP to only allow your local IP to access:

    Access VM and Install LAMP Server

    Retrieve the public IP address and SSH into the server:

    ssh <user>@<public_ip>

    Install LAMP Server:

    sudo apt update && sudo apt install lamp-server^

    To ensure the installation happened successfully, run the following commands:

    apache2 -v
    mysql -V
    php -v

    Once LAMP server is installed, verify that you can connect to HTTP using the public IP address – you should see the Apache2 Ubuntu Default Page:

     

    Set up MySQL

    Once the web server is running, the next step is configuring MySQL. Run the following command, installing the Validate Password Plugin and using “Medium” policy:

    sudo mysql_secure_installation

    When installing, use medium strength, and default yes to all options except “Disallow root login remotely?” Generate a password.
    The next step is configuring access to MySQL through external servers (such as from a VPN). This assumes you’ll be using the NSG from Azure to restrict access based on desired IP addresses.
    Run a query to allow access:

    sudo mysql -u root -p
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;

    Edit MySQL configuration:

    sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

    Comment out the line that says ‘bind-address’.
    After making that change, restart MySQL:

    sudo service mysql restart

    Finally, create an NSG rule that allows for external access to port 3306:

    Once the installation is done, let’s verify that the MySQL server can be accessed. I usually use MySQL Workbench and connect to the server using the following information:

    • Hostname: public IP

    After MySQL is set up, set up any database that may be needed.
    Here, you’ll want to set up the WordPress database server, whether you are starting fresh or migrating from an old instance.
    If running into an issue with packet size, run the following command in MySQL and restart:

    sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

    The final step is creating a DB user specifically for the WordPress installation – this use would only have access to the specific database that WordPress uses. Create a user with the following:

    • Allow access to the DB used for the WordPress installation.

    Installing WordPress

    After finishing setting up the LAMP server, next is installing WordPress. Assuming you’ve downloaded the source, you can use the following:

    scp -r .\wordpress-download\ vmadmin@YOUR_SERVER_IP:~

    Now you’ll need to SSH into the server and move the files into /var/www/html:

    sudo mv -v ~/wordpress-download/* /var/www/html/

    Before doing the 5-minute install, run the following to allow for Apache to have write permissions:
    Check the group that Apache is running under:

    cat /etc/apache2/apache2.conf | grep ^Group -B 2
    cat /etc/apache2/envvars | grep GROUP
    # Give that group access
    sudo chown -R www-data:www-data /var/www/html
    sudo find /var/www/html -type d -exec chmod 755 {} \;
    sudo find /var/www/html -type f -exec chmod 644 {} \;
    

    Now perform the 5-minute install to ensure everything is working, you can access the site using the IP address to ensure everything in place.
    While doing this, make sure you can do the following:

    • Configure Apache to use .htaccess files. Change the following in apache2.conf to change AllowOverride to All:
      • <Directory /var/www/>
          Options Indexes FollowSymLinks
          AllowOverride None
          Require all granted
        </Directory>
    • Access a page outside of the home page (sudo a2enmod rewrite && sudo systemctl restart apache2)
    • Upload a media file to test uploads

    Enabling Mail (using G Suite)

    First, set up DNS to use email. For this example, we are using Google Suite for email. Add the following 5 MX records:

    • Host: @
    • Records (priority-URL)
      • 1-ASPMX.L.GOOGLE.COM.
      • 5-ALT1.ASPMX.L.GOOGLE.COM.
      • 5-ALT2.ASPMX.L.GOOGLE.COM.
      • 10-ALT3.ASPMX.L.GOOGLE.COM.
      • 10-ALT4.ASPMX.L.GOOGLE.COM.

    Then, do the following:
    https://wpforms.com/how-to-securely-send-wordpress-emails-using-gmail-smtp/

    Setting up SSL

    Once the web server can be reached and LAMP is installed, the next step is securing the site using SSL. Run the following to enable SSL, enable the SSL site, and restart Apache:

    sudo a2enmod ssl
    sudo a2ensite default-ssl
    sudo systemctl reload apache2

    Once that’s done, access the public IP using HTTPS – you should get an insecure cert warning.
    Now that we’ve determined the port is listening, let’s set up Let’s Encrypt. Using CertBot usually makes this much easier. Since in this case, we’re using Apache and Ubuntu 18.04, we just need to populate those values and run the commands provided by CertBot:

    With these commands, you’ll also need to set up DNS for the domain to use. With the public IP address, create the following:

    • create an A record with the host as @ and the IP address as the web server IP address.

    After this finishes, run the CertBot job to create the certificate. After that finishes, allow for the ability to redirect to HTTPS using the CertBot plugin.
    Reference:

    ]]>