Skip to content

Commit

Permalink
Update azd hooks (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
justinyoo authored Jan 2, 2025
1 parent 7ae34f8 commit 593897e
Show file tree
Hide file tree
Showing 13 changed files with 419 additions and 150 deletions.
1 change: 1 addition & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"GitHub.copilot-chat",
"GitHub.vscode-github-actions",
"GitHub.vscode-pull-request-github",
"ms-azuretools.vscode-azure-github-copilot",
"ms-azuretools.vscode-bicep",
"ms-azuretools.vscode-docker",
"ms-dotnettools.csharp",
Expand Down
2 changes: 1 addition & 1 deletion .devcontainer/on-create.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
sudo apt-get update && \
sudo apt upgrade -y && \
sudo apt-get install -y dos2unix libsecret-1-0 xdg-utils && \
sudo apt-get install -y dos2unix libsecret-1-0 xdg-utils uuid-runtime && \
sudo apt clean -y && \
sudo rm -rf /var/lib/apt/lists/*

Expand Down
48 changes: 48 additions & 0 deletions infra/hooks/deploy_swa.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/bin/bash

# Runs the deploy_swa script
# It does the following:
# 1. Loads the azd environment variables
# 2. Logs in to the Azure CLI if not running in a GitHub Action
# 3. Build SWA app
# 4. Deploy SWA app

set -e

# REPOSITORY_ROOT=$(git rev-parse --show-toplevel)
REPOSITORY_ROOT="$(dirname "$(realpath "$0")")/../.."

# Load the azd environment variables
source "$REPOSITORY_ROOT/infra/hooks/load_azd_env.sh"

if [ -z "$GITHUB_WORKSPACE" ]; then
# The GITHUB_WORKSPACE is not set, meaning this is not running in a GitHub Action
source "$REPOSITORY_ROOT/infra/hooks/login.sh"
fi

# Run only if GITHUB_WORKSPACE is NOT set - this is NOT running in a GitHub Action workflow
if [ -z "$GITHUB_WORKSPACE" ]; then
echo "Deploying to Azure Static Web Apps..."

RESOURCE_GROUP="rg-$AZURE_ENV_NAME"
STATICAPP_NAME=$AZURE_RESOURCE_EASYAUTH_STATICAPP_NAME

# Build SWA app
swa build

# Get deployment token
deploymentToken=$(az staticwebapp secrets list \
--resource-group "$RESOURCE_GROUP" \
--name "$STATICAPP_NAME" \
--query "properties.apiKey" -o tsv)

# Deploy SWA app
swa deploy \
--api-location src/EasyAuth.FunctionApp/bin/Release/net9.0 \
--env Production \
-d "$deploymentToken"

echo "...Done"
else
echo "Skipping to deploy the application Azure Static Web Apps..."
fi
64 changes: 43 additions & 21 deletions infra/hooks/load_azd_env.sh
Original file line number Diff line number Diff line change
@@ -1,21 +1,43 @@
# Loads the azd .env file into the current environment
# It does the following:
# 1. Loads the azd .env file from the current environment

Param(
[switch]
[Parameter(Mandatory=$false)]
$ShowMessage
)

if ($ShowMessage) {
Write-Host "Loading azd .env file from current environment" -ForegroundColor Cyan
}

foreach ($line in (& azd env get-values)) {
if ($line -match "([^=]+)=(.*)") {
$key = $matches[1]
$value = $matches[2] -replace '^"|"$'
[Environment]::SetEnvironmentVariable($key, $value)
}
}
#!/bin/bash

set -e

SHOW_MESSAGE=false

if [[ $# -eq 0 ]]; then
SHOW_MESSAGE=false
fi

while [[ "$1" != "" ]]; do
case $1 in
-m | --show-message)
SHOW_MESSAGE=true
;;

*)
usage
exit 1
;;
esac

shift
done

if [[ $SHOW_MESSAGE == true ]]; then
echo -e "\033[0;36mLoading azd .env file from current environment...\033[0m"
fi

# while IFS='=' read -r key value; do
# value=$(echo "$value" | sed 's/^"//' | sed 's/"$//')
# export "$key=$value"
# done <<EOF
# $(azd env get-values)
# EOF

while IFS= read -r line; do
if [[ $line =~ ^([^=]+)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]//\"}"
export "$key"="$value"
fi
done < <(azd env get-values)
89 changes: 46 additions & 43 deletions infra/hooks/login.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/bin/bash

# Logs in to Azure through AZD and AZ CLI
# It does the following:
# 1. Checks if the user is logged in to Azure
Expand All @@ -8,61 +10,62 @@
# 6. Sets the active subscription to the selected subscription
# 7. Exits if the subscription is not found

# $REPOSITORY_ROOT = git rev-parse --show-toplevel
$REPOSITORY_ROOT = "$(Split-Path $MyInvocation.MyCommand.Path)/../.."
set -e

# REPOSITORY_ROOT=$(git rev-parse --show-toplevel)
REPOSITORY_ROOT="$(dirname "$(realpath "$0")")/../.."

# Load the azd environment variables
& "$REPOSITORY_ROOT/infra/hooks/load_azd_env.ps1"
"$REPOSITORY_ROOT/infra/hooks/load_azd_env.sh"

# AZD LOGIN
# Check if the user is logged in to Azure
$login_status = azd auth login --check-status
login_status=$(azd auth login --check-status)

# Check if the user is not logged in
if ($login_status -like "*Not logged in*") {
Write-Host "Not logged in, initiating login process..."
# Command to log in to Azure
azd auth login
}
if [[ "$login_status" == *"Not logged in"* ]]; then
echo "Not logged in, initiating login process..."
# Command to log in to Azure
azd auth login
fi

# AZ LOGIN
$EXPIRED_TOKEN = az ad signed-in-user show --query 'id' -o tsv 2>$null
EXPIRED_TOKEN=$(az ad signed-in-user show --query 'id' -o tsv 2>/dev/null || true)

if ([string]::IsNullOrEmpty($EXPIRED_TOKEN)) {
if [[ -z "$EXPIRED_TOKEN" ]]; then
az login --scope https://graph.microsoft.com/.default -o none
}
fi

if ([string]::IsNullOrEmpty($env:AZURE_SUBSCRIPTION_ID)) {
$ACCOUNT = az account show --query '[id,name]'
Write-Host "You can set the `AZURE_SUBSCRIPTION_ID` environment variable with `azd env set AZURE_SUBSCRIPTION_ID`."
Write-Host $ACCOUNT
if [[ -z "${AZURE_SUBSCRIPTION_ID:-}" ]]; then
ACCOUNT=$(az account show --query '[id,name]')
echo "You can set the \`AZURE_SUBSCRIPTION_ID\` environment variable with \`azd env set AZURE_SUBSCRIPTION_ID\`."
echo $ACCOUNT

$response = Read-Host "Do you want to use the above subscription? (Y/n) "
$response = if ([string]::IsNullOrEmpty($response)) { "Y" } else { $response }
switch ($response) {
{ $_ -match "^[yY](es)?$" } {
# Do nothing
break
}
default {
Write-Host "Listing available subscriptions..."
$SUBSCRIPTIONS = az account list --query 'sort_by([], &name)' --output json
Write-Host "Available subscriptions:"
Write-Host ($SUBSCRIPTIONS | ConvertFrom-Json | ForEach-Object { "{0} {1}" -f $_.name, $_.id } | Format-Table)
$subscription_input = Read-Host "Enter the name or ID of the subscription you want to use: "
$AZURE_SUBSCRIPTION_ID = ($SUBSCRIPTIONS | ConvertFrom-Json | Where-Object { $_.name -eq $subscription_input -or $_.id -eq $subscription_input } | Select-Object -exp id)
if (-not [string]::IsNullOrEmpty($AZURE_SUBSCRIPTION_ID)) {
Write-Host "Setting active subscription to: $AZURE_SUBSCRIPTION_ID"
read -r -p "Do you want to use the above subscription? (Y/n) " response
response=${response:-Y}
case "$response" in
[yY][eE][sS]|[yY])
;;
*)
echo "Listing available subscriptions..."
SUBSCRIPTIONS=$(az account list --query 'sort_by([], &name)' --output json)
echo "Available subscriptions:"
echo "$SUBSCRIPTIONS" | jq -r '.[] | [.name, .id] | @tsv' | column -t -s $'\t'
read -r -p "Enter the name or ID of the subscription you want to use: " subscription_input
AZURE_SUBSCRIPTION_ID=$(echo "$SUBSCRIPTIONS" | jq -r --arg input "$subscription_input" '.[] | select(.name==$input or .id==$input) | .id')
if [[ -n "$AZURE_SUBSCRIPTION_ID" ]]; then
echo "Setting active subscription to: $AZURE_SUBSCRIPTION_ID"
az account set -s $AZURE_SUBSCRIPTION_ID
}
else {
Write-Host "Subscription not found. Please enter a valid subscription name or ID."
else
echo "Subscription not found. Please enter a valid subscription name or ID."
exit 1
}
break
}
}
}
else {
az account set -s $env:AZURE_SUBSCRIPTION_ID
}
fi
;;
*)
echo "Use the \`az account set\` command to set the subscription you'd like to use and re-run this script."
exit 0
;;
esac
else
az account set -s $AZURE_SUBSCRIPTION_ID
fi
2 changes: 1 addition & 1 deletion infra/hooks/postdeploy.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Runs the post-deploy script after the environment is provisioned
# Runs the post-deploy script after the apps are deployed
# It does the following:
# 1. Loads the azd environment variables
# 2. Logs in to the Azure CLI if not running in a GitHub Action
Expand Down
17 changes: 17 additions & 0 deletions infra/hooks/postdeploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash

# Runs the post-deploy script after the apps are deployed
# It does the following:
# 1. Loads the azd environment variables
# 2. Logs in to the Azure CLI if not running in a GitHub Action
# 3. Deploys the application to Azure Static Web Apps

set -e

echo "Running post-deploy script..."

# REPOSITORY_ROOT=$(git rev-parse --show-toplevel)
REPOSITORY_ROOT="$(dirname "$(realpath "$0")")/../.."

# Deploy SWA app
"$REPOSITORY_ROOT/infra/hooks/deploy_swa.sh"
16 changes: 10 additions & 6 deletions infra/hooks/postprovision.sh
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
# Runs the post-provision script after the environment is provisioned
#!/bin/bash

# Runs the post-provision script before the environment is provisioned
# It does the following:
# 1. Loads the azd environment variables
# 2. Logs in to the Azure CLI if not running in a GitHub Action
# 3. Updates the application on Microsoft Entra ID

Write-Host "Running pre-provision script..."
set -e

echo "Running post-provision script..."

# $REPOSITORY_ROOT = git rev-parse --show-toplevel
$REPOSITORY_ROOT = "$(Split-Path $MyInvocation.MyCommand.Path)/../.."
# REPOSITORY_ROOT=$(git rev-parse --show-toplevel)
REPOSITORY_ROOT="$(dirname "$(realpath "$0")")/../.."

# Update the Entra ID application
& "$REPOSITORY_ROOT/infra/hooks/update_app.ps1"
# Update the Entra ID application in Azure
"$REPOSITORY_ROOT/infra/hooks/update_app.sh"
77 changes: 9 additions & 68 deletions infra/hooks/preprovision.sh
Original file line number Diff line number Diff line change
@@ -1,76 +1,17 @@
#!/bin/bash

# Runs the pre-provision script before the environment is provisioned
# It does the following:
# 1. Loads the azd environment variables
# 2. Logs in to the Azure CLI if not running in a GitHub Action
# 3. Registers the application on Microsoft Entra ID

Write-Host "Running pre-provision script..."

# $REPOSITORY_ROOT = git rev-parse --show-toplevel
$REPOSITORY_ROOT = "$(Split-Path $MyInvocation.MyCommand.Path)/../.."

# Load the azd environment variables
& "$REPOSITORY_ROOT/infra/hooks/load_azd_env.ps1" -ShowMessage

if ([string]::IsNullOrEmpty($env:GITHUB_WORKSPACE)) {
# The GITHUB_WORKSPACE is not set, meaning this is not running in a GitHub Action
& "$REPOSITORY_ROOT/infra/hooks/login.ps1"
}

$AZURE_ENV_NAME = $env:AZURE_ENV_NAME

# Run only if GITHUB_WORKSPACE is NOT set - this is NOT running in a GitHub Action workflow
if ([string]::IsNullOrEmpty($env:GITHUB_WORKSPACE)) {
Write-Host "Registering the application in Azure..."

# Create a service principal
$appId = $env:AZURE_CLIENT_ID
if ([string]::IsNullOrEmpty($appId)) {
$appId = az ad app list --display-name "spn-$AZURE_ENV_NAME" --query "[].appId" -o tsv
if ([string]::IsNullOrEmpty($appId)) {
$appId = az ad app create --display-name spn-$AZURE_ENV_NAME --query "appId" -o tsv
$spnId = az ad sp create --id $appId --query "id" -o tsv
}
}

$spnId = az ad sp list --display-name "spn-$AZURE_ENV_NAME" --query "[].id" -o tsv
if ([string]::IsNullOrEmpty($spnId)) {
$spnId = az ad sp create --id $appId --query "id" -o tsv
}

$objectId = az ad app show --id $appId --query "id" -o tsv

# Add client secret to the app
$clientSecret = az ad app credential reset --id $appId --display-name "default" --append

# Add identifier URIs to the app
$identifierUris = @( "api://$appId" )

# Add API scopes to the app
$api = @{
acceptMappedClaims = $null;
knownClientApplications = @();
requestedAccessTokenVersion = $null;
oauth2PermissionScopes = @(
@{
type = "User";
value = "user_impersonation";
adminConsentDisplayName = "Access EasyAuth apps";
adminConsentDescription = "Allows users to access apps using EasyAuth";
isEnabled = $true;
}
)
}
set -e

$payload = @{ $identifierUris = $identifierUris; api = $api } | ConvertTo-Json -Depth 100 -Compress | ConvertTo-Json
echo "Running pre-provision script..."

az rest -m PATCH `
--uri "https://graph.microsoft.com/v1.0/applications/$objectId" `
--headers Content-Type=application/json `
--body $payload
# REPOSITORY_ROOT=$(git rev-parse --show-toplevel)
REPOSITORY_ROOT="$(dirname "$(realpath "$0")")/../.."

# Set the environment variables
azd env set AZURE_PRINCIPAL_ID $appId
azd env set AZURE_PRINCIPAL_SECRET $clientSecret
} else {
Write-Host "Skipping to register the application in Azure..."
}
# Register the Entra ID application in Azure
"$REPOSITORY_ROOT/infra/hooks/register_app.sh"
Loading

0 comments on commit 593897e

Please sign in to comment.