<file_sep>#!/bin/bash

var_file='demo-redhat-variables-scott.json'
packer_file='demo-redhat.json'

function capture_var() {
    val=$(cat $var_file | jq .$1 | tail -c +2 | head -c -2)
    echo $val
}

service_principal_client_id=$(capture_var service_principal_client_id)
service_principal_client_secret=$(capture_var service_principal_client_secret)
azure_ad_tenant_id=$(capture_var azure_ad_tenant_id)
azure_subscription_id=$(capture_var azure_subscription_id)
resource_group_name=$(capture_var resource_group_name)
resource_group_location=$(capture_var resource_group_location)
azure_storage_account=$(capture_var azure_storage_account)
echo "Logging in"
az login --service-principal -u $service_principal_client_id -p $service_principal_client_secret --tenant $azure_ad_tenant_id

# Check if the needed resource group has been created
echo "Making sure that the resource group $resource_group_name exists"

if [[ "false" == $(az group exists -n $resource_group_name) ]]; then
    echo "Creating resource group"
    az group create -l $resource_group_location -n $resource_group_name
fi

if [[ "true" == $(az storage account check-name --name $azure_storage_account --query nameAvailable) ]]; then
    echo "Creating storage account"
    az storage account create \
        -n $azure_storage_account \
        -g $resource_group_name \
        -l $resource_group_location \
        --sku Standard_LRS
fi

echo "Building packer image"
packer build -var-file=$var_file -force $packer_file

az logout
<file_sep>#!/bin/bash
echo "Running deploy.sh"
# Setup error handling
tempfiles=( )
cleanup() {
  rm -f "${tempfiles[@]}"
}
trap cleanup 0

error() {
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi

  exit "${code}"
}
trap 'error ${LINENO}' ERR

echo "Checking terraform"
if [[ ! -d ".terraform" ]]; then
    terraform init
fi

# Load the config 
echo "Loading config"
. variables.conf
resource_group_name=$(echo $base_name)rg

# Login as the service principal
echo "Getting the connection string"
#az login --service-principal -u $service_principal_id -p $service_principal_secret --tenant $azure_ad_tenant_id
az account set -s $azure_subscription_id
storage_connection_string=$(az storage account show-connection-string --name $vhd_storage_account --query connectionString --output tsv)

# Pull the most recent VHD
echo "Getting the most recent VHD"
latest_vhd=$(az storage blob list --account-name $vhd_storage_account \
                                  --container-name $vhd_storage_container \
                                  --auth-mode key \
                                  --connection-string $storage_connection_string \
                                  --prefix $vhd_path \
                                  --query '[].{name: name, create: properties.creationTime}' --output tsv \
              | grep -F '.vhd' \
              | sort -k2 -r \
              | head -n 1 \
              | cut -f1)
echo "Found $latest_vhd"

# Generate a SAS URI which expires 1 month from today
echo "Generating SAS URI"
expiry_date=$(date -d "+1 month" --iso-8601)
source_vhd=$(az storage blob generate-sas --account-name $vhd_storage_account \
                                          --container-name $vhd_storage_container \
                                          --auth-mode key \
                                          --connection-string $storage_connection_string \
                                          --name $latest_vhd \
                                          --permissions r \
                                          --expiry $expiry_date \
                                          --full-uri \
                                          --output tsv)

if [[ $(az vm list -g $resource_group_name --query '[].name' --output tsv | wc -l) != "0" ]]; then
  echo "Deleting vm $(echo $base_name)vm"
  az vm delete --name $(echo $base_name)vm \
               --resource-group $resource_group_name \
               --yes
  
  echo "Deleting VHD images"
  vhds_storage_connection_string=$(az storage account show-connection-string --name $stg_account_name --query connectionString --output tsv)
  az storage container delete --name vhds --connection-string $vhds_storage_connection_string 

  echo "Pausing for 60s. When deleting a container, the system can take a bit to fully remove the resource.."
  for i in {1..60}
    do
      echo -ne "$i.."\\r
      sleep 1s
    done
fi

terraform apply -auto-approve -var="azure_ad_tenant_id=$azure_ad_tenant_id" \
                              -var="azure_subscription_id=$azure_subscription_id" \
                              -var="base_name=$base_name" \
                              -var="location=$resource_group_location" \
                              -var="source_vhd=$source_vhd" \
                              -var="stg_account_name=$stg_account_name"

echo "Creating VM"

az vm create --name $(echo $base_name)vm \
             --resource-group $resource_group_name \
             --os-type Windows \
             --use-unmanaged-disk \
             --admin-username $admin_username \
             --admin-password $<PASSWORD> \
             --image "https://$stg_account_name.blob.core.windows.net/vhd/$base_name.vhd" \
             --nics $(echo $base_name)Nic \
             --storage-account $stg_account_name \
             --storage-container-name vhds \
             --size $vm_sku


#az logout<file_sep>#!/bin/bash

# Run this script as root via sudo. If you don't, most of the script fails.
# This script makes the following assumptions:
# 1. The VHD starts with 2 partitions on /dev/sda
# 2. The os-disk-size was set to 128 GB
# 3. The LVM should use all remaining space (~95GB)
# 
# So, if you use this script, validate these assumptions. If you use
# the script blindly, bad things may happen.

# set the directory to map all the new space to
map_dir=/usr/mydata

# This bit assumes that the empty space is on sda3. If that's wrong, 
# change the device_id.
device_id=/dev/sda
device_num=3
device_path=$(echo $device_id$device_num)

# First, determine what the last block is on the device.
last_block=$(fdisk -l $device_id | grep 'sda2' | awk '{ print $3 }')

# Create the string to start the new partition on the next 
# blank spot. 
new_block=$(($last_block + 1))
new_block_string=$(echo "$new_block"s)

# Create the partition
parted -a optimal -s $device_id mkpart primary $new_block_string 100%

# Set the partition as an LVM volume
parted $device_id set $device_num lvm on

# Create the physical volume
pvcreate $device_path

# Extend rootvg to this volume
# This bit exercises assumption 1
vgextend rootvg $device_path
lvcreate -L 95GB -n mydatalv rootvg

# Set the file system
mkfs -t ext4 /dev/rootvg/mydatalv

# Create the mount point
mkdir $map_dir

# Note: echoing directly to /etc/fstab did not work, so we do it locally.
cp /etc/fstab .
chmod 666 fstab

# Edit the fstab file so that things mount every time.
echo -e "/dev/mapper/rootvg-mydatalv\t$map_dir\text4\tdefaults\t0 0" >> fstab

# Copy the edits back
chmod 644 fstab
cp fstab /etc/fstab
rm fstab

# Extra, if needed: make sure the LVM is mounted, it will auto-mount on reboot
mount $map_dir<file_sep>last_block=$(sudo fdisk -l /dev/sda | grep 'sda2' | awk '{ print $3 }')
            
# Create the string to start the new partition on the next 
# blank spot. 
new_block=$(($last_block + 1))
new_block_string=$(echo "$new_block"s)

# Create the partition
sudo parted -a optimal -s /dev/sda mkpart primary $new_block_string 100%

# Set the partition as an LVM volume
sudo parted /dev/sda set 3 lvm on

# Create the physical volume
sudo pvcreate /dev/sda3

# Extend rootvg to this volume
sudo vgextend rootvg /dev/sda3
sudo lvcreate -L 95GB -n fioranolv rootvg

# Set the file system
sudo mkfs -t ext4 /dev/rootvg/fioranolv

# Create the mount point
sudo mkdir /var/fiorano

# Note: echoing directly to /etc/fstab did not work, so we do it locally.
sudo cp /etc/fstab .
sudo chmod 666 fstab

# Edit the fstab file so that things mount every time.
sudo echo -e "/dev/mapper/rootvg-fioranolv\t/var/fiorano\text4\tdefaults\t0 0" >> fstab

# Copy the edits back
sudo chmod 644 fstab
sudo cp fstab /etc/fstab
sudo rm fstab

# Extra, if needed: make sure the LVM is mounted, it will auto-mount on reboot
sudo mount /var/fiorano<file_sep># Requirements

Must have Azure CLI and jq installed.
* Azure CLI: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-apt?view=azure-cli-latest
* jq: https://stedolan.github.io/jq/download/

Next, login to your Azure account:
>az login
>az account set -s <subscription id>

Now, create a Service Principal to handle the login (and capture the output for this command! You can't retrieve the generated password later). Documentation for this is found at https://docs.microsoft.com/cli/azure/create-an-azure-service-principal-azure-cli?view=azure-cli-latest:

>az ad sp create-for-rbac --name ServicePrincipalName

From the output of the previous step, update demo-centos-variables.json such that the variables are appropriate for your environment. 

Finally, run packvm.sh. This will create the VM as you require. 

You can now adapt the packer file, demo-centos.json, to your requirements. 

# Updating the base image:

The following command lists the CentOS images published by OpenLogic:

>az vm image list --location centralus --publisher OpenLogic --all

Finally, when updating an existing VM offer on Azure, follow [these guidelines](https://docs.microsoft.com/azure/marketplace/cloud-partner-portal/virtual-machine/cpp-update-existing-offer#common-update-operations).<file_sep>#!/bin/bash

# Run this script as root via sudo. If you don't, most of the script fails.
# This script makes the following assumptions:
# Set a label on the device
# TODO: discover the device, don't hard code it. This flows 
#   through the rest of the script. Reason: a data disk may sometimes attach
#   as /dev/sda or other letters too. The assumptions in this sample are bad 
#   for production.
parted /dev/sdc mklabel msdos

# Create the partition
parted -a optimal -s /dev/sdc mkpart primary 1 100%

# Set the partition as an LVM volume
parted /dev/sdc set 1 lvm on

# Create the physical volume
pvcreate /dev/sdc1

# Extend rootvg to this volume
vgextend rootvg /dev/sdc1
lvcreate -L 127GB -n datavol rootvg

# Set the file system
mkfs -t ext4 /dev/rootvg/datavol

# Create the mount point
mkdir /var/datavol

# Note: echoing directly to /etc/fstab did not work, so we do it locally.
cp /etc/fstab .
chmod 666 fstab

# Get blkid of rootvg-datavols
datavol=$(blkid | grep 'rootvg-datavol')
startuuid=$(echo $datavol | \grep -aob '"' | head -n1 | cut -d: -f1)
enduuid=$(echo $datavol | \grep -aob '"' | head -n2 | tail -n1 | cut -d: -f1)
let "startuuid = $startuuid +1"
let "enduuid = $enduuid - $startuuid"
blockid=$(echo ${datavol:$startuuid:$enduuid})

# Edit the fstab file so that things mount every time.
echo -e "UUID=$blockid\t/var/datavol\text4\tdefaults,nofail\t1" >> fstab

# Copy the edits back
chmod 644 fstab
cp fstab /etc/fstab
rm fstab

# Extra, if needed: make sure the LVM is mounted, it will auto-mount on reboot
mount /var/datavol

