How Do You Create a Server in Azure with Terraform?

Problem scenario
You want to use Terraform to create a virtual machine in Azure. What do you do?

Solution
Prerequisites

i. Terraform must be installed on a Linux server. If you need assistance with this, see this posting.
ii. The Azure CLI must be installed and configured on the Linux server. If you need assistance with this, see this posting. (Normally you would need a client_id and client_secret in the provider block of the .tf file; you do not need these if your Azure CLI has been configured properly.)
iii. You have run ssh-keygen on the Linux server with Terraform, and you have the id_rsa.pub file. You'll need the content of the file for the directions below.

Procedures

  1. Create a file called instance.tf with the following content (this was mostly taken from https://docs.microsoft.com/en-us/azure/virtual-machines/linux/terraform-create-complete-vm) :
# Configure the Microsoft Azure Provider
provider "azurerm" {
    subscription_id = "abcdefghijklmnopqrstuvwxyz1234567891"
    tenant_id       = "777777777777777777777777777777777777"
    version = "=1.22.0"
}

# Create a resource group if it doesn’t exist
resource "azurerm_resource_group" "myterraformgroup" {
    name     = "Coolthing"
    location = "eastus"

    tags {
        environment = "Terraform Demo"
    }
}

# Create virtual network
resource "azurerm_virtual_network" "myterraformnetwork" {
    name                = "myVnet"
    address_space       = ["10.0.0.0/16"]
    location            = "eastus"
    resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"

    tags {
        environment = "Terraform Demo"
    }
}

# Create subnet
resource "azurerm_subnet" "myterraformsubnet" {
    name                 = "mySubnet"
    resource_group_name  = "${azurerm_resource_group.myterraformgroup.name}"
    virtual_network_name = "${azurerm_virtual_network.myterraformnetwork.name}"
    address_prefix       = "10.0.1.0/24"
}

# Create public IPs
resource "azurerm_public_ip" "myterraformpublicip" {
    name                         = "myPublicIP"
    location                     = "eastus"
    resource_group_name          = "${azurerm_resource_group.myterraformgroup.name}"
    allocation_method            = "Dynamic"

    tags {
        environment = "Terraform Demo"
    }
}

# Create Network Security Group and rule
resource "azurerm_network_security_group" "myterraformnsg" {
    name                = "myNetworkSecurityGroup"
    location            = "eastus"
    resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"

    security_rule {
        name                       = "SSH"
        priority                   = 1001
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "22"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
    }

    tags {
        environment = "Terraform Demo"
    }
}

# Create network interface
resource "azurerm_network_interface" "myterraformnic" {
    name                      = "myNIC"
    location                  = "eastus"
    resource_group_name       = "${azurerm_resource_group.myterraformgroup.name}"
    network_security_group_id = "${azurerm_network_security_group.myterraformnsg.id}"

    ip_configuration {
        name                          = "myNicConfiguration"
        subnet_id                     = "${azurerm_subnet.myterraformsubnet.id}"
        private_ip_address_allocation = "Dynamic"
        public_ip_address_id          = "${azurerm_public_ip.myterraformpublicip.id}"
    }

    tags {
        environment = "Terraform Demo"
    }
}

# Generate random text for a unique storage account name
resource "random_id" "randomId" {
    keepers = {
        # Generate a new ID only when a new resource group is defined
        resource_group = "${azurerm_resource_group.myterraformgroup.name}"
    }

    byte_length = 8
}

# Create storage account for boot diagnostics
resource "azurerm_storage_account" "mystorageaccount" {
    name                        = "diag${random_id.randomId.hex}"
    resource_group_name         = "${azurerm_resource_group.myterraformgroup.name}"
    location                    = "eastus"
    account_tier                = "Standard"
    account_replication_type    = "LRS"

    tags {
        environment = "Terraform Demo"
    }
}

# Create virtual machine
resource "azurerm_virtual_machine" "myterraformvm" {
    name                  = "myVM"
    location              = "eastus"
    resource_group_name   = "Coolthing"
    network_interface_ids = ["${azurerm_network_interface.myterraformnic.id}"]
    vm_size               = "Standard_DS1_v2"

    storage_os_disk {
        name              = "myOsDisk"
        caching           = "ReadWrite"
        create_option     = "FromImage"
        managed_disk_type = "Premium_LRS"
    }

    storage_image_reference {
        publisher = "Canonical"
        offer     = "UbuntuServer"
        sku       = "16.04.0-LTS"
        version   = "latest"
    }

    os_profile {
        computer_name  = "myvm"
        admin_username = "azureuser"
    }

    os_profile_linux_config {
        disable_password_authentication = true
        ssh_keys {
            path     = "/home/azureuser/.ssh/authorized_keys"
            key_data = "ssh-rsa AAAAB...ec2-instance5.azure.gcp.com"
        }
    }

    boot_diagnostics {
        enabled = "true"
        storage_uri = "${azurerm_storage_account.mystorageaccount.primary_blob_endpoint}"
    }

    tags {
        environment = "Terraform Demo"
    }
}

2.a. Replace "ssh-rsa AAAAB…ec2-instance5.azure.gcp.com" in the above file with the content of the id_rsa.pub file. To find this file run sudo find / -name id_rsa.pub. To create this file if you do not have it, run ssh-keygen -t rsa -P ""
2.b. Change "abcdefghijklmnopqrstuvwxyz1234567891" to your subscription ID. If you need assistance finding your subscription ID, see this posting.
2.c. Change "777777777777777777777777777777777777" in the file above to your tenant ID.
2.d. (Optional.) Change "eastus" to the region of your choice (e.g., "westus").

3. Run these commands:

terraform init
terraform apply

(Respond with "yes" to the prompt.)

4. You have now created a VM in Azure. You will be able to log in with SSH to the new VM using the "azureuser" account from the server you ran the Terraform commands from.

Using Python How Do You Write a Palindrome Tester?

Problem scenario
You want to write a Python program that tests if a string is a palindrome. You want the calling function to have five lines of code or fewer. How do you do this?

Solution
Here is a program that interactively prompts you for a string and will tell you if it is palindromic or not.

# You may want to see this documentation page: https://docs.python.org/2.3/whatsnew/section-slices.html

stra = input("Enter a string: ")

def goodone(stra):
  if(str(stra) == str(stra)[::-1]):
    print("It is palindromic.")
  else:
    print("The entered string was not a palindrome.")

goodone(stra)

What is Calico?

Question
In the context of container orchestration, you have read or seen "Calico." What is it?

Answer
"Calico provides a highly scalable networking and network policy solution for connecting Kubernetes pods based on the same IP networking principles as the internet. … Calico also provides fine-grained, intent based network security policy for Kubernetes pods via its distributed firewall." Taken from https://kubernetes.io/docs/concepts/cluster-administration/networking/

"Calico provides secure network connectivity for containers and virtual machine workloads. Calico creates and manages a flat layer 3 network, assigning each workload a fully routable IP address." Taken from https://docs.projectcalico.org/v3.3/introduction/

"Project Calico is an open source container networking provider and network policy engine." taken from https://kubernetes.io/docs/concepts/cluster-administration/networking/

What is Flannel?

Question
You have heard about flannel in the context of container orchestration. What is flannel?

Answer
"Flannel is a simple and easy way to configure a layer 3 network fabric designed for Kubernetes." Taken from https://github.com/coreos/flannel

"Flannel is a networking technology used to connect Linux Containers. It is distributed and maintained by CoreOS, the producer of the stripped-down CoreOS Linux operating system for containers, as well as the rkt container system that competes with Docker." Taken from
https://www.sdxcentral.com/containers/definitions/what-is-coreos-flannel-definition/

"Flannel is a very simple overlay network that satisfies the Kubernetes requirements." taken from https://kubernetes.io/docs/concepts/cluster-administration/networking/

How Do You Find (Or Determine) What Product Key Id Is Associated with Your Windows Computer?

Problem scenario
You lost your product key to your Windows computer. You find command prompt and PowerShell commands do not work to display the key ID. How do you display it (e.g., for upgrade purposes)?

Solution
Use this GUI (.exe) tool found here:
https://gallery.technet.microsoft.com/scriptcenter/Get-Windows-Product-6b5e6f6e

What Is The Difference between git merge and git rebase?

Question
What is the difference between git merge and git rebase?

Answer
git merge takes code from one branch and copies it into another branch. One branch will prevail to the extent there are conflicts. (The details of the syntax are beyond the scope of this solution. The git merge operation can be done in a GUI (e.g., via BitBucket).) The published source code would usually change.

git rebase takes code from a committed branch and overwrites your local branch. git rebase brings down code with the trunk code always prevailing. The published source code does not change.

git merge is for committing code upstream and git rebase is for bring new code downstream. If production is the most upstream you can go and development is the most downstream you can go, the public Git repository holds code. As you develop a new feature, you may find another developer committed code for something you were working on. You may want to bring that change upstream back down into development. This way when you integrate your code, you can manually reconcile any potential conflicts.

"The golden rule of git rebase is to never use it on public branches." (Taken from this link.)

git merge operations are usually for making public your code. git rebase is usually for getting a new baseline to develop from.

If you want to learn more about the differences between the two, see these postings:
https://www.atlassian.com/git/tutorials/merging-vs-rebasing
https://stackoverflow.com/questions/804115/when-do-you-use-git-rebase-instead-of-git-merge

How Do You Install the Azure CLI on a Debian/Ubuntu Linux Server?

Problem scenario
You want to use the Azure CLI on a Debian/Ubuntu Linux server.

Solution

1. Run these commands:

sudo apt-get -y update sudo apt-get install -y curl apt-transport-https lsb-release gpg curl -sL https://packages.microsoft.com/keys/microsoft.asc | \ gpg --dearmor | \ sudo tee /etc/apt/trusted.gpg.d/microsoft.asc.gpg > /dev/null AZ_REPO=$(lsb_release -cs) echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | \ sudo tee /etc/apt/sources.list.d/azure-cli.list sudo apt-get -y update sudo apt-get -y install azure-cli

2. Test it with this command:
az login

(You will need to go to a web browser and enter a code.)

What Does __name__ in Python Do?

Problem scenario
What does the name syntax signify?

Solution
In the Python interpreter name keeps track of how a function or file is called. What does it signify exactly? Rather than explain this one in words, do the following:

1. Create foo.py with the following line (the name of the next file without its extension):

import bar

2. In the same directory as foo.py above, create bar.py with the following lines:

print ("Hello World from %s!" % __name__)

if __name__ == '__main__':
    print("Hello World again from %s!" % __name__)

3. Run these two commands and examine the output:

python foo.py

It prints out this:
Hello World from bar!

python bar.py

It prints out this:

Hello World from main!
Hello World again from
main!

How Do You Troubleshoot the Kubernetes Problem “connection to the server localhost:8080 was refused”?

One of the following applies (with #1 being related to Kubernetes anywhere and #2 only being relevant to running Kubernetes in GCP).

Problem scenario #1 (any Kubernetes)
You run a command like this: kubectl get svc

You get an error like this: The connection to the server localhost:8080 was refused - did you specify the right host or port?

What should you do?


Problem scenario #2 (in GCP only)
You created a Google Kubernetes cluster. From a server with kubectl, you run a kubectl command. Here is an example:

kubectl cluster-info dump

You receive this error: "The connection to the server localhost:8080 was refused - did you specify the right host or port?" What should you do?

Possible Solution #1
What is your $KUBECONFIG variable set to? Run this: echo $KUBECONFIG

This may remedy the problem, but replace "verycool" with the name of your cluster:

export KUBECONFIG=$KUBECONFIG:~/.kube/config-verycool

(You may want to do this: cd ~/.kube and run ls -lh.)

Possible Solution #2 (for GCP only)
1. Log into the web UI for GCP.
2. Search for "kubernetes engine".
3. Find the clusters that exist.
4. Mentally identify the name (e.g., standard-cluster-1) of the cluster and the region (e.g., us-central1-a).
5. In the upper righthand corner click on the icon ">_" (to activate the shell).
6. Stop the VM.
7. Click on the hyperlinked name of the VM.
8. Click "Edit"
9. Check the option to "Allow full access to all Cloud APIs" (unless the VM was created with the configuration such that it can run gcloud commands governing the Kubernetes engine).
10. Click Save.
11. Turn the VM on.
12. From the VM run this command (but substitute standard-cluster1 for the name of your cluster): gcloud container clusters get-credentials standard-cluster-1 --region us-central1-a

Possible Solution #3 (for EKS)
If you are running EKS (in AWS), see this posting.

How Do You Find the Security Group ID Values in AWS?

Problem scenario
You want to list the Security Group ID value in AWS.

Solution
Prerequisite
Install and configure the AWS CLI; if you need assistance, see this posting if you can you the pip command and you are using Ubuntu. If you cannot use the pip command or you are not using Ubuntu, see this posting.

Procedures
Run this command:
aws ec2 describe-security-groups | grep GroupId